Compare commits
434 Commits
fix-readab
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 7ace1e2219 | |||
|
|
1e18e0bc98 | ||
|
|
844d8a0708 | ||
|
|
9078c7ff30 | ||
|
|
1ffa091fde | ||
|
|
189bb295a5 | ||
|
|
7773fa02bb | ||
|
|
49bcb91fc4 | ||
|
|
4b2d6097c4 | ||
|
|
6a99b8af8c | ||
|
|
8c5274bbe8 | ||
|
|
6207540804 | ||
|
|
e9099062ff | ||
|
|
84073b7728 | ||
|
|
928e0e86b6 | ||
|
|
0f7bca7720 | ||
|
|
3613ad5370 | ||
|
|
a5a89d87cb | ||
|
|
9e59515381 | ||
|
|
82dcc24014 | ||
|
|
094eebfc8c | ||
|
|
d8849dbda4 | ||
|
|
36c909de2b | ||
|
|
5d6db07de8 | ||
|
|
0e2df24cc8 | ||
|
|
3bc9a50795 | ||
|
|
12070f4517 | ||
|
|
ab1dc4c366 | ||
|
|
5f36368add | ||
|
|
1ed521665f | ||
|
|
df974c9f22 | ||
|
|
a551c866e4 | ||
|
|
668be3f659 | ||
|
|
59807b1166 | ||
|
|
7b3cb5fa08 | ||
|
|
6e5bf1d94a | ||
|
|
ae60f94d27 | ||
|
|
551fce4b41 | ||
|
|
ebb2bbe2eb | ||
|
|
7ed65d03b5 | ||
|
|
af35a11a48 | ||
|
|
51faa6eb34 | ||
|
|
f74fe8fa46 | ||
|
|
8c0c9ca479 | ||
|
|
3d31da901e | ||
|
|
0b0eab6e62 | ||
|
|
868b6d2e09 | ||
|
|
ef6ab3eb47 | ||
|
|
7bf9d488af | ||
|
|
a99bdef7d4 | ||
|
|
efe7085836 | ||
|
|
d1c85d8822 | ||
|
|
9d5f64667d | ||
|
|
008a54a46e | ||
|
|
c58f2236ae | ||
|
|
d10b2593c7 | ||
|
|
751bcc0585 | ||
|
|
0f0a27eaba | ||
|
|
e2b3206acf | ||
|
|
03e1c5e1a8 | ||
|
|
6626af4d54 | ||
|
|
db91b60cac | ||
|
|
b7a01da071 | ||
|
|
2a7acc83ca | ||
|
|
86fa47b25f | ||
|
|
30c64ea694 | ||
|
|
ba5b290932 | ||
|
|
e369445190 | ||
|
|
493b1ee0f5 | ||
|
|
ab7d385a86 | ||
|
|
a37a15e325 | ||
|
|
13128db012 | ||
|
|
96ad8f715b | ||
|
|
ae2842b521 | ||
|
|
dc1ab04357 | ||
|
|
0633c3f7d8 | ||
|
|
97691812b0 | ||
|
|
896e828fa3 | ||
|
|
4526d733e2 | ||
|
|
d9abf8a179 | ||
|
|
6b76f7f531 | ||
|
|
e72b926858 | ||
|
|
8f21e04c6d | ||
|
|
41a67b02bd | ||
|
|
5e77e3b84c | ||
|
|
458a0e36ec | ||
|
|
527a19ba8d | ||
|
|
c9cfc7ddc2 | ||
|
|
97d7a29dea | ||
|
|
af4a16b3f2 | ||
|
|
314309f3d7 | ||
|
|
11914d262c | ||
|
|
2fac551b82 | ||
|
|
e6d3fad24e | ||
|
|
5eeea88e02 | ||
|
|
e019a3e624 | ||
|
|
e4a89b4d19 | ||
|
|
35769812ab | ||
|
|
5ab71fa1b1 | ||
|
|
5bb9853523 | ||
|
|
781c41eda7 | ||
|
|
94bd7857c7 | ||
|
|
086e2fee4e | ||
|
|
bdb5434844 | ||
|
|
733dc3734f | ||
|
|
f980f9fd96 | ||
|
|
24d932acc8 | ||
|
|
a2f4d754d8 | ||
|
|
b5056f8d21 | ||
|
|
32a379c426 | ||
|
|
ba4c8be202 | ||
|
|
7ff050861a | ||
|
|
ed6f639ca7 | ||
|
|
ee4b7fbcb7 | ||
|
|
ec6aeb777a | ||
|
|
2675e75b0b | ||
|
|
149e08a36f | ||
|
|
bca221f491 | ||
|
|
bd8e1d4883 | ||
|
|
7ac0d4bbaa | ||
|
|
a3ecb974de | ||
|
|
c6c1fee3e3 | ||
|
|
05b1de9edb | ||
|
|
0edfcbc714 | ||
|
|
826fb928c6 | ||
|
|
325c65462d | ||
|
|
734b6a81db | ||
|
|
9fbae82a04 | ||
|
|
ce7128f662 | ||
|
|
2eb95cf16c | ||
|
|
36c183969b | ||
|
|
898b6fa683 | ||
|
|
920d0c2d6b | ||
|
|
6ab8bba1ef | ||
|
|
7272eecacf | ||
|
|
7a0f74e139 | ||
|
|
87f15b399a | ||
|
|
e507c49ad1 | ||
|
|
c81e9ddde5 | ||
|
|
4f63ec83e7 | ||
|
|
9b572f8657 | ||
|
|
7011775cca | ||
|
|
16e0aae620 | ||
|
|
f118c3537e | ||
|
|
8ded7f889d | ||
|
|
278a9b2b27 | ||
|
|
5a987910e5 | ||
|
|
677a63e292 | ||
|
|
4b4a3384b2 | ||
|
|
fe80a08830 | ||
|
|
6cb0967df2 | ||
|
|
04832705bd | ||
|
|
f000ee64d4 | ||
|
|
fc8ac44067 | ||
|
|
e5b0791fcc | ||
|
|
49f61aa9fe | ||
|
|
b03f8ee6ec | ||
|
|
1fd5ae81f0 | ||
|
|
1c9d452a82 | ||
|
|
32adbbd5c9 | ||
|
|
779c4a0ce1 | ||
|
|
b441ca3c39 | ||
|
|
e6e61156d2 | ||
|
|
e242b63b00 | ||
|
|
b4fb563be9 | ||
|
|
a4e0e3d313 | ||
|
|
783a83fd8b | ||
|
|
0d03875852 | ||
|
|
aa02e659e3 | ||
|
|
44b55fdbcc | ||
|
|
eb2f0c0441 | ||
|
|
7fa0fd0c78 | ||
|
|
1ff4022cce | ||
|
|
11b278a565 | ||
|
|
5a65ff5d08 | ||
|
|
6f26767084 | ||
|
|
469169b3d9 | ||
|
|
af6bdcae26 | ||
|
|
e00cc74f4c | ||
|
|
efb1bca8b4 | ||
|
|
406d62654d | ||
|
|
d816b7b1a1 | ||
|
|
c8562c7239 | ||
|
|
29a0143565 | ||
|
|
42929e8c82 | ||
|
|
cf8bbb4c33 | ||
|
|
4a2fc4fcba | ||
|
|
f532003ea3 | ||
|
|
866b795490 | ||
|
|
595f262621 | ||
|
|
99a9b201bf | ||
|
|
c059ccd999 | ||
|
|
002838c377 | ||
|
|
499dcecd40 | ||
|
|
59193360c9 | ||
|
|
1474d8d2a9 | ||
|
|
a1c05405d3 | ||
|
|
5a38078bd9 | ||
|
|
903e468ee9 | ||
|
|
6e4bf253d9 | ||
|
|
102910d103 | ||
|
|
dae02709a3 | ||
|
|
721b8db155 | ||
|
|
3d12f08399 | ||
|
|
fb4084dc2f | ||
|
|
33f84fa77b | ||
|
|
8b05da9076 | ||
|
|
06abb82397 | ||
|
|
ea102e17b4 | ||
|
|
df30e5b6e1 | ||
|
|
14301f6bb4 | ||
|
|
60c69fd6db | ||
|
|
4018aa491c | ||
|
|
6ffc43f145 | ||
|
|
3fdaf6a4b0 | ||
|
|
98d1dafdde | ||
|
|
132859b883 | ||
|
|
905ed34a7d | ||
|
|
16fa3e0550 | ||
|
|
f0c0a17694 | ||
|
|
2a847f996b | ||
|
|
61738bef6c | ||
|
|
6fd304c388 | ||
|
|
8e5b2bd79d | ||
|
|
1a2c1a9685 | ||
|
|
db4f47e68a | ||
|
|
0bfdd67b3a | ||
|
|
acc057ed3c | ||
|
|
b9d25da577 | ||
|
|
c05a057cd8 | ||
|
|
ab1afc567f | ||
|
|
d6d2a2559b | ||
|
|
e3fbd67d0b | ||
|
|
efd38f16ae | ||
|
|
7fe2ebd4f6 | ||
|
|
e9267df9f5 | ||
|
|
3ec6a794c2 | ||
|
|
4f3274df15 | ||
|
|
cb038f48d3 | ||
|
|
7226b4d2a0 | ||
|
|
10a247040e | ||
|
|
a2aa428d2a | ||
|
|
98352a182a | ||
|
|
7f4603001f | ||
|
|
70e263d51a | ||
|
|
c9556b6873 | ||
|
|
3aa12f1c1b | ||
|
|
3689245892 | ||
|
|
0499c7477c | ||
|
|
d9413e377f | ||
|
|
43c1c64f43 | ||
|
|
13d1ee7d0f | ||
|
|
c2a1dd5ac3 | ||
|
|
fdba946572 | ||
|
|
5e07b1babd | ||
|
|
2590b44acf | ||
|
|
411cc713b2 | ||
|
|
a83375eedd | ||
|
|
292d29fdf0 | ||
|
|
4d22beb569 | ||
|
|
25fe0b30b2 | ||
|
|
d77a5ac1a4 | ||
|
|
8ce0f510ef | ||
|
|
a5672d9861 | ||
|
|
d4cad84a73 | ||
|
|
6430abaa15 | ||
|
|
ea67682892 | ||
|
|
047ab9c57e | ||
|
|
6c6cc811f8 | ||
|
|
1a9af8bcc9 | ||
|
|
4ca41430b8 | ||
|
|
a121ffd8e5 | ||
|
|
f42caab156 | ||
|
|
d129de8842 | ||
|
|
0b925daba6 | ||
|
|
2e68d5c336 | ||
|
|
e4efd1ac06 | ||
|
|
9c5811f1a9 | ||
|
|
4b8f5ac9eb | ||
|
|
debe4f1388 | ||
|
|
704f318ad7 | ||
|
|
2ff71cb90e | ||
|
|
427e2726d4 | ||
|
|
0192f71228 | ||
|
|
69ff37759f | ||
|
|
c5756e44ab | ||
|
|
b2c624b904 | ||
|
|
dcb611181b | ||
|
|
86f3d2ff8a | ||
|
|
7bdd121102 | ||
|
|
ee32f046cb | ||
|
|
f8d7908975 | ||
|
|
c9ea251d8c | ||
|
|
79c662baf3 | ||
|
|
a259f020b5 | ||
|
|
9d47f5c434 | ||
|
|
66aa36d942 | ||
|
|
854695c5ec | ||
|
|
79a3e70905 | ||
|
|
ae77f9fac7 | ||
|
|
2c890a900b | ||
|
|
2ccd639aed | ||
|
|
ded358b15f | ||
|
|
91d65c8e3f | ||
|
|
03e3dad546 | ||
|
|
fa11ad232a | ||
|
|
9646a066c0 | ||
|
|
4aa82d43f0 | ||
|
|
b7fd990a22 | ||
|
|
9f91dfe0ef | ||
|
|
3f34600708 | ||
|
|
83904d3ee7 | ||
|
|
a2fb82261a | ||
|
|
75091f968f | ||
|
|
23567280ce | ||
|
|
18bce5f457 | ||
|
|
c160ab8ff5 | ||
|
|
44d1f48838 | ||
|
|
dec371cb05 | ||
|
|
124d4d9627 | ||
|
|
f0a51a71d4 | ||
|
|
3b3036f69b | ||
|
|
dca8980c5b | ||
|
|
a93e76cbca | ||
|
|
c7cda0d25d | ||
|
|
571e41cfb5 | ||
|
|
f6bc475ae0 | ||
|
|
559e8e0bf7 | ||
|
|
d722782934 | ||
|
|
fdaa45c717 | ||
|
|
8902f9de94 | ||
|
|
39ddd9b14c | ||
|
|
c69102b085 | ||
|
|
b7285a49e1 | ||
|
|
7fa3ed378d | ||
|
|
963a5bb918 | ||
|
|
42688c757a | ||
|
|
6d68c6083f | ||
|
|
b98aafa030 | ||
|
|
4edec1a5cf | ||
|
|
934444e6e7 | ||
|
|
e832e97599 | ||
|
|
008dee2fc0 | ||
|
|
0b644132f7 | ||
|
|
272ea322cc | ||
|
|
f5109f5898 | ||
|
|
3b05580b70 | ||
|
|
520e72f045 | ||
|
|
75a1563396 | ||
|
|
9d1782a03c | ||
|
|
0f057a2fd9 | ||
|
|
bf61590516 | ||
|
|
e45ea3c405 | ||
|
|
7c2c19c6ff | ||
|
|
c6603bf494 | ||
|
|
a91e892d26 | ||
|
|
bfcdfc8263 | ||
|
|
c43d903a97 | ||
|
|
b444dff3c7 | ||
|
|
30a779bc20 | ||
|
|
5879baac6d | ||
|
|
db5af6af0a | ||
|
|
f8daf390d0 | ||
|
|
bd36e8a263 | ||
|
|
59bca0fcff | ||
|
|
70e208fc20 | ||
|
|
089859eb4a | ||
|
|
492fd1743b | ||
|
|
a3646146b7 | ||
|
|
55c6a8fe25 | ||
|
|
6c970c5a24 | ||
|
|
5bbe5c0028 | ||
|
|
c402312c23 | ||
|
|
b329a3663c | ||
|
|
f04058e908 | ||
|
|
0b963b798c | ||
|
|
a25b1efc6d | ||
|
|
a1259b2622 | ||
|
|
ae64564963 | ||
|
|
ab3f8355d7 | ||
|
|
616680027b | ||
|
|
e213af5534 | ||
|
|
34c29fe2d9 | ||
|
|
f66533558f | ||
|
|
43fdb31e7b | ||
|
|
fe847213ad | ||
|
|
15575ccae9 | ||
|
|
a776624cd1 | ||
|
|
cd1f92edd1 | ||
|
|
0c96b12cc7 | ||
|
|
02c42dbdf0 | ||
|
|
f6880cfc68 | ||
|
|
92198ae1b1 | ||
|
|
09f245c95d | ||
|
|
bc53b83024 | ||
|
|
8f9dd26f19 | ||
|
|
a84ee9df3e | ||
|
|
b2d4e451e0 | ||
|
|
1bd6b54a5c | ||
|
|
01a47568dd | ||
|
|
1e8721df80 | ||
|
|
9b5e01bef9 | ||
|
|
bf5b7a0b71 | ||
|
|
ceacaad56d | ||
|
|
ced14e19bb | ||
|
|
04496dd479 | ||
|
|
232f3e1b53 | ||
|
|
81e31d0d32 | ||
|
|
a79b2855fa | ||
|
|
fe2f996a49 | ||
|
|
3e4faad81b | ||
|
|
a9131207e5 | ||
|
|
93e123f394 | ||
|
|
073a37ef6a | ||
|
|
a4aad6c004 | ||
|
|
132223248a | ||
|
|
5d9c3aad3c | ||
|
|
5a9316b62b | ||
|
|
3c859b214e | ||
|
|
7f2e862b72 | ||
|
|
4000328d56 | ||
|
|
503ecda280 | ||
|
|
859208196b | ||
|
|
ba22ef1752 | ||
|
|
fbbca81221 | ||
|
|
f03d4dff2f | ||
|
|
ab7b99a056 | ||
|
|
12f139ba53 | ||
|
|
97fa5ad62b | ||
|
|
978aa9aa7f | ||
|
|
0b4c49aa4d | ||
|
|
0a6edd4f98 | ||
|
|
896a32ef5f | ||
|
|
c64a759e8c |
10
.eslintignore
Normal file
@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
dist
|
||||
dist-electron
|
||||
*.min.js
|
||||
vite.config.ts
|
||||
*.config.js
|
||||
*.config.cjs
|
||||
frontend/public
|
||||
main/dist
|
||||
backend
|
||||
56
.github/workflows/build.yml
vendored
@ -1,8 +1,8 @@
|
||||
name: Build Crystal
|
||||
name: Build and Publish Canary
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
branches: [ main, 'release/**' ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
workflow_dispatch:
|
||||
@ -11,24 +11,28 @@ jobs:
|
||||
build:
|
||||
strategy:
|
||||
matrix:
|
||||
# Build both platforms with -dev suffix to prevent auto-updater cache conflicts
|
||||
# Build both platforms for validation, but use different commands for speed
|
||||
os: [macos-latest, ubuntu-latest]
|
||||
include:
|
||||
- os: macos-latest
|
||||
build_cmd: build:mac:ci:dev
|
||||
artifact_name: crystal-macos-dev
|
||||
artifact_path: dist-electron/*.dmg
|
||||
build_cmd: build:mac:universal
|
||||
artifact_name: crystal-macos-canary
|
||||
artifact_path: |
|
||||
dist-electron/*.dmg
|
||||
dist-electron/*.zip
|
||||
dist-electron/latest-mac.yml
|
||||
- os: ubuntu-latest
|
||||
build_cmd: build:linux:ci:dev
|
||||
artifact_name: crystal-linux-dev
|
||||
build_cmd: canary:linux
|
||||
artifact_name: crystal-linux-canary
|
||||
artifact_path: |
|
||||
dist-electron/*.deb
|
||||
dist-electron/*.AppImage
|
||||
dist-electron/latest-linux.yml
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
permissions:
|
||||
contents: read # Required for accessing repository contents
|
||||
contents: write # Required for creating releases and accessing repository contents
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
@ -48,19 +52,7 @@ jobs:
|
||||
node-version: '22.15.1'
|
||||
cache: 'pnpm'
|
||||
|
||||
# Cache native modules and electron binaries to speed up rebuilds
|
||||
- name: Cache native modules
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
main/node_modules/.bin
|
||||
main/build
|
||||
~/.electron
|
||||
~/.electron-gyp
|
||||
key: ${{ runner.os }}-native-modules-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-native-modules-
|
||||
|
||||
# Cache electron binaries to speed up builds
|
||||
- name: Cache Electron binaries
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
@ -101,24 +93,16 @@ jobs:
|
||||
echo "Using cached frontend and main builds"
|
||||
fi
|
||||
|
||||
- name: Rebuild native modules (if needed)
|
||||
run: |
|
||||
# Only rebuild if native modules cache missed or build files changed
|
||||
if [ ! -f "main/node_modules/.bin/electron-rebuild" ] || [ ! -f "main/build/Release/better_sqlite3.node" ]; then
|
||||
echo "Rebuilding native modules..."
|
||||
pnpm run electron:rebuild
|
||||
else
|
||||
echo "Using cached native modules"
|
||||
fi
|
||||
|
||||
- name: Generate NOTICES file
|
||||
run: pnpm run generate-notices
|
||||
|
||||
- name: Build application
|
||||
- name: Build and publish canary release
|
||||
run: pnpm run ${{ matrix.build_cmd }}
|
||||
env:
|
||||
# GitHub token (required by electron-builder even for non-publish builds)
|
||||
# GitHub token (required by electron-builder for publishing)
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# Mark this as a canary build
|
||||
CANARY_BUILD: true
|
||||
# macOS code signing (optional for CI builds)
|
||||
CSC_LINK: ${{ matrix.os == 'macos-latest' && secrets.APPLE_CERTIFICATE || '' }}
|
||||
CSC_KEY_PASSWORD: ${{ matrix.os == 'macos-latest' && secrets.APPLE_CERTIFICATE_PASSWORD || '' }}
|
||||
@ -128,6 +112,8 @@ jobs:
|
||||
APPLE_TEAM_ID: ${{ matrix.os == 'macos-latest' && secrets.APPLE_TEAM_ID || '' }}
|
||||
# Only enable signing when certificates are available
|
||||
CSC_IDENTITY_AUTO_DISCOVERY: ${{ matrix.os == 'macos-latest' && 'true' || 'false' }}
|
||||
# Disable signing entirely when no certificates are present
|
||||
CSC_DISABLE: ${{ (matrix.os == 'macos-latest' && !secrets.APPLE_CERTIFICATE) && 'true' || 'false' }}
|
||||
|
||||
- name: List build artifacts
|
||||
run: ls -la dist-electron/
|
||||
@ -144,5 +130,5 @@ jobs:
|
||||
name: ${{ matrix.artifact_name }}
|
||||
path: ${{ matrix.artifact_path }}
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
retention-days: 30
|
||||
|
||||
|
||||
4
.github/workflows/license-compliance.yml
vendored
@ -99,5 +99,5 @@ jobs:
|
||||
- name: Validate license compatibility
|
||||
run: |
|
||||
# Use our more sophisticated license compatibility check
|
||||
chmod +x ./scripts/check-license-compatibility.sh
|
||||
./scripts/check-license-compatibility.sh
|
||||
chmod +x ./check-license-compatibility.sh
|
||||
./check-license-compatibility.sh
|
||||
6
.github/workflows/release.yml
vendored
@ -9,11 +9,10 @@ jobs:
|
||||
release:
|
||||
strategy:
|
||||
matrix:
|
||||
# Official release builds (no version suffix) - triggered by version tags
|
||||
os: [macos-latest, ubuntu-latest]
|
||||
include:
|
||||
- os: macos-latest
|
||||
release_cmd: release:mac
|
||||
release_cmd: release:mac:universal
|
||||
artifact_name: crystal-macos
|
||||
artifact_path: |
|
||||
dist-electron/*.dmg
|
||||
@ -56,9 +55,6 @@ jobs:
|
||||
- name: Build main process
|
||||
run: pnpm run build:main
|
||||
|
||||
- name: Rebuild native modules
|
||||
run: pnpm run electron:rebuild
|
||||
|
||||
- name: Build and publish application
|
||||
run: pnpm run ${{ matrix.release_cmd }}
|
||||
env:
|
||||
|
||||
1
.gitignore
vendored
@ -13,7 +13,6 @@ node_modules/
|
||||
dist/
|
||||
build/
|
||||
!build/entitlements.mac.plist
|
||||
!build/linux/
|
||||
*.tsbuildinfo
|
||||
dist-electron/
|
||||
main/dist/
|
||||
|
||||
1
.node-version
Normal file
@ -0,0 +1 @@
|
||||
22.15.1
|
||||
3
.npmrc
@ -1,3 +1,4 @@
|
||||
public-hoist-pattern[]=*
|
||||
public-hoist-pattern[]=!better-sqlite3
|
||||
public-hoist-pattern[]=!@homebridge/node-pty-prebuilt-multiarch
|
||||
public-hoist-pattern[]=!@homebridge/node-pty-prebuilt-multiarch
|
||||
auto-install-peers=false
|
||||
42
AGENTS.md
Normal file
@ -0,0 +1,42 @@
|
||||
# Repository Guidelines
|
||||
|
||||
## Project Structure & Module Organization
|
||||
- Root `pnpm` workspace with packages: `main/` (Electron main process, TypeScript), `frontend/` (React + Vite), `shared/` (shared types), and `tests/` (Playwright E2E).
|
||||
- Key paths: `main/src/{services,ipc,utils}/`, `frontend/src/{components,hooks,stores,utils}/`, `main/assets/`, `scripts/`.
|
||||
- Build artifacts: `frontend/dist/`, `main/dist/`, packaged output `dist-electron/`.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
- Dev app: `pnpm dev` (spawns frontend + Electron).
|
||||
- Build all: `pnpm build` (frontend, main, then electron package).
|
||||
- Package (examples): `pnpm build:mac`, `pnpm build:linux`.
|
||||
- Lint: `pnpm lint`; Type-check: `pnpm typecheck` (runs per package).
|
||||
- Tests (E2E): `pnpm test`, `pnpm test:ui`, CI configs in `playwright.ci*.config.ts`.
|
||||
- Main unit tests (if added): `pnpm --filter main test`, coverage: `pnpm --filter main run test:coverage`.
|
||||
|
||||
## Coding Style & Naming Conventions
|
||||
- Use TypeScript throughout; follow ESLint configs in `frontend/eslint.config.js` and `main/eslint.config.js`.
|
||||
- Indentation 2 spaces; prefer explicit types at module boundaries.
|
||||
- Naming: `camelCase` for variables/functions, `PascalCase` for React components/types, `kebab-case` for filenames (React files may match component name).
|
||||
- Run `pnpm lint && pnpm typecheck` before sending PRs.
|
||||
|
||||
## Testing Guidelines
|
||||
- E2E tests live in `tests/*.spec.ts` (Playwright). Example: `pnpm test -- tests/smoke.spec.ts`.
|
||||
- Add Playwright tests for user-visible flows; mock external services where possible.
|
||||
- For backend logic in `main/`, use Vitest colocated under `main/src/**/__tests__` or `*.spec.ts`.
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
- Commits: present tense, focused, reference issues (e.g., "Fix session diff flicker, closes #123").
|
||||
- PRs must include: clear description, linked issues, testing notes; screenshots/GIFs for UI changes.
|
||||
- If dependencies change, run `pnpm run generate-notices` and commit updated `NOTICES`.
|
||||
|
||||
## Security & Configuration Tips
|
||||
- Node >= `22.14`; `pnpm` >= `8`. Use `pnpm` only.
|
||||
- Secrets via `.env` (dotenv) for local dev; never commit secrets.
|
||||
- To avoid clobbering local data when hacking on Crystal with Crystal: `CRYSTAL_DIR=~/.crystal_test pnpm dev`.
|
||||
|
||||
## Agent Notes (for automation)
|
||||
- Keep changes minimal and scoped; prefer small patches.
|
||||
- Update docs alongside code; do not alter build targets without discussion.
|
||||
- Use repository scripts (pnpm) and keep formatting consistent with existing files.
|
||||
- Always review the root `CLAUDE.md` before beginning any work.
|
||||
- Scan the repository for every `CLAUDE.md`, and when working in a folder or any of its subfolders that has one, read and follow that file too.
|
||||
206
CHANGELOG.md
@ -1,6 +1,212 @@
|
||||
|
||||
All notable changes to Crystal will be documented in this file.
|
||||
|
||||
## [0.3.5] - 2026-02-26
|
||||
|
||||
### We recommend migrating to Nimbalyst, our successor product to Crystal.
|
||||
https://nimbalyst.com/
|
||||
You may continue to use Crystal but it will not be updated in the future.
|
||||
|
||||
## [0.3.4] - 2025-12-19
|
||||
|
||||
### Added
|
||||
- **Merge and archive**: New "merge and archive" button that merges changes and archives the session in one action
|
||||
- **Archive folders on merge**: Ability to archive entire folders when merging
|
||||
- **Nimbalyst integration**: Open Nimbalyst directly from Crystal with worktree filter support
|
||||
- **Resizable UI elements**: File changes panel and prompt box/panel can now be resized
|
||||
|
||||
### Changed
|
||||
- **Multiple agents per worktree**: Run multiple agents in one worktree at a time for more flexible workflows
|
||||
|
||||
### Fixed
|
||||
- **Token usage parsing**: Fixed issues with token usage parsing
|
||||
- **Run script command**: Fixed wrong script command for run script ([#226](https://github.com/stravu/crystal/issues/226))
|
||||
- **Run script state**: Fixed run script state management issues
|
||||
- **Graceful degradation**: Application no longer fails to load if Codex or Claude Code are not installed
|
||||
- **Dependencies and linting**: Fixed various dependency and linting errors
|
||||
|
||||
### Documentation
|
||||
- **Windows build requirements**: Added Windows build requirements documentation
|
||||
|
||||
## [0.3.3] - 2025-10-12
|
||||
|
||||
### Added
|
||||
- **Prompt navigation**: Click on a prompt in the prompt history to snap to it in the output
|
||||
- **Reverse sort order**: Ability to reverse the sort order of sessions
|
||||
- **Multi-agent session creation**: Can now create both Codex and Claude Code sessions with one prompt
|
||||
|
||||
### Changed
|
||||
- **Git merge strategy**: Now uses merge to main instead of rebase for safer operations
|
||||
- **Folder sorting**: Folders are no longer always pinned to the top in sort order
|
||||
|
||||
### Fixed
|
||||
- **Light mode persistence**: Fixed light mode setting not persisting across sessions
|
||||
- **Light mode UI**: Various light mode visual fixes
|
||||
- **Automatic /context**: Fixed automatic /context command handling
|
||||
- **Codex parsing**: Fixed parsing issues with new Codex format
|
||||
|
||||
## [0.3.2] - 2025-10-10
|
||||
|
||||
### Fixed
|
||||
- **Mermaid diagram error handling**: Application no longer crashes when Mermaid diagrams fail to render
|
||||
- **Error boundary improvements**: Better error boundaries throughout the application for more graceful error handling
|
||||
- **Tool panels database error**: Fixed "no such table: tool_panels" database error
|
||||
- **Claude panels model selection**: Fixed bug where Claude panels were not respecting the selected model choice
|
||||
- **Timestamp handling**: Fixed timestamp handling issues in messaging view
|
||||
- **Git operations**: Optimized git operations by removing unnecessary process.chdir() calls for better performance
|
||||
|
||||
## [0.3.1] - 2025-09-30
|
||||
|
||||
### Major Changes
|
||||
- **Setup Tasks Panel**: New guided setup panel on project pane with auto-navigation to incomplete tasks
|
||||
- **Major Performance Improvements**: 40%+ CPU reduction through git status polling optimizations and terminal output processing enhancements
|
||||
- **Tool calls collapsed by default**: Cleaner output view with expandable tool call details
|
||||
- **Attribution messages in commits**: "Co-Authored-By: Crystal" attribution footer for commits made through Crystal. These can be disabled in the settings menu.
|
||||
- **Slash Commands in Claude Code**: You can now use commands such as /context in Claude Code panels
|
||||
|
||||
### Added
|
||||
- **Keyboard navigation between panels**: Use Cmd+Option+Arrow to quickly jump between panels
|
||||
- **Tool calls collapsed by default**: Cleaner output view with expandable tool call details
|
||||
- **Copy to clipboard for messages**: Copy individual messages directly from the output view
|
||||
- **New renderer for TODO lists**: Display Claude's todo lists directly in the output
|
||||
- **Cmd+Click for quick session creation**: Quick way to create new sessions without opening dialog
|
||||
- **GitHub status loading indicator**: Shows when GitHub integration is loading
|
||||
|
||||
### Changed
|
||||
- **Claude Code SDK updated to 2.0.0**: Latest SDK version with improved features
|
||||
- **Electron temporarily upgraded to 37.6.0** (Previous version had performance issues on OSX Tahoe)
|
||||
- **Reduced logging**: Less verbose console output for cleaner logs
|
||||
- **Panel state saving improvements**: Better persistence of panel states across sessions
|
||||
- **Library updates**: Updated dependencies based on Dependabot security warnings
|
||||
|
||||
### Fixed
|
||||
- **Run scripts don't auto-start on startup**: Prevents unwanted script execution on app launch
|
||||
- **Critical session bugs**: Fixed new sessions stuck on initializing, multiple sessions not appearing, and worktree deletion failures
|
||||
- **UI/UX fixes**: Slash command rendering, panel navigation, missing session IDs, and project settings clearing
|
||||
- **Performance fixes**: Fixed 2800ms+ frame drops, EventEmitter memory leaks, React infinite loops, and unnecessary re-renders
|
||||
- **Editor tab state persistence**: Editor now properly reloads state when switching sessions
|
||||
- **Terminal state preservation**: Terminal state no longer lost when switching between sessions
|
||||
- **Logs panel disappearing**: Fixed bug where closed logs panel wouldn't reappear
|
||||
- **Build fixes**: Multiple GitHub build fixes, Electron version mismatch, type errors, and linting errors
|
||||
- **Git operations**: Optimized git status refresh, reduced unnecessary checks, and centralized PATH management
|
||||
|
||||
### Performance
|
||||
- **Reduced CPU usage by 40%+**: Through git status polling optimizations with smart polling system
|
||||
- **Eliminated frame drops**: Fixed 2800ms+ frame drops during terminal output processing
|
||||
- **Memory leak fixes**: Fixed EventEmitter leaks in session list
|
||||
- **Optimized rendering**: Prevented unnecessary re-renders and improved terminal processing with adaptive debouncing
|
||||
|
||||
## [0.3.0] - 2025-09-21
|
||||
|
||||
### Major Changes
|
||||
- **OpenAI Codex support** - Run OpenAI Codex as well as Claude Code
|
||||
- **Panel-based workspace** - You may now create multiple agent and terminal panels inside a single session
|
||||
|
||||
### Added
|
||||
- **Session attachments & shortcuts** - Add text attachment support alongside images when starting sessions and Cmd+Click to spin up a new session.
|
||||
- **Clipboard actions** - Copy-to-clipboard icons for session messages and run-script logs.
|
||||
|
||||
### Changed
|
||||
- **New session dialog** - Remembers preferences, allows promptless sessions, stabilizes prompts when switching models, and improves model selection.
|
||||
- **Environment reliability** - Centralized PATH handling and refreshed git actions after commits for more accurate status updates.
|
||||
- **Session naming** - Session names can now have spaces for better flexibility.
|
||||
|
||||
### Fixed
|
||||
- **Session UX issues** - Fixed session rename regressions, prompt box glitches, duplicate key errors, and ensured git actions only appear on the right session.
|
||||
- **Attachments & prompts** - Corrected handling for image/text attachments, wrong prompts in dialogs, and Codex conversation continuation.
|
||||
- **Performance improvements** - Improved scroll behavior on diff viewer commits and better worktree deletion queuing.
|
||||
|
||||
### Security
|
||||
- **Race condition hardening** - Added session validation, mutex locks, and database transactions to prevent cross-session data leaks.
|
||||
|
||||
## [0.2.3] - 2025-08-25
|
||||
|
||||
### Fixed
|
||||
- **Session completion status updates** - Fixed "Rebase to main" button not updating when a session completed
|
||||
- **Session archiving performance** - Made session archiving operation much quicker
|
||||
|
||||
## [0.2.2] - 2025-08-23
|
||||
|
||||
### Added
|
||||
- **Homebrew install** - Crystal can now be installed with `brew install --cask stravu-crystal` on OSX
|
||||
|
||||
### Changed
|
||||
- **Performance improvements** - Optimized application performance for faster response times and smoother operation
|
||||
|
||||
## [0.2.1] - 2025-08-21
|
||||
|
||||
### Added
|
||||
- **'Auto' model selection** - New automatic model selection option that lets Claude Code choose the best model
|
||||
- **Sub-agent output visualization** - Enhanced UX for displaying sub-agent task outputs
|
||||
- **Terminal/Logs separation** - Logs from run scripts now have their own dedicated tab with filter and search
|
||||
- **Dev mode for debugging** - New developer mode to view raw Claude Code messages in the Messages tab
|
||||
- **Canary channel publishing** - Automatic canary builds from main branch for early testing
|
||||
|
||||
### Changed
|
||||
- **Performance improvements** - Various optimizations for better responsiveness
|
||||
- **Auto-scroll reliability** - More reliable auto-scrolling behavior that only activates when at bottom of output
|
||||
- **Project panel usage** - Now uses project panel instead of special (main) session
|
||||
- **Git branch actions labeling** - Renamed "Branch Actions" to "Git Branch Actions" for clarity
|
||||
|
||||
### Fixed
|
||||
- **Double prompt submission prevention** - Fixed issue where prompts could be submitted twice
|
||||
- **Commit message display** - Fixed showing commit messages in diff viewer
|
||||
- **Worktree file references** - Don't show worktree files when using @ to reference files
|
||||
- **Git status indicators** - Fixed "Behind Only - No unique changes" status marker
|
||||
- **Revert button backend** - Updated backend to use after_commit_hash for revert button functionality
|
||||
- **Run script log clearing** - Clear logs on fresh run script execution
|
||||
- **Canary build process** - Fixed canary build issues
|
||||
|
||||
### Documentation
|
||||
- **Demo video updated** - Updated demo video to showcase latest features
|
||||
- **Markdown cleanup** - Cleaned up and reorganized documentation structure
|
||||
|
||||
## [0.2.0] - 2025-08-05
|
||||
|
||||
### Added
|
||||
- Rich Output for Claude Code to replace text-only output
|
||||
- Light/Dark modes
|
||||
- Compact context
|
||||
- AWS Bedrock model support
|
||||
- Git status indicators in session sidebar
|
||||
- Always use the latest versions of Opus/Sonnet/Haiku, including Opus 4.1
|
||||
|
||||
### Changed
|
||||
- Terminal scrollback increased to 100,000 lines for better debugging
|
||||
- Project dashboard loading improvements
|
||||
- Enhanced IDE integration with loading states and command validation
|
||||
|
||||
### Fixed
|
||||
- Duplicate right-click context menus issue
|
||||
- IDE button not opening IDE properly
|
||||
- Context compaction now actually restarts conversations instead of just showing status
|
||||
- GTK 3 forced on Linux to resolve Electron 36 compatibility issues
|
||||
|
||||
## [0.1.17] - 2025-07-23
|
||||
|
||||
### Added
|
||||
- Project Dashboard view
|
||||
- Multi-mode auto-commit system
|
||||
- Visual refinements to Projects & Sessions sidebar with tree lines
|
||||
- Slider to select session count when creating multiple sessions
|
||||
|
||||
### Changed
|
||||
- Improved indentation levels in UI
|
||||
|
||||
### Fixed
|
||||
- ReferenceError: ReadableStream is not defined
|
||||
- Bug where navigation away from dashboard was blocked
|
||||
- Index issue with session navigation
|
||||
- Messages tab functionality restored for debugging Claude Code JSON output
|
||||
- Subfolder creation issues
|
||||
|
||||
### Internal/Development
|
||||
- Multiple code refactoring attempts (some reverted for stability)
|
||||
- Build artifacts now show commit hash
|
||||
- Added strict port checking for Vite dev server
|
||||
- CI/CD improvements including GitHub Actions for testing and building
|
||||
- Frontend console debugging for developing Crystal on Crystal
|
||||
|
||||
## [0.1.16] - 2025-07-18
|
||||
|
||||
Special thanks to eshaffer321 who contributed almost all the code in this release.
|
||||
|
||||
610
CLAUDE.md
@ -4,12 +4,15 @@ Created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_cam
|
||||
|
||||
## Project Overview
|
||||
|
||||
Crystal is a fully-implemented Electron desktop application for managing multiple Claude Code instances against a single directory using git worktrees. It provides a streamlined interface for running parallel Claude Code sessions with different approaches to the same problem.
|
||||
Crystal is a fully-implemented Electron desktop application for managing multiple AI code assistant instances (Claude Code and Codex) against a single directory using git worktrees. It provides a streamlined interface for running parallel AI assistant sessions with different approaches to the same problem.
|
||||
|
||||
## References
|
||||
Use these reference pages for more information:
|
||||
- How to invoke Claude Code through the command line as an SDK: https://docs.anthropic.com/en/docs/claude-code/sdk
|
||||
- How to run multiple Claude Code instances with Git Worktrees: https://docs.anthropic.com/en/docs/claude-code/tutorials#run-parallel-claude-code-sessions-with-git-worktrees
|
||||
- [**Adding New CLI Tools**](./docs/ADDING_NEW_CLI_TOOLS.md): Guide for extending Crystal to support additional CLI tools beyond Claude Code
|
||||
- [**Implementing New CLI Agents**](./docs/IMPLEMENTING_NEW_CLI_AGENTS.md): Step-by-step instructions for adding new CLI agent tools with code examples and best practices
|
||||
- [**Codex Configuration**](./main/src/services/panels/codex/CODEX_CONFIG.md): Configuration guide for Codex CLI integration
|
||||
|
||||
## Implementation Status: ✅ COMPLETE
|
||||
|
||||
@ -49,12 +52,15 @@ All core features have been successfully implemented with significant enhancemen
|
||||
- **Active project**: Persistent active project selection
|
||||
|
||||
### User Interface
|
||||
- **Professional terminal**: XTerm.js with 50,000 line scrollback buffer
|
||||
- **Dual tab system**: Main view tabs (Output | Diff | Logs | Editor) with tool panel bar underneath
|
||||
- **Tool Panel System**: Flexible panel framework supporting multiple terminal instances per session
|
||||
- **Multiple view modes**:
|
||||
- Output View: Formatted terminal output with syntax highlighting
|
||||
- Messages View: Raw JSON message inspection for debugging
|
||||
- View Diff View: Git diff viewer with file statistics
|
||||
- Terminal View: Dedicated terminal for running project scripts
|
||||
- Editor View: File editor with syntax highlighting
|
||||
- **Multi-instance terminals**: Multiple XTerm.js terminals per session with 50,000 line scrollback
|
||||
- **Panel management**: Create, switch, rename, and close tool panels dynamically
|
||||
- **Sidebar navigation**: Session list, project selector, prompt history
|
||||
- **Real-time updates**: IPC-based live output streaming
|
||||
- **Status indicators**: Color-coded badges with animations
|
||||
@ -68,11 +74,27 @@ All core features have been successfully implemented with significant enhancemen
|
||||
- **Clipboard support**: Copy prompts to clipboard
|
||||
|
||||
### Advanced Terminal Features
|
||||
- **Panel-based terminals**: Each terminal runs in its own panel with independent state
|
||||
- **Multi-instance support**: Multiple terminal panels per session for parallel workflows
|
||||
- **Multi-line input**: Auto-resizing textarea with keyboard shortcuts
|
||||
- **Smart formatting**: Automatic formatting of JSON messages
|
||||
- **Tool call display**: Clear visual structure for Claude's tool usage
|
||||
- **Script execution**: Run project scripts with real-time output
|
||||
- **Process management**: Start/stop script processes
|
||||
- **State persistence**: Terminal scrollback, working directory, and history persist across app restarts
|
||||
- **Lazy initialization**: Terminal processes only start when panels are first viewed
|
||||
|
||||
### Tool Panel System ✨ NEW
|
||||
- **Flexible architecture**: Extensible panel framework supporting multiple panel types
|
||||
- **Multi-instance terminals**: Run multiple terminal instances per session in separate panels
|
||||
- **Lazy initialization**: Panels only start processes when first viewed for memory efficiency
|
||||
- **State persistence**: Terminal scrollback, working directories, and panel configurations persist across restarts
|
||||
- **Panel lifecycle management**: Create, switch, rename, and delete panels dynamically
|
||||
- **Event-driven communication**: Panel event bus enabling future inter-panel communication
|
||||
- **Always-visible panel bar**: Tool panel tabs always visible below main view tabs
|
||||
- **Seamless integration**: Panels integrate with existing session and view management
|
||||
- **Memory efficient**: Inactive panels suspend rendering while maintaining background processes
|
||||
- **Future extensibility**: Architecture designed to support Claude, Diff, and Editor panels in future releases
|
||||
|
||||
### Settings & Configuration
|
||||
- **Global settings**:
|
||||
@ -91,15 +113,22 @@ All core features have been successfully implemented with significant enhancemen
|
||||
|
||||
### Data Persistence
|
||||
- **SQLite Database**:
|
||||
- `projects`: Project configurations and paths
|
||||
- `sessions`: Core session metadata
|
||||
- `session_outputs`: Terminal output history
|
||||
- `conversation_messages`: Conversation history for continuations
|
||||
- `execution_diffs`: Git diff tracking per execution
|
||||
- `prompt_markers`: Navigation markers for prompts
|
||||
- `projects`: Project configurations, paths, and commit settings
|
||||
- `sessions`: Core session metadata with active_panel_id, folder_id, tool_type ('claude'|'codex'|'none'), and status tracking
|
||||
- `session_outputs`: Terminal output history (linked to panels via panel_id)
|
||||
- `conversation_messages`: Conversation history with tool calls/results (linked to panels via panel_id)
|
||||
- `execution_diffs`: Git diff tracking per execution (linked to panels via panel_id)
|
||||
- `prompt_markers`: Navigation markers for prompts with completion timestamps (linked to panels via panel_id)
|
||||
- `tool_panels`: Panel configurations, state, metadata, and settings (JSON)
|
||||
- `folders`: Hierarchical folder structure for organizing sessions (supports nesting via parent_folder_id)
|
||||
- `project_run_commands`: Multiple configurable run commands per project
|
||||
- `claude_panel_settings`: Claude-specific panel configuration (legacy, being migrated to tool_panels.settings)
|
||||
- `ui_state`: UI state persistence for application preferences
|
||||
- `app_opens`: Application launch tracking for analytics
|
||||
- `user_preferences`: User preference storage for application behavior
|
||||
- **Automatic initialization**: `~/.crystal` directory created on first run
|
||||
- **Migration system**: SQL migrations for schema evolution
|
||||
- **Electron Store**: Application configuration persistence
|
||||
- **Migration system**: Dual migration system (TypeScript and SQL) for schema evolution
|
||||
- **JSON Configuration**: Application configuration stored in ~/.crystal/config.json
|
||||
|
||||
### Developer Experience
|
||||
- **Task Queue**: Bull queue with optional Redis support
|
||||
@ -113,7 +142,7 @@ All core features have been successfully implemented with significant enhancemen
|
||||
### Electron Application
|
||||
- **Main Process**: Electron main process with IPC communication
|
||||
- Window management with native OS integration
|
||||
- Electron Store for configuration persistence
|
||||
- Custom ConfigManager for configuration persistence (~/.crystal/config.json)
|
||||
- IPC handlers for renderer communication
|
||||
|
||||
### Frontend (React 19 + TypeScript)
|
||||
@ -139,7 +168,7 @@ All core features have been successfully implemented with significant enhancemen
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
```javascript
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Electron Desktop Application │
|
||||
├─────────────────────────────────────────────────────────┤
|
||||
@ -186,350 +215,69 @@ All core features have been successfully implemented with significant enhancemen
|
||||
|
||||
### Modular Architecture (Refactored)
|
||||
|
||||
The main process has been refactored from a monolithic `index.ts` file (previously 2,705 lines) into a modular structure:
|
||||
The main process has been refactored from a monolithic `index.ts` file into a comprehensive modular structure:
|
||||
|
||||
- **`index.ts`** (414 lines): Core Electron setup and initialization
|
||||
- **`ipc/git.ts`** (843 lines): All git-related IPC handlers
|
||||
- **`ipc/session.ts`** (428 lines): Session management IPC handlers
|
||||
- **`events.ts`** (359 lines): Event handling and coordination
|
||||
**Core Main Process:**
|
||||
- **`index.ts`** (776 lines): Core Electron setup and initialization
|
||||
- **`events.ts`** (1,108 lines): Event handling and coordination
|
||||
|
||||
The frontend has also been modularized:
|
||||
- **`useSessionView.ts`** (941 lines): Extracted session view logic from the previous monolithic SessionView component
|
||||
**IPC Handlers** (`main/src/ipc/`):
|
||||
- **`session.ts`** (1,872 lines): Session management IPC handlers
|
||||
- **`git.ts`** (1,391 lines): Git-related IPC handlers
|
||||
- **`file.ts`** (865 lines): File operations (read/write/delete/list)
|
||||
- **`dashboard.ts`** (741 lines): Dashboard overview and project status
|
||||
- **`codexPanel.ts`** (496 lines): Codex AI panel management
|
||||
- **`baseAIPanelHandler.ts`** (382 lines): Base class for AI panel handlers
|
||||
- **`project.ts`** (349 lines): Project CRUD operations
|
||||
- **`claudePanel.ts`** (268 lines): Claude AI panel management
|
||||
- **`script.ts`** (230 lines): Script execution handlers
|
||||
- **`panels.ts`** (228 lines): General panel lifecycle management
|
||||
- Plus 13 additional specialized handlers
|
||||
|
||||
**Service Layer** (`main/src/services/`):
|
||||
- **`sessionManager.ts`** (1,598 lines): Core session lifecycle management
|
||||
- **`worktreeManager.ts`** (931 lines): Git worktree operations
|
||||
- **`gitStatusManager.ts`** (872 lines): Git status tracking
|
||||
- **`taskQueue.ts`** (671 lines): Async task queue management
|
||||
- **`gitDiffManager.ts`** (606 lines): Diff generation and tracking
|
||||
- **`cliToolRegistry.ts`** (532 lines): CLI tool registration system
|
||||
- **`panelManager.ts`** (374 lines): Panel lifecycle coordinator
|
||||
- **`terminalPanelManager.ts`** (370 lines): Terminal panel processes
|
||||
- Plus 8 additional service modules
|
||||
|
||||
**Panel Services** (`main/src/services/panels/`):
|
||||
- **`codex/codexManager.ts`** (1,251 lines): Codex CLI integration
|
||||
- **`cli/AbstractCliManager.ts`** (994 lines): Abstract CLI manager base class
|
||||
- **`claude/claudeCodeManager.ts`** (741 lines): Claude CLI integration
|
||||
- **`logPanel/logsManager.ts`** (496 lines): Log panel management
|
||||
- **`ai/AbstractAIPanelManager.ts`** (395 lines): Abstract AI panel base class
|
||||
- **`codex/codexPanelManager.ts`** (403 lines): Codex panel lifecycle
|
||||
- **`claude/claudePanelManager.ts`** (135 lines): Claude panel lifecycle
|
||||
|
||||
**Frontend Hooks** (`frontend/src/hooks/`):
|
||||
- **`useSessionView.ts`** (1,694 lines): Session view logic and state management
|
||||
- **`useClaudePanel.ts`** (475 lines): Claude panel state management
|
||||
- **`useCliPanel.ts`** (452 lines): CLI panel state management
|
||||
- **`useIPCEvents.ts`** (349 lines): IPC event handling
|
||||
- **`useCodexPanel.ts`** (343 lines): Codex panel state management
|
||||
- **`useAIInputPanel.ts`** (311 lines): AI input panel logic
|
||||
- **`useNotifications.ts`** (212 lines): Notification system
|
||||
|
||||
**Frontend Stores** (`frontend/src/stores/`):
|
||||
- **`sessionStore.ts`** (699 lines): Session state management with Zustand
|
||||
- **`sessionPreferencesStore.ts`** (154 lines): User session preferences
|
||||
- **`panelStore.ts`** (109 lines): Panel state management
|
||||
- **`sessionHistoryStore.ts`** (93 lines): Session history tracking
|
||||
|
||||
**Major Frontend Components** (`frontend/src/components/`):
|
||||
- **`DraggableProjectTreeView.tsx`** (2,565 lines): Main project/session tree UI
|
||||
- **`CreateSessionDialog.tsx`** (1,293 lines): Session creation dialog
|
||||
- **`ProjectTreeView.tsx`** (612 lines): Project tree display
|
||||
- **`Settings.tsx`** (589 lines): Settings management UI
|
||||
- **`SessionView.tsx`** (587 lines): Session display (uses useSessionView hook)
|
||||
|
||||
This modular structure improves maintainability and makes it easier to locate and modify specific functionality.
|
||||
|
||||
### Session Output Handling (DO NOT MODIFY WITHOUT EXPLICIT PERMISSION)
|
||||
|
||||
⚠️ **WARNING**: The session output handling system is complex and fragile. Modifying it frequently causes issues like duplicate messages, disappearing content, or blank screens. Any changes require explicit user permission.
|
||||
|
||||
#### How It Works:
|
||||
|
||||
1. **Database Storage**:
|
||||
- Raw JSON messages from Claude are stored as-is in the database
|
||||
- Stdout/stderr outputs are stored directly
|
||||
- No formatting or transformation happens at storage time
|
||||
|
||||
2. **Real-time Streaming**:
|
||||
- When Claude outputs data, it's saved to the database immediately
|
||||
- For JSON messages, a formatted stdout version is sent to the frontend for the Output view
|
||||
- The original JSON is also sent for the Messages view
|
||||
- This provides immediate visual feedback during active sessions
|
||||
|
||||
3. **Session Loading**:
|
||||
- When navigating to a session, outputs are loaded from the database
|
||||
- The `sessions:get-output` handler transforms JSON messages to formatted stdout on-the-fly
|
||||
- Uses `setSessionOutputs` for atomic updates to prevent race conditions
|
||||
|
||||
4. **Frontend Display**:
|
||||
- The useSessionView hook manages session view logic and state (extracted from SessionView component)
|
||||
- A mutex lock (`loadingRef`) prevents concurrent loads
|
||||
- Timing is carefully managed with `requestAnimationFrame` and delays
|
||||
- The `formattedOutput` state is NOT cleared on session switch - it updates naturally
|
||||
|
||||
5. **Key Principles**:
|
||||
- Database is the single source of truth
|
||||
- Transformations happen on-the-fly, not at storage time
|
||||
- Real-time updates supplement but don't replace database data
|
||||
- Session switches always reload from database to ensure consistency
|
||||
|
||||
#### Common Issues and Solutions:
|
||||
|
||||
- **Duplicate messages**: Usually caused by sending both formatted and raw versions
|
||||
- **Disappearing content**: Often due to clearing output states at the wrong time
|
||||
- **Black screens**: Typically from race conditions during session switching
|
||||
- **Content only loads once**: Results from improper state management or missing dependencies
|
||||
|
||||
The current implementation carefully balances real-time updates with data persistence to provide a smooth user experience.
|
||||
|
||||
### Timestamp Handling Guidelines
|
||||
|
||||
⚠️ **IMPORTANT**: Proper timestamp handling is critical for the application to function correctly, especially for prompt duration calculations.
|
||||
|
||||
#### Overview
|
||||
|
||||
Crystal uses timestamps throughout the application for tracking session activity, prompt execution times, and displaying time-based information. Due to the mix of SQLite database storage and JavaScript Date objects, special care must be taken to ensure timezone consistency.
|
||||
|
||||
#### Key Principles
|
||||
|
||||
1. **Database Storage**: All timestamps are stored in UTC using SQLite's `CURRENT_TIMESTAMP` or `datetime()` functions
|
||||
2. **Frontend Display**: Timestamps are parsed as UTC and converted to local time only for display
|
||||
3. **Consistency**: Always use the timestamp utility functions instead of manual date parsing
|
||||
4. **Validation**: Always validate timestamps before using them in calculations
|
||||
|
||||
#### Timestamp Formats
|
||||
|
||||
- **SQLite DATETIME**: `YYYY-MM-DD HH:MM:SS` (stored in UTC without timezone indicator)
|
||||
- **ISO 8601**: `YYYY-MM-DDTHH:MM:SS.sssZ` (with explicit UTC timezone)
|
||||
- **JavaScript Date**: Local timezone by default (be careful!)
|
||||
|
||||
#### Utility Functions
|
||||
|
||||
Crystal provides timestamp utilities in both frontend and backend:
|
||||
|
||||
**Backend** (`main/src/utils/timestampUtils.ts`):
|
||||
```typescript
|
||||
import { formatForDatabase, getCurrentTimestamp } from '../utils/timestampUtils';
|
||||
|
||||
// For database storage
|
||||
const timestamp = formatForDatabase(); // Returns ISO string
|
||||
const now = getCurrentTimestamp(); // Alias for formatForDatabase()
|
||||
|
||||
// For display formatting
|
||||
const displayTime = formatForDisplay(timestamp);
|
||||
```
|
||||
|
||||
**Frontend** (`frontend/src/utils/timestampUtils.ts`):
|
||||
```typescript
|
||||
import { parseTimestamp, formatDuration, getTimeDifference } from '../utils/timestampUtils';
|
||||
|
||||
// Parse SQLite timestamps correctly
|
||||
const date = parseTimestamp("2024-01-01 12:00:00"); // Handles UTC conversion
|
||||
|
||||
// Calculate durations
|
||||
const durationMs = getTimeDifference(startTime, endTime);
|
||||
const formatted = formatDuration(durationMs); // "2m 34s"
|
||||
|
||||
// Display relative time
|
||||
const ago = formatDistanceToNow(timestamp); // "5 minutes ago"
|
||||
```
|
||||
|
||||
#### Database Operations
|
||||
|
||||
When working with timestamps in SQLite:
|
||||
|
||||
```sql
|
||||
-- Use datetime() for UTC timestamps
|
||||
INSERT INTO prompt_markers (timestamp) VALUES (datetime('now'));
|
||||
|
||||
-- When selecting, append 'Z' for proper UTC parsing
|
||||
SELECT datetime(timestamp) || 'Z' as timestamp FROM prompt_markers;
|
||||
|
||||
-- For completion timestamps with NULL handling
|
||||
SELECT
|
||||
CASE
|
||||
WHEN completion_timestamp IS NOT NULL
|
||||
THEN datetime(completion_timestamp) || 'Z'
|
||||
ELSE NULL
|
||||
END as completion_timestamp
|
||||
FROM prompt_markers;
|
||||
```
|
||||
|
||||
#### Common Patterns
|
||||
|
||||
**Creating a new timestamp**:
|
||||
```typescript
|
||||
// Backend - for database storage
|
||||
const timestamp = formatForDatabase();
|
||||
|
||||
// Frontend - for immediate use
|
||||
const now = new Date();
|
||||
```
|
||||
|
||||
**Tracking prompt execution time**:
|
||||
```typescript
|
||||
// When prompt starts
|
||||
db.addPromptMarker(sessionId, promptText, outputIndex);
|
||||
|
||||
// When prompt completes
|
||||
db.updatePromptMarkerCompletion(sessionId);
|
||||
```
|
||||
|
||||
**Calculating duration**:
|
||||
```typescript
|
||||
// With completion timestamp
|
||||
if (prompt.completion_timestamp) {
|
||||
const duration = getTimeDifference(prompt.timestamp, prompt.completion_timestamp);
|
||||
return formatDuration(duration);
|
||||
}
|
||||
|
||||
// For ongoing prompts
|
||||
const duration = getTimeDifference(prompt.timestamp); // Uses current time as end
|
||||
return formatDuration(duration) + ' (ongoing)';
|
||||
```
|
||||
|
||||
#### Common Pitfalls to Avoid
|
||||
|
||||
1. **Never parse SQLite timestamps directly with `new Date()`**:
|
||||
```typescript
|
||||
// ❌ WRONG - treats UTC as local time
|
||||
const date = new Date("2024-01-01 12:00:00");
|
||||
|
||||
// ✅ CORRECT - uses parseTimestamp utility
|
||||
const date = parseTimestamp("2024-01-01 12:00:00");
|
||||
```
|
||||
|
||||
2. **Always validate timestamps before calculations**:
|
||||
```typescript
|
||||
if (!isValidTimestamp(timestamp)) {
|
||||
return 'Unknown duration';
|
||||
}
|
||||
```
|
||||
|
||||
3. **Be careful with timezone conversions**:
|
||||
```typescript
|
||||
// Database stores UTC, display shows local
|
||||
const dbTime = "2024-01-01 12:00:00"; // UTC
|
||||
const parsed = parseTimestamp(dbTime); // Correctly handled as UTC
|
||||
const display = formatForDisplay(parsed); // Converts to local for display
|
||||
```
|
||||
|
||||
4. **Handle negative durations gracefully**:
|
||||
```typescript
|
||||
const duration = endTime - startTime;
|
||||
if (duration < 0) {
|
||||
console.warn('Negative duration detected');
|
||||
return 'Invalid duration';
|
||||
}
|
||||
```
|
||||
|
||||
#### Testing Timestamp Code
|
||||
|
||||
When testing timestamp-related features:
|
||||
|
||||
1. Test with different timezones (especially negative UTC offsets)
|
||||
2. Test with daylight saving time transitions
|
||||
3. Test with very old and future timestamps
|
||||
4. Test with invalid/malformed timestamps
|
||||
5. Verify duration calculations are always positive
|
||||
|
||||
### State Management Guidelines
|
||||
|
||||
⚠️ **IMPORTANT**: Crystal follows a targeted update pattern for state management to minimize unnecessary re-renders and network requests.
|
||||
|
||||
#### Overview
|
||||
|
||||
Crystal uses a combination of Zustand stores, IPC events, and targeted updates to manage application state efficiently. The application prioritizes specific, targeted updates over global refreshes to improve performance and user experience.
|
||||
|
||||
#### Key Principles
|
||||
|
||||
1. **Targeted Updates**: Always update only the specific data that changed
|
||||
2. **Event-Driven Updates**: Use IPC events to communicate changes between processes
|
||||
3. **Avoid Global Refreshes**: Never reload entire lists when only one item changes
|
||||
4. **Database as Source of Truth**: Frontend state should reflect backend state, not override it
|
||||
|
||||
#### State Update Patterns
|
||||
|
||||
**Session Updates**:
|
||||
```typescript
|
||||
// ❌ BAD: Global refresh
|
||||
const handleSessionCreated = () => {
|
||||
loadProjectsWithSessions(); // Reloads everything
|
||||
};
|
||||
|
||||
// ✅ GOOD: Targeted update
|
||||
const handleSessionCreated = (newSession: Session) => {
|
||||
setProjectsWithSessions(prevProjects => {
|
||||
return prevProjects.map(project => {
|
||||
if (project.id === newSession.projectId) {
|
||||
return {
|
||||
...project,
|
||||
sessions: [...project.sessions, newSession]
|
||||
};
|
||||
}
|
||||
return project;
|
||||
});
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
**Project Updates**:
|
||||
```typescript
|
||||
// ❌ BAD: Reload all projects
|
||||
const handleProjectDeleted = () => {
|
||||
fetchProjects(); // Network request for all projects
|
||||
};
|
||||
|
||||
// ✅ GOOD: Remove from local state
|
||||
const handleProjectDeleted = () => {
|
||||
setProjects(prev => prev.filter(p => p.id !== deletedId));
|
||||
};
|
||||
```
|
||||
|
||||
#### IPC Event Handling
|
||||
|
||||
The application uses IPC events to synchronize state between the main process and renderer:
|
||||
|
||||
1. **Session Events**:
|
||||
- `session:created` - Add new session to appropriate project
|
||||
- `session:updated` - Update specific session properties
|
||||
- `session:deleted` - Remove session from project list
|
||||
|
||||
2. **Project Events** (if implemented):
|
||||
- `project:created` - Add new project to list
|
||||
- `project:updated` - Update specific project properties
|
||||
- `project:deleted` - Remove project from list
|
||||
|
||||
#### When Global Refreshes Are Acceptable
|
||||
|
||||
- **Initial Load**: When component mounts for the first time
|
||||
- **User-Triggered Refresh**: When user explicitly requests a refresh
|
||||
- **Error Recovery**: After connection loss or critical errors
|
||||
- **Complex State Changes**: When multiple interdependent items change
|
||||
|
||||
#### Implementation Examples
|
||||
|
||||
**DraggableProjectTreeView.tsx**:
|
||||
- Uses targeted updates for session creation, update, and deletion
|
||||
- Only reloads all data on initial mount or when critical errors occur
|
||||
- Maintains local state synchronized with backend through IPC events
|
||||
|
||||
**ProjectSelector.tsx**:
|
||||
- Updates project list locally when projects are deleted
|
||||
- Falls back to refresh only when necessary (e.g., complex updates)
|
||||
|
||||
#### Best Practices
|
||||
|
||||
1. **Use State Setters with Callbacks**: Always use the callback form of setState to ensure you're working with the latest state
|
||||
2. **Merge Updates**: When updating objects, spread existing properties to preserve data
|
||||
3. **Handle Edge Cases**: Always check if the item exists before updating
|
||||
4. **Log State Changes**: Add console logs for debugging state updates in development
|
||||
5. **Validate IPC Data**: Ensure IPC events contain expected data structure
|
||||
|
||||
### Diff Viewer CSS Troubleshooting
|
||||
|
||||
⚠️ **IMPORTANT**: The diff viewer (react-diff-viewer-continued) has specific CSS requirements that can be tricky to debug.
|
||||
|
||||
#### Common Issue: No Scrollbars on Diff Viewer
|
||||
|
||||
If the diff viewer content is cut off and scrollbars don't appear:
|
||||
|
||||
1. **DO NOT add complex CSS overrides** - This often makes the problem worse
|
||||
2. **Check parent containers for `overflow-hidden`** - This is usually the root cause
|
||||
3. **Use simple `overflow: 'auto'`** on the immediate diff container
|
||||
4. **Remove any forced widths or min-widths** unless absolutely necessary
|
||||
|
||||
#### The Solution That Works:
|
||||
|
||||
```tsx
|
||||
// In DiffViewer.tsx - Keep it simple!
|
||||
<div className="border border-t-0 border-gray-600 rounded-b-lg" style={{ overflow: 'auto', maxHeight: '600px' }}>
|
||||
<ReactDiffViewer
|
||||
oldValue={file.oldValue || ''}
|
||||
newValue={file.newValue || ''}
|
||||
splitView={viewType === 'split'}
|
||||
useDarkTheme={isDarkMode}
|
||||
styles={currentStyles}
|
||||
// Don't add complex style overrides here
|
||||
/>
|
||||
</div>
|
||||
```
|
||||
|
||||
#### What NOT to Do:
|
||||
|
||||
- Don't add multiple wrapper divs with conflicting overflow settings
|
||||
- Don't use CSS-in-JS to override react-diff-viewer's internal styles
|
||||
- Don't add global CSS selectors targeting generated class names
|
||||
- Don't use JavaScript hacks to force reflows
|
||||
|
||||
#### Root Cause:
|
||||
|
||||
The issue is typically caused by parent containers having `overflow-hidden` which prevents child scrollbars from appearing. Check these files:
|
||||
- `SessionView.tsx` - Look for `overflow-hidden` classes
|
||||
- `CombinedDiffView.tsx` - Check both the main container and flex containers
|
||||
- `App.tsx` - Sometimes the issue starts at the app root level
|
||||
|
||||
The react-diff-viewer-continued library uses emotion/styled-components internally, which makes CSS overrides unreliable. The best approach is to ensure proper overflow handling in parent containers and keep the diff viewer wrapper simple.
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Session Management
|
||||
@ -571,68 +319,112 @@ The react-diff-viewer-continued library uses emotion/styled-components internall
|
||||
|
||||
## Available Commands
|
||||
|
||||
### Setup & Installation
|
||||
```bash
|
||||
# One-time setup (install, build, and rebuild native modules)
|
||||
pnpm run setup
|
||||
pnpm run setup # One-time setup (install, build, and rebuild native modules)
|
||||
```
|
||||
|
||||
# Run as Electron app in development mode
|
||||
pnpm electron-dev
|
||||
# Or use the shorthand:
|
||||
pnpm run dev
|
||||
|
||||
# Run frontend only (without Electron shell)
|
||||
pnpm dev
|
||||
|
||||
# Build for production
|
||||
pnpm build
|
||||
|
||||
# Type checking
|
||||
pnpm typecheck
|
||||
|
||||
# Linting
|
||||
pnpm lint
|
||||
### Development
|
||||
```bash
|
||||
pnpm electron-dev # Run as Electron app in development mode
|
||||
pnpm run dev # Shorthand for electron-dev
|
||||
pnpm dev # Run frontend only (without Electron shell)
|
||||
```
|
||||
|
||||
**Note:** You must run `pnpm run build:main` at least once before running `pnpm electron-dev` to compile the main process.
|
||||
|
||||
### Building Packaged Electron App
|
||||
|
||||
### Building
|
||||
```bash
|
||||
# Build for macOS
|
||||
pnpm build:mac # macOS (only works on macOS)
|
||||
pnpm build # Build for production (all platforms)
|
||||
pnpm build:main # Build main process only
|
||||
pnpm build:frontend # Build frontend only
|
||||
```
|
||||
|
||||
### Building Packaged Electron App
|
||||
```bash
|
||||
pnpm build:mac # Build for macOS (universal)
|
||||
pnpm build:mac:x64 # Build for macOS (Intel only)
|
||||
pnpm build:mac:arm64 # Build for macOS (Apple Silicon only)
|
||||
pnpm build:linux # Build for Linux
|
||||
```
|
||||
|
||||
### Testing
|
||||
```bash
|
||||
pnpm test # Run Playwright tests
|
||||
pnpm test:ui # Run tests with Playwright UI
|
||||
pnpm test:headed # Run tests in headed browser mode
|
||||
```
|
||||
|
||||
### Code Quality
|
||||
```bash
|
||||
pnpm typecheck # Type checking across all workspaces
|
||||
pnpm lint # Linting across all workspaces
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
```javascript
|
||||
crystal/
|
||||
├── frontend/ # React renderer process
|
||||
│ ├── src/
|
||||
│ │ ├── components/ # React components
|
||||
│ │ ├── components/ # React components (50+ files)
|
||||
│ │ │ ├── panels/ # Panel components (Terminal, Claude, Codex, Diff, Editor, Logs, Dashboard, SetupTasks)
|
||||
│ │ │ ├── Help.tsx # Help dialog
|
||||
│ │ │ └── ... # Other UI components
|
||||
│ │ ├── hooks/ # Custom React hooks
|
||||
│ │ │ └── useSessionView.ts # Session view logic (941 lines)
|
||||
│ │ │ ├── DraggableProjectTreeView.tsx # Main project/session tree UI
|
||||
│ │ │ └── ... # Other UI components
|
||||
│ │ ├── hooks/ # Custom React hooks (9 hooks)
|
||||
│ │ │ ├── useSessionView.ts # Session view logic (1,694 lines)
|
||||
│ │ │ ├── useClaudePanel.ts # Claude panel state
|
||||
│ │ │ ├── useCodexPanel.ts # Codex panel state
|
||||
│ │ │ └── ... # Other hooks
|
||||
│ │ ├── stores/ # Zustand state stores
|
||||
│ │ │ ├── sessionStore.ts # Session state (699 lines)
|
||||
│ │ │ ├── panelStore.ts # Panel state
|
||||
│ │ │ └── ... # Other stores
|
||||
│ │ ├── contexts/ # React context providers
|
||||
│ │ ├── services/ # Frontend services
|
||||
│ │ └── utils/ # Utility functions
|
||||
│ │ └── timestampUtils.ts # Timestamp handling
|
||||
├── main/ # Electron main process
|
||||
│ ├── src/
|
||||
│ │ ├── index.ts # Main entry point (reduced to 414 lines)
|
||||
│ │ ├── index.ts # Main entry point (776 lines)
|
||||
│ │ ├── preload.ts # Preload script
|
||||
│ │ ├── events.ts # Event handling (359 lines)
|
||||
│ │ ├── events.ts # Event handling (1,108 lines)
|
||||
│ │ ├── database/ # SQLite database
|
||||
│ │ ├── ipc/ # IPC handlers (modular)
|
||||
│ │ │ ├── git.ts # Git operation handlers (843 lines)
|
||||
│ │ │ ├── session.ts # Session operation handlers (428 lines)
|
||||
│ │ │ └── ... # Other IPC handlers
|
||||
│ │ ├── services/ # Business logic services
|
||||
│ │ │ ├── taskQueue.ts # Bull queue for async tasks
|
||||
│ │ │ └── ... # Other service modules
|
||||
│ │ ├── routes/ # API routes
|
||||
│ │ └── types/ # TypeScript types
|
||||
│ │ │ └── migrations/ # Database migration files
|
||||
│ │ ├── ipc/ # IPC handlers (23 handlers)
|
||||
│ │ │ ├── git.ts # Git operations (1,391 lines)
|
||||
│ │ │ ├── session.ts # Session management (1,872 lines)
|
||||
│ │ │ ├── file.ts # File operations (865 lines)
|
||||
│ │ │ ├── claudePanel.ts # Claude panel management
|
||||
│ │ │ ├── codexPanel.ts # Codex panel management
|
||||
│ │ │ └── ... # 18 more IPC handlers
|
||||
│ │ ├── services/ # Business logic services (33 modules)
|
||||
│ │ │ ├── sessionManager.ts # Core session lifecycle (1,598 lines)
|
||||
│ │ │ ├── worktreeManager.ts # Git worktree operations (931 lines)
|
||||
│ │ │ ├── panelManager.ts # Panel lifecycle coordinator
|
||||
│ │ │ ├── terminalPanelManager.ts # Terminal panel processes
|
||||
│ │ │ ├── taskQueue.ts # Bull queue
|
||||
│ │ │ └── panels/ # Panel-specific services
|
||||
│ │ │ ├── claude/ # Claude CLI integration
|
||||
│ │ │ ├── codex/ # Codex CLI integration
|
||||
│ │ │ ├── cli/ # Abstract CLI manager
|
||||
│ │ │ └── ai/ # Abstract AI panel base
|
||||
│ │ ├── polyfills/ # Node.js polyfills
|
||||
│ │ ├── types/ # TypeScript types
|
||||
│ │ └── utils/ # Utility functions
|
||||
│ │ └── timestampUtils.ts # Timestamp handling
|
||||
│ └── dist/ # Compiled output
|
||||
├── shared/ # Shared TypeScript types
|
||||
├── dist-electron/ # Packaged Electron app
|
||||
│ └── types/
|
||||
│ └── panels.ts # Panel type definitions
|
||||
├── tests/ # E2E tests (Playwright)
|
||||
├── scripts/ # Build and utility scripts
|
||||
├── docs/ # Documentation
|
||||
│ ├── troubleshooting/ # Troubleshooting guides
|
||||
│ ├── ADDING_NEW_CLI_TOOLS.md
|
||||
│ └── IMPLEMENTING_NEW_CLI_AGENTS.md
|
||||
├── dist-electron/ # Packaged Electron app (generated during build)
|
||||
├── package.json # Root workspace configuration
|
||||
└── pnpm-workspace.yaml
|
||||
```
|
||||
@ -685,30 +477,40 @@ Enable verbose logging in Settings to see detailed logs for troubleshooting.
|
||||
|
||||
In development mode, Crystal automatically captures all frontend console logs and writes them to a file that Claude Code can read for debugging purposes.
|
||||
|
||||
**Location**: `crystal-frontend-debug.log` in the project root directory
|
||||
**Location**: `crystal-frontend-debug.log` and `crystal-backend-debug.log`in the project root directory
|
||||
|
||||
**What gets logged**:
|
||||
- All `console.log`, `console.warn`, `console.error`, `console.info`, and `console.debug` calls from the React frontend
|
||||
- Automatic console messages from Electron's webContents (warnings, errors)
|
||||
- Timestamp, log level, and source information for each message
|
||||
|
||||
**Example log format**:
|
||||
```
|
||||
[2024-07-21T15:30:45.123Z] [RENDERER LOG] User clicked session creation button
|
||||
[2024-07-21T15:30:45.234Z] [FRONTEND WARNING] Session validation failed: missing prompt
|
||||
[2024-07-21T15:30:45.345Z] [FRONTEND ERROR] Failed to create session (SessionView.tsx:123)
|
||||
```
|
||||
|
||||
**Usage for Claude Code debugging**:
|
||||
1. Add debug console.log statements to frontend components
|
||||
2. Reproduce the issue in the Crystal app
|
||||
3. Read `crystal-frontend-debug.log` to see what happened
|
||||
3. Read `crystal-frontend-debug.log` and `crystal-backend-debug.log` to see what happened
|
||||
4. No need to manually check Chrome DevTools or ask humans to copy logs
|
||||
|
||||
`crystal-frontend-debug.log` and `crystal-backend-debug.log` are reset every time the user runs in development mode, so if they report that a change is not working, you can look at those logs and they will represent the session they tested the change.
|
||||
|
||||
**IMPORTANT** Logs are best investigated in a sub-agent
|
||||
|
||||
**File rotation**: The log file grows continuously during development. Delete or truncate it manually if it gets too large.
|
||||
|
||||
**Note**: This feature is only active in development mode and will not affect production builds.
|
||||
|
||||
## TypeScript Coding Standards
|
||||
|
||||
### NO 'ANY' TYPE USAGE
|
||||
|
||||
**IMPORTANT**: This codebase enforces a strict no-any policy. The TypeScript 'any' type is NOT allowed.
|
||||
|
||||
- ❌ **NEVER use \****`any`**\*\* type** - ESLint will error and CI/CD will fail
|
||||
- ✅ Use `unknown` when the type is truly unknown (requires type guards before use)
|
||||
- ✅ Use specific types or interfaces whenever possible
|
||||
- ✅ Use generics with type constraints for flexible but type-safe code
|
||||
|
||||
|
||||
**Enforcement**:
|
||||
- ESLint rule `@typescript-eslint/no-explicit-any` is set to `'error'`
|
||||
- GitHub Actions quality workflow enforces this on all PRs
|
||||
- Local development will show errors immediately
|
||||
|
||||
## Disclaimer
|
||||
|
||||
Crystal is an independent project created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1). Claude™ is a trademark of Anthropic, PBC. Crystal is not affiliated with, endorsed by, or sponsored by Anthropic. This tool is designed to work with Claude Code, which must be installed separately.
|
||||
|
||||
@ -4,6 +4,10 @@ Thank you for your interest in contributing to Crystal! We welcome contributions
|
||||
|
||||
Crystal is an open source project created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1). Stravu is the way AI-first teams collaborate.
|
||||
|
||||
## Right to Contribute this Code
|
||||
- You represent and warrant that You are legally entitled to contribute the code you contribute to Crystal
|
||||
- You represent and warrant that each of Your Contributions is Your original creation. You represent and warrant that, to Your knowledge, none of Your Contributions infringe, violate, or misappropriate any third party intellectual property or other proprietary rights.
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Fork the repository on GitHub
|
||||
|
||||
190
README.md
@ -1,150 +1,56 @@
|
||||
# Crystal - Multi-Session Claude Code Manager
|
||||
|
||||
<div align="center">
|
||||
<h3><a href="https://github.com/stravu/crystal/releases/latest">**Get the Latest Release Here**</a></h3>
|
||||
<a href="https://nimbalyst.com/">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://nimbalyst.com/nimbalyst-logo-white.svg" />
|
||||
<img src="https://nimbalyst.com/nimbalyst-logo.svg" alt="Nimbalyst Logo" width="260" />
|
||||
</picture>
|
||||
</a>
|
||||
<p><a href="https://nimbalyst.com/">https://nimbalyst.com/</a></p>
|
||||
<p><a href="https://nimbalyst.com/download/">Download here</a></p>
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://github.com/stravu/crystal/actions/workflows/build.yml)
|
||||
[](https://github.com/stravu/crystal/actions/workflows/quality.yml)
|
||||
[](https://discord.gg/XrVa6q7DPY)
|
||||
|
||||
<h1>Crystal Is Now Nimbalyst</h1>
|
||||
<p>Crystal (formerly a multi-session AI code assistant manager) has been deprecated and replaced by <strong>Nimbalyst</strong>.</p>
|
||||
<p>Deprecated: February 2026.</p>
|
||||
</div>
|
||||
|
||||
Crystal is an Electron desktop application that lets you run, inspect, and test multiple Claude Code instances simultaneously using git worktrees. Crystal is an independent project created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1). Stravu provides editable, collaborate AI notebooks with text, tables, diagrams.
|
||||
|
||||
|
||||
|
||||
https://github.com/user-attachments/assets/e32f0ee7-c25a-43d6-a704-8a39878032eb
|
||||
|
||||
|
||||
|
||||
## The Crystal Workflow
|
||||
|
||||
1. Create sessions from prompts, each in an isolated git worktree
|
||||
2. Iterate with Claude Code inside your sessions. Each iteration will make a commit so you can always go back.
|
||||
3. Review the diff changes and make manual edits as needed
|
||||
4. Squash your commits together with a new message and rebase to your main branch.
|
||||
|
||||
## ✨ Key Features
|
||||
|
||||
- **🚀 Parallel Sessions** - Run multiple Claude Code instances at once
|
||||
- **🌳 Git Worktree Isolation** - Each session gets its own branch
|
||||
- **💾 Session Persistence** - Resume conversations anytime
|
||||
- **🔧 Git Integration** - Built-in rebase and squash operations
|
||||
- **📊 Change Tracking** - View diffs and track modifications
|
||||
- **🔔 Notifications** - Desktop alerts when sessions need input
|
||||
- **🏗️ Run Scripts** - Test changes instantly without leaving Crystal
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Prerequisites
|
||||
- Claude Code installed and logged in or API key provided
|
||||
- Git installed
|
||||
- Git repository (Crystal will initialize one if needed)
|
||||
|
||||
### 1. Create a Project
|
||||
Create a new project if you haven't already. This can be an empty folder or an existing git repository. Crystal will initialize git if needed.
|
||||
|
||||
### 2. Create Sessions from a Prompt
|
||||
For any feature you're working on, create one or multiple new sessions:
|
||||
- Each session will be an isolated git worktree
|
||||
|
||||
### 3. Monitor and Test Your Changes
|
||||
As sessions complete:
|
||||
- **Configure run scripts** in project settings to test your application without leaving Crystal
|
||||
- **Use the diff viewer** to review all changes and make manual edits as needed
|
||||
- **Continue conversations** with Claude Code if you need additional changes
|
||||
|
||||
### 4. Finalize Your Changes
|
||||
When everything looks good:
|
||||
- Click **"Rebase to main"** to squash all commits with a new message and rebase them to your main branch
|
||||
- This creates a clean commit history on your main branch
|
||||
|
||||
### Git Operations
|
||||
- **Rebase from main**: Pull latest changes from main into your worktree
|
||||
- **Squash and rebase to main**: Combine all commits and rebase onto main
|
||||
- Always preview commands with tooltips before executing
|
||||
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
### Download Pre-built Binaries
|
||||
|
||||
- **macOS**: Download `Crystal-{version}.dmg` from the [latest release](https://github.com/stravu/crystal/releases/latest)
|
||||
- Open the DMG file and drag Crystal to your Applications folder
|
||||
- On first launch, you may need to right-click and select "Open" due to macOS security settings
|
||||
|
||||
|
||||
## Building from Source
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/stravu/crystal.git
|
||||
cd crystal
|
||||
|
||||
# One-time setup
|
||||
pnpm run setup
|
||||
|
||||
# Run in development
|
||||
pnpm run electron-dev
|
||||
```
|
||||
|
||||
## Building for Production
|
||||
|
||||
```bash
|
||||
# Build for macOS
|
||||
pnpm build:mac
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.
|
||||
|
||||
### Developing Crystal with Crystal
|
||||
|
||||
If you're using Crystal to develop Crystal itself, you need to use a separate data directory to avoid conflicts with your main Crystal instance:
|
||||
|
||||
```bash
|
||||
# Set the run script in your Crystal project settings to:
|
||||
pnpm run setup && pnpm run build:main && CRYSTAL_DIR=~/.crystal_test pnpm electron-dev
|
||||
```
|
||||
|
||||
This ensures:
|
||||
- Your development Crystal instance uses `~/.crystal_test` for its data
|
||||
- Your main Crystal instance continues using `~/.crystal`
|
||||
- Worktrees won't conflict between the two instances
|
||||
- You can safely test changes without affecting your primary Crystal setup
|
||||
|
||||
## Additional Documentation
|
||||
|
||||
For a full project overview, see [CLAUDE.md](CLAUDE.md). Additional diagrams, database schema details, release instructions, and license notes can be found in the [docs](./docs) directory.
|
||||
|
||||
## 📄 License
|
||||
|
||||
Crystal is open source software licensed under the [MIT License](LICENSE).
|
||||
|
||||
### Third-Party Licenses
|
||||
|
||||
Crystal includes third-party software components. All third-party licenses are documented in the [NOTICES](NOTICES) file. This file is automatically generated and kept up-to-date with our dependencies.
|
||||
|
||||
To regenerate the NOTICES file after updating dependencies:
|
||||
```bash
|
||||
pnpm run generate-notices
|
||||
```
|
||||
|
||||
## Disclaimer
|
||||
|
||||
Crystal is an independent project created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1). Claude™ is a trademark of Anthropic, PBC. Crystal is not affiliated with, endorsed by, or sponsored by Anthropic. This tool is designed to work with Claude Code, which must be installed separately.
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<img src="frontend/public/stravu-logo.png" alt="Stravu Logo" width="80" height="80">
|
||||
<br>
|
||||
Made with ❤️ by <a href="https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1">Stravu</a>
|
||||
<a href="https://nimbalyst.com/">
|
||||
<img src="https://nimbalyst.com/_astro/ai-agent-transcript.Bd8j1G0q_BQpgv.webp" alt="Nimbalyst Agent Window" width="960" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Migration
|
||||
|
||||
- Download Nimbalyst: https://nimbalyst.com/
|
||||
- Documentation: https://docs.nimbalyst.com/
|
||||
- GitHub repository: https://github.com/Nimbalyst/nimbalyst
|
||||
|
||||
## Nimbalyst Features
|
||||
|
||||
- AI-native workspace for human + AI collaboration
|
||||
- AI agents that stream edits directly into open editors in real time
|
||||
- Multi-editor environment for code, markdown, spreadsheets, diagrams, and visual docs
|
||||
- Extension-first architecture for custom editor/file-type support
|
||||
- Local-first file model using open formats like Markdown, JSON, and CSV
|
||||
- Code-aware agent orchestration for implementation planning and task execution
|
||||
- Git worktree isolation for safer parallel AI coding sessions
|
||||
- Rich markdown editing with tables, code blocks, embeds, and formatting tools
|
||||
- Monaco-based code editing experience for programming workflows
|
||||
- RevoGrid-powered spreadsheet editing for CSV and tabular workflows
|
||||
- Excalidraw integration for diagram and whiteboard workflows
|
||||
- Visual data modeling tools for schema-centric work
|
||||
- Visual mockup editing for interface ideation and iteration
|
||||
- Unified editor lifecycle with consistent AI integration across editor types
|
||||
- Auto-save and file watching for reliable local development workflows
|
||||
- Project-level workspace management and AI session tracking
|
||||
- Built on production-grade desktop foundations with Electron
|
||||
|
||||
## FAQ
|
||||
|
||||
- **Is Crystal discontinued?** Yes. Crystal is deprecated and replaced by Nimbalyst.
|
||||
- **Can I still use Crystal?** Yes. You can continue using Crystal, but we recommend moving to Nimbalyst for active updates.
|
||||
- **Where is Nimbalyst?** https://nimbalyst.com/
|
||||
|
||||
For downloads, documentation, and updates, go to **https://nimbalyst.com/**.
|
||||
|
||||
@ -9,6 +9,12 @@ exports.default = async function(context) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we have signing certificates - if not, skip signing-related operations
|
||||
const hasSigningCredentials = process.env.CSC_LINK || process.env.CSC_KEY_PASSWORD;
|
||||
if (!hasSigningCredentials) {
|
||||
console.log('AfterSign: No signing credentials found, skipping certificate-dependent operations');
|
||||
}
|
||||
|
||||
console.log('AfterSign: Starting JAR cleanup process...');
|
||||
console.log('AfterSign: appOutDir =', appOutDir);
|
||||
console.log('AfterSign: productName =', packager.appInfo.productName);
|
||||
|
||||
720
docs/ADDING_NEW_CLI_TOOLS.md
Normal file
@ -0,0 +1,720 @@
|
||||
# Adding New CLI Tools to Crystal
|
||||
|
||||
This guide explains how to extend Crystal to support additional CLI tools beyond Claude Code. Crystal's architecture has been designed with extensibility in mind, using abstract base classes and a registry pattern.
|
||||
|
||||
## Table of Contents
|
||||
- [Overview](#overview)
|
||||
- [Architecture](#architecture)
|
||||
- [Step-by-Step Implementation](#step-by-step-implementation)
|
||||
- [Testing Your Integration](#testing-your-integration)
|
||||
- [Database Considerations](#database-considerations)
|
||||
- [Best Practices](#best-practices)
|
||||
|
||||
## Overview
|
||||
|
||||
Crystal uses a modular architecture that allows you to add support for new CLI tools (like Aider, Continue, Cursor, etc.) by:
|
||||
1. Creating a manager class that extends `AbstractCliManager`
|
||||
2. Registering the tool in the CLI tool registry
|
||||
3. Adding frontend panel components
|
||||
4. Updating type definitions
|
||||
|
||||
## Architecture
|
||||
|
||||
### Key Components
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Frontend (React) │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ CliPanelFactory → YourCliPanel → BaseCliPanel │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
↕ IPC
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Main Process (Electron) │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ CliToolRegistry → YourCliManager → AbstractCliManager │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Core Classes
|
||||
|
||||
- **`AbstractCliManager`**: Base class providing common CLI management functionality
|
||||
- **`CliToolRegistry`**: Singleton registry for managing CLI tools
|
||||
- **`CliPanelFactory`**: Factory for rendering appropriate CLI panels
|
||||
- **`BaseCliPanel`**: (Optional) Base React component with common UI elements
|
||||
|
||||
## Step-by-Step Implementation
|
||||
|
||||
### Step 1: Create Your CLI Manager
|
||||
|
||||
Create a new manager class in `main/src/services/panels/[your-cli]/`:
|
||||
|
||||
```typescript
|
||||
// main/src/services/panels/aider/aiderManager.ts
|
||||
import { AbstractCliManager } from '../cli/AbstractCliManager';
|
||||
import type { Logger } from '../../../utils/logger';
|
||||
import type { ConfigManager } from '../../configManager';
|
||||
|
||||
interface AiderSpawnOptions {
|
||||
panelId: string;
|
||||
sessionId: string;
|
||||
worktreePath: string;
|
||||
prompt: string;
|
||||
conversationHistory?: string[];
|
||||
// Add your CLI-specific options
|
||||
model?: string;
|
||||
editFormat?: 'whole' | 'diff' | 'patch';
|
||||
}
|
||||
|
||||
export class AiderManager extends AbstractCliManager {
|
||||
constructor(
|
||||
sessionManager: any,
|
||||
logger?: Logger,
|
||||
configManager?: ConfigManager
|
||||
) {
|
||||
super(sessionManager, logger, configManager);
|
||||
}
|
||||
|
||||
// Required abstract method implementations
|
||||
|
||||
protected getCliToolName(): string {
|
||||
return 'Aider';
|
||||
}
|
||||
|
||||
protected async testCliAvailability(customPath?: string): Promise<{
|
||||
available: boolean;
|
||||
error?: string;
|
||||
version?: string;
|
||||
path?: string;
|
||||
}> {
|
||||
// Implement CLI availability test
|
||||
try {
|
||||
const { execSync } = require('child_process');
|
||||
const command = customPath || 'aider';
|
||||
const version = execSync(`${command} --version`, { encoding: 'utf8' }).trim();
|
||||
return {
|
||||
available: true,
|
||||
version,
|
||||
path: command
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
available: false,
|
||||
error: `Aider not found: ${error}`
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
protected buildCommandArgs(options: AiderSpawnOptions): string[] {
|
||||
const args: string[] = [];
|
||||
|
||||
// Add your CLI-specific arguments
|
||||
if (options.model) {
|
||||
args.push('--model', options.model);
|
||||
}
|
||||
|
||||
if (options.editFormat) {
|
||||
args.push('--edit-format', options.editFormat);
|
||||
}
|
||||
|
||||
// Add the prompt
|
||||
if (options.prompt) {
|
||||
args.push('--message', options.prompt);
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
protected async getCliExecutablePath(): Promise<string> {
|
||||
// Check for custom path in config
|
||||
const customPath = this.configManager?.getConfig()?.aiderExecutablePath;
|
||||
if (customPath) {
|
||||
return customPath;
|
||||
}
|
||||
|
||||
// Otherwise find in PATH
|
||||
const { findExecutableInPath } = require('../../../utils/shellPath');
|
||||
const foundPath = findExecutableInPath('aider');
|
||||
if (!foundPath) {
|
||||
throw new Error('Aider not found in PATH');
|
||||
}
|
||||
return foundPath;
|
||||
}
|
||||
|
||||
protected parseCliOutput(
|
||||
data: string,
|
||||
panelId: string,
|
||||
sessionId: string
|
||||
): Array<{
|
||||
panelId: string;
|
||||
sessionId: string;
|
||||
type: 'json' | 'stdout' | 'stderr';
|
||||
data: any;
|
||||
timestamp: Date;
|
||||
}> {
|
||||
// Parse your CLI's output format
|
||||
const events = [];
|
||||
|
||||
// Example: if your CLI outputs JSON
|
||||
try {
|
||||
const jsonMessage = JSON.parse(data.trim());
|
||||
events.push({
|
||||
panelId,
|
||||
sessionId,
|
||||
type: 'json' as const,
|
||||
data: jsonMessage,
|
||||
timestamp: new Date()
|
||||
});
|
||||
} catch {
|
||||
// Treat as regular output
|
||||
events.push({
|
||||
panelId,
|
||||
sessionId,
|
||||
type: 'stdout' as const,
|
||||
data,
|
||||
timestamp: new Date()
|
||||
});
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
protected async initializeCliEnvironment(options: AiderSpawnOptions): Promise<{
|
||||
[key: string]: string;
|
||||
}> {
|
||||
// Set up environment variables for your CLI
|
||||
return {
|
||||
AIDER_AUTO_COMMITS: 'false',
|
||||
// Add other environment variables
|
||||
};
|
||||
}
|
||||
|
||||
protected async cleanupCliResources(sessionId: string): Promise<void> {
|
||||
// Clean up any resources specific to your CLI
|
||||
// e.g., temp files, cache, etc.
|
||||
}
|
||||
|
||||
protected getCliNotAvailableMessage(error?: string): string {
|
||||
return [
|
||||
`Error: ${error}`,
|
||||
'',
|
||||
'Aider is not installed or not found in your PATH.',
|
||||
'',
|
||||
'Please install Aider:',
|
||||
'1. Run: pip install aider-chat',
|
||||
'2. Verify installation by running "aider --version" in your terminal',
|
||||
'',
|
||||
'If Aider is installed but not in your PATH:',
|
||||
'- Add the Aider installation directory to your PATH',
|
||||
'- Or set a custom Aider path in Crystal Settings'
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
// Public methods for panel interaction
|
||||
|
||||
async startPanel(
|
||||
panelId: string,
|
||||
sessionId: string,
|
||||
worktreePath: string,
|
||||
prompt: string,
|
||||
model?: string
|
||||
): Promise<void> {
|
||||
const options: AiderSpawnOptions = {
|
||||
panelId,
|
||||
sessionId,
|
||||
worktreePath,
|
||||
prompt,
|
||||
model
|
||||
};
|
||||
return this.spawnCliProcess(options);
|
||||
}
|
||||
|
||||
async continuePanel(
|
||||
panelId: string,
|
||||
sessionId: string,
|
||||
worktreePath: string,
|
||||
prompt: string,
|
||||
conversationHistory: any[]
|
||||
): Promise<void> {
|
||||
// Implement continuation logic for your CLI
|
||||
const options: AiderSpawnOptions = {
|
||||
panelId,
|
||||
sessionId,
|
||||
worktreePath,
|
||||
prompt,
|
||||
conversationHistory
|
||||
};
|
||||
return this.spawnCliProcess(options);
|
||||
}
|
||||
|
||||
async stopPanel(panelId: string): Promise<void> {
|
||||
return this.killProcess(panelId);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Register Your CLI Tool
|
||||
|
||||
Add your tool to the registry in `main/src/services/cliManagerFactory.ts`:
|
||||
|
||||
```typescript
|
||||
// main/src/services/cliManagerFactory.ts
|
||||
import { AiderManager } from './panels/aider/aiderManager';
|
||||
|
||||
export function registerBuiltInTools(
|
||||
registry: CliToolRegistry,
|
||||
sessionManager: any,
|
||||
logger?: Logger,
|
||||
configManager?: ConfigManager,
|
||||
permissionIpcPath?: string | null
|
||||
): void {
|
||||
// Existing Claude registration...
|
||||
|
||||
// Register Aider
|
||||
registry.registerTool({
|
||||
id: 'aider',
|
||||
name: 'Aider',
|
||||
description: 'AI pair programming in your terminal',
|
||||
managerClass: AiderManager,
|
||||
icon: 'terminal', // or custom icon
|
||||
config: {
|
||||
executablePath: 'aider',
|
||||
defaultModel: 'gpt-4',
|
||||
// Add other default config
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Add Type Definitions
|
||||
|
||||
Update the shared types in `shared/types/`:
|
||||
|
||||
```typescript
|
||||
// shared/types/panels.ts
|
||||
export type ToolPanelType =
|
||||
| 'terminal'
|
||||
| 'claude'
|
||||
| 'aider' // Add your tool here
|
||||
| 'diff'
|
||||
| 'editor'
|
||||
| 'logs'
|
||||
| 'dashboard';
|
||||
|
||||
// shared/types/cliPanels.ts
|
||||
export type CliPanelType = 'claude' | 'aider'; // Add your tool here
|
||||
|
||||
// Add specific state interfaces if needed
|
||||
export interface AiderPanelState {
|
||||
model?: string;
|
||||
editFormat?: 'whole' | 'diff' | 'patch';
|
||||
autoCommits?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Create Frontend Panel Component
|
||||
|
||||
Create your panel component in `frontend/src/components/panels/[your-cli]/`:
|
||||
|
||||
```typescript
|
||||
// frontend/src/components/panels/aider/AiderPanel.tsx
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Terminal } from 'lucide-react';
|
||||
import { BaseCliPanel } from '../cli/BaseCliPanel'; // Optional
|
||||
import { usePanelStore } from '../../../stores/panelStore';
|
||||
|
||||
interface AiderPanelProps {
|
||||
panelId: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export const AiderPanel: React.FC<AiderPanelProps> = ({
|
||||
panelId,
|
||||
sessionId
|
||||
}) => {
|
||||
const { activePanel, panels } = usePanelStore();
|
||||
const [output, setOutput] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
// Set up IPC listeners for output
|
||||
const handleOutput = (event: any, data: any) => {
|
||||
if (data.panelId === panelId) {
|
||||
setOutput(prev => [...prev, data.data]);
|
||||
}
|
||||
};
|
||||
|
||||
window.electron.on('panel:output', handleOutput);
|
||||
|
||||
// Initialize panel if needed
|
||||
if (activePanel === panelId) {
|
||||
window.electron.invoke('panels:initialize', panelId);
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.electron.off('panel:output', handleOutput);
|
||||
};
|
||||
}, [panelId, activePanel]);
|
||||
|
||||
const handleInput = async (input: string) => {
|
||||
await window.electron.invoke('panels:send-input', panelId, input);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex items-center justify-between p-4 border-b border-border-primary">
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="w-4 h-4" />
|
||||
<span className="font-medium">Aider</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-auto p-4">
|
||||
{output.map((line, index) => (
|
||||
<div key={index} className="font-mono text-sm">
|
||||
{line}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border-primary p-4">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Type your message..."
|
||||
className="w-full px-3 py-2 bg-surface-secondary rounded"
|
||||
onKeyPress={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleInput(e.currentTarget.value);
|
||||
e.currentTarget.value = '';
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### Step 5: Update Panel Factory
|
||||
|
||||
Add your panel to the factory in `frontend/src/components/panels/cli/CliPanelFactory.tsx`:
|
||||
|
||||
```typescript
|
||||
// frontend/src/components/panels/cli/CliPanelFactory.tsx
|
||||
import { AiderPanel } from '../aider/AiderPanel';
|
||||
|
||||
export const CliPanelFactory: React.FC<CliPanelFactoryProps> = ({
|
||||
panel
|
||||
}) => {
|
||||
switch (panel.type) {
|
||||
case 'claude':
|
||||
return <ClaudePanel panelId={panel.id} sessionId={panel.session_id} />;
|
||||
|
||||
case 'aider':
|
||||
return <AiderPanel panelId={panel.id} sessionId={panel.session_id} />;
|
||||
|
||||
default:
|
||||
return (
|
||||
<div className="p-4 text-text-secondary">
|
||||
Unknown panel type: {panel.type}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Step 6: Add IPC Handlers
|
||||
|
||||
Create IPC handlers for your CLI in `main/src/ipc/[your-cli].ts`:
|
||||
|
||||
```typescript
|
||||
// main/src/ipc/aider.ts
|
||||
import { ipcMain } from 'electron';
|
||||
import { getCliManagerFactory } from '../services/cliManagerFactory';
|
||||
|
||||
export function registerAiderHandlers() {
|
||||
const factory = getCliManagerFactory();
|
||||
const registry = factory.getRegistry();
|
||||
|
||||
ipcMain.handle('aider:start', async (event, panelId, sessionId, options) => {
|
||||
const manager = registry.createManager('aider');
|
||||
return manager.startPanel(
|
||||
panelId,
|
||||
sessionId,
|
||||
options.worktreePath,
|
||||
options.prompt,
|
||||
options.model
|
||||
);
|
||||
});
|
||||
|
||||
ipcMain.handle('aider:send-input', async (event, panelId, input) => {
|
||||
const manager = registry.getManager('aider');
|
||||
return manager.sendInput(panelId, input);
|
||||
});
|
||||
|
||||
ipcMain.handle('aider:stop', async (event, panelId) => {
|
||||
const manager = registry.getManager('aider');
|
||||
return manager.stopPanel(panelId);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Your Integration
|
||||
|
||||
### 1. Test CLI Availability
|
||||
```typescript
|
||||
// In your test file or console
|
||||
const manager = new AiderManager(sessionManager, logger, configManager);
|
||||
const result = await manager.testCliAvailability();
|
||||
console.log('Aider available:', result);
|
||||
```
|
||||
|
||||
### 2. Test Process Spawning
|
||||
```typescript
|
||||
// Test spawning a process
|
||||
await manager.startPanel(
|
||||
'test-panel-1',
|
||||
'test-session-1',
|
||||
'/path/to/project',
|
||||
'Hello from Aider'
|
||||
);
|
||||
```
|
||||
|
||||
### 3. Test Output Parsing
|
||||
```typescript
|
||||
// Test your output parser
|
||||
const output = manager.parseCliOutput(
|
||||
'{"type": "message", "content": "Hello"}',
|
||||
'panel-1',
|
||||
'session-1'
|
||||
);
|
||||
console.log('Parsed output:', output);
|
||||
```
|
||||
|
||||
## Database Considerations
|
||||
|
||||
Crystal's database schema is flexible and can accommodate new CLI tools without migration:
|
||||
|
||||
- The `tool_panels` table has a `type` column that accepts any string value
|
||||
- Panel-specific state is stored as JSON in the `state` column
|
||||
- No schema changes are needed for new CLI tools
|
||||
|
||||
### Storing CLI-Specific Data
|
||||
|
||||
```typescript
|
||||
// When creating a panel
|
||||
const panelData = {
|
||||
id: generateId(),
|
||||
session_id: sessionId,
|
||||
type: 'aider', // Your CLI type
|
||||
name: 'Aider Session',
|
||||
state: JSON.stringify({
|
||||
model: 'gpt-4',
|
||||
editFormat: 'diff',
|
||||
// Your CLI-specific state
|
||||
})
|
||||
};
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Error Handling
|
||||
Always provide clear error messages and recovery paths:
|
||||
|
||||
```typescript
|
||||
protected async testCliAvailability(): Promise<CliAvailabilityResult> {
|
||||
try {
|
||||
// Test CLI
|
||||
} catch (error) {
|
||||
return {
|
||||
available: false,
|
||||
error: this.getCliNotAvailableMessage(error.message)
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Resource Cleanup
|
||||
Always clean up resources when panels are closed:
|
||||
|
||||
```typescript
|
||||
protected async cleanupCliResources(sessionId: string): Promise<void> {
|
||||
// Clean up temp files
|
||||
const tempDir = path.join(os.tmpdir(), `aider-${sessionId}`);
|
||||
if (fs.existsSync(tempDir)) {
|
||||
fs.rmSync(tempDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Clear any caches
|
||||
this.clearCache(sessionId);
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Output Formatting
|
||||
Provide consistent output formatting for better UX:
|
||||
|
||||
```typescript
|
||||
protected parseCliOutput(data: string): OutputEvent[] {
|
||||
// Detect different output types
|
||||
if (this.isToolCall(data)) {
|
||||
return this.formatToolCall(data);
|
||||
}
|
||||
if (this.isError(data)) {
|
||||
return this.formatError(data);
|
||||
}
|
||||
return this.formatStandard(data);
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Configuration
|
||||
Allow users to customize CLI behavior:
|
||||
|
||||
```typescript
|
||||
// In your manager
|
||||
const getCliConfig = () => {
|
||||
return {
|
||||
executablePath: this.configManager?.getConfig()?.aiderPath,
|
||||
defaultModel: this.configManager?.getConfig()?.aiderModel || 'gpt-4',
|
||||
autoCommits: this.configManager?.getConfig()?.aiderAutoCommits ?? false
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
### 5. Process Management
|
||||
Handle process lifecycle properly:
|
||||
|
||||
```typescript
|
||||
// Override spawnCliProcess if needed for special handling
|
||||
async spawnCliProcess(options: AiderSpawnOptions): Promise<void> {
|
||||
// Pre-spawn setup
|
||||
await this.validateEnvironment(options);
|
||||
|
||||
// Call parent implementation
|
||||
await super.spawnCliProcess(options);
|
||||
|
||||
// Post-spawn setup
|
||||
await this.initializeSession(options);
|
||||
}
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Stream Processing
|
||||
For CLIs that stream output:
|
||||
|
||||
```typescript
|
||||
protected handleStreamData(chunk: Buffer, panelId: string): void {
|
||||
const lines = chunk.toString().split('\n');
|
||||
for (const line of lines) {
|
||||
if (line.trim()) {
|
||||
const events = this.parseCliOutput(line, panelId, this.getSessionId(panelId));
|
||||
events.forEach(event => this.emit('output', event));
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Session Persistence
|
||||
To support session resumption:
|
||||
|
||||
```typescript
|
||||
async continuePanel(panelId: string, sessionId: string, ...args): Promise<void> {
|
||||
// Load previous session state
|
||||
const sessionState = await this.loadSessionState(sessionId);
|
||||
|
||||
// Reconstruct command with session context
|
||||
const options = this.buildContinuationOptions(sessionState, ...args);
|
||||
|
||||
return this.spawnCliProcess(options);
|
||||
}
|
||||
```
|
||||
|
||||
### Interactive Commands
|
||||
For CLIs that require interaction:
|
||||
|
||||
```typescript
|
||||
async sendInput(panelId: string, input: string): Promise<void> {
|
||||
const process = this.processes.get(panelId);
|
||||
if (!process) {
|
||||
throw new Error(`No process found for panel ${panelId}`);
|
||||
}
|
||||
|
||||
// Handle special commands
|
||||
if (this.isSpecialCommand(input)) {
|
||||
return this.handleSpecialCommand(panelId, input);
|
||||
}
|
||||
|
||||
// Send to CLI
|
||||
process.write(input + '\n');
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **CLI not found**: Ensure the CLI is installed and in PATH
|
||||
2. **Process won't start**: Check permissions and working directory
|
||||
3. **Output not displaying**: Verify output parsing and event emission
|
||||
4. **Panel not updating**: Check IPC event listeners and handlers
|
||||
|
||||
### Debug Tips
|
||||
|
||||
1. Enable verbose logging in your manager
|
||||
2. Add console.log statements in critical paths
|
||||
3. Use Chrome DevTools for frontend debugging
|
||||
4. Check the main process console for backend errors
|
||||
|
||||
## Examples
|
||||
|
||||
### Minimal CLI Integration
|
||||
|
||||
For a simple CLI that just needs basic I/O:
|
||||
|
||||
```typescript
|
||||
export class SimpleCliManager extends AbstractCliManager {
|
||||
protected getCliToolName(): string {
|
||||
return 'SimpleCLI';
|
||||
}
|
||||
|
||||
protected buildCommandArgs(options: any): string[] {
|
||||
return [options.prompt];
|
||||
}
|
||||
|
||||
protected async getCliExecutablePath(): Promise<string> {
|
||||
return 'simple-cli';
|
||||
}
|
||||
|
||||
// Use default implementations for other methods
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced CLI Integration
|
||||
|
||||
For complex CLIs with multiple features:
|
||||
|
||||
```typescript
|
||||
export class AdvancedCliManager extends AbstractCliManager {
|
||||
private sessions = new Map<string, SessionContext>();
|
||||
private configCache = new Map<string, any>();
|
||||
|
||||
// Override multiple methods for advanced behavior
|
||||
// Add session management, caching, etc.
|
||||
}
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
When adding a new CLI tool to Crystal:
|
||||
|
||||
1. Follow the existing code style and patterns
|
||||
2. Add comprehensive error handling
|
||||
3. Include debug logging for troubleshooting
|
||||
4. Test thoroughly with different scenarios
|
||||
5. Update this documentation if you discover new patterns
|
||||
|
||||
## Support
|
||||
|
||||
For questions or issues with CLI integration:
|
||||
1. Check existing CLI implementations (ClaudeCodeManager) for examples
|
||||
2. Review the AbstractCliManager base class documentation
|
||||
3. Open an issue on the Crystal GitHub repository
|
||||
304
docs/ANALYTICS_UI_EVENTS_INTEGRATION.md
Normal file
@ -0,0 +1,304 @@
|
||||
# Analytics UI Events Integration Guide
|
||||
|
||||
This document describes how to integrate UI interaction event tracking into Crystal's frontend components.
|
||||
|
||||
## Overview
|
||||
|
||||
The analytics system has been implemented with:
|
||||
1. Backend IPC handlers in `/main/src/ipc/analytics.ts`
|
||||
2. AnalyticsManager service enhancements to support string arrays
|
||||
3. Frontend service utility in `/frontend/src/services/analyticsService.ts`
|
||||
4. Preload script exposure for secure IPC communication
|
||||
|
||||
## Backend Implementation
|
||||
|
||||
### IPC Handlers
|
||||
- **File**: `/main/src/ipc/analytics.ts`
|
||||
- **Registered**: In `/main/src/ipc/index.ts`
|
||||
- **Service Integration**: AnalyticsManager added to AppServices in `/main/src/ipc/types.ts`
|
||||
|
||||
### IPC Endpoints
|
||||
|
||||
1. `analytics:track-ui-event` - Track UI interaction events
|
||||
2. `analytics:categorize-result-count` - Helper to categorize search result counts
|
||||
3. `analytics:hash-session-id` - Helper to hash session IDs for privacy
|
||||
|
||||
## Frontend Integration Points
|
||||
|
||||
### Using the AnalyticsService
|
||||
|
||||
Import the service:
|
||||
```typescript
|
||||
import { AnalyticsService } from '@/services/analyticsService';
|
||||
```
|
||||
|
||||
### Event 1: view_switched
|
||||
|
||||
**Track when users switch between tabs (Output, Diff, Logs, Editor, etc.)**
|
||||
|
||||
**Where to implement:**
|
||||
- Component: `/frontend/src/components/SessionView.tsx` or `/frontend/src/hooks/useSessionView.ts`
|
||||
- Trigger: When user clicks on a tab to switch views
|
||||
- Implementation example:
|
||||
|
||||
```typescript
|
||||
const handleViewSwitch = async (fromView: string, toView: string, sessionId?: string) => {
|
||||
// Hash the session ID for privacy
|
||||
const sessionIdHash = sessionId
|
||||
? await AnalyticsService.hashSessionId(sessionId)
|
||||
: undefined;
|
||||
|
||||
await AnalyticsService.trackViewSwitched({
|
||||
from_view: fromView,
|
||||
to_view: toView,
|
||||
session_id_hash: sessionIdHash,
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
**View names to use:**
|
||||
- `output` - Main output view
|
||||
- `diff` - Git diff view
|
||||
- `logs` - Logs/terminal view
|
||||
- `editor` - Editor view
|
||||
- `dashboard` - Dashboard view
|
||||
|
||||
### Event 2: help_dialog_opened
|
||||
|
||||
**Track when users open the help dialog**
|
||||
|
||||
**Where to implement:**
|
||||
- Component: `/frontend/src/components/Help.tsx` (or wherever the help dialog trigger is)
|
||||
- Trigger: When the help button/icon is clicked
|
||||
- Implementation example:
|
||||
|
||||
```typescript
|
||||
const handleHelpOpen = async (location: string) => {
|
||||
await AnalyticsService.trackHelpDialogOpened({
|
||||
from_location: location,
|
||||
});
|
||||
|
||||
// Then open the help dialog
|
||||
setShowHelp(true);
|
||||
};
|
||||
```
|
||||
|
||||
**Location values to use:**
|
||||
- `sidebar` - From sidebar help button
|
||||
- `toolbar` - From toolbar help button
|
||||
- `settings` - From settings page
|
||||
- `keyboard_shortcut` - From keyboard shortcut
|
||||
|
||||
### Event 3: settings_opened
|
||||
|
||||
**Track when users open settings**
|
||||
|
||||
**Where to implement:**
|
||||
- Component: `/frontend/src/components/Settings.tsx` (or wherever settings trigger is)
|
||||
- Trigger: When settings dialog/page is opened
|
||||
- Implementation example:
|
||||
|
||||
```typescript
|
||||
const handleSettingsOpen = async (location: string) => {
|
||||
await AnalyticsService.trackSettingsOpened({
|
||||
from_location: location,
|
||||
});
|
||||
|
||||
// Then open settings
|
||||
setShowSettings(true);
|
||||
};
|
||||
```
|
||||
|
||||
**Location values to use:**
|
||||
- `sidebar` - From sidebar settings button
|
||||
- `menu` - From menu bar
|
||||
- `keyboard_shortcut` - From keyboard shortcut
|
||||
|
||||
### Event 4: settings_saved
|
||||
|
||||
**Track when users save settings changes**
|
||||
|
||||
**Where to implement:**
|
||||
- Component: `/frontend/src/components/Settings.tsx`
|
||||
- Trigger: When user clicks "Save" or settings are persisted
|
||||
- Implementation example:
|
||||
|
||||
```typescript
|
||||
const handleSettingsSave = async (category: string, changedKeys: string[]) => {
|
||||
await AnalyticsService.trackSettingsSaved({
|
||||
category: category,
|
||||
setting_keys: changedKeys,
|
||||
});
|
||||
|
||||
// Then save the settings
|
||||
await window.electronAPI.config.update(updatedSettings);
|
||||
};
|
||||
```
|
||||
|
||||
**Category values to use:**
|
||||
- `general` - General settings
|
||||
- `notifications` - Notification settings
|
||||
- `project` - Project-specific settings
|
||||
- `appearance` - UI/appearance settings
|
||||
- `advanced` - Advanced settings
|
||||
|
||||
**Setting keys examples:**
|
||||
- `verbose_logging`
|
||||
- `api_key`
|
||||
- `notification_enabled`
|
||||
- `notification_sound`
|
||||
- `custom_prompt`
|
||||
- `main_branch`
|
||||
|
||||
### Event 5: sidebar_toggled
|
||||
|
||||
**Track when users show/hide the sidebar**
|
||||
|
||||
**Where to implement:**
|
||||
- Component: Main layout component (likely in `/frontend/src/App.tsx` or similar)
|
||||
- Trigger: When sidebar visibility changes
|
||||
- Implementation example:
|
||||
|
||||
```typescript
|
||||
const handleSidebarToggle = async (isVisible: boolean) => {
|
||||
await AnalyticsService.trackSidebarToggled({
|
||||
is_visible: isVisible,
|
||||
});
|
||||
|
||||
// Then toggle sidebar
|
||||
setSidebarVisible(isVisible);
|
||||
};
|
||||
```
|
||||
|
||||
### Event 6: search_used
|
||||
|
||||
**Track when users use search functionality**
|
||||
|
||||
**Where to implement:**
|
||||
- Component: Search components (likely in `/frontend/src/components/DraggableProjectTreeView.tsx` or search bar component)
|
||||
- Trigger: When search is executed (on Enter or search button click)
|
||||
- Implementation example:
|
||||
|
||||
```typescript
|
||||
const handleSearch = async (searchTerm: string, searchType: string, resultCount: number) => {
|
||||
// Categorize the result count for privacy (don't track exact numbers)
|
||||
const resultCategory = await AnalyticsService.categorizeResultCount(resultCount);
|
||||
|
||||
await AnalyticsService.trackSearchUsed({
|
||||
search_type: searchType,
|
||||
result_count_category: resultCategory,
|
||||
});
|
||||
|
||||
// Note: Do NOT track the actual search term for privacy
|
||||
};
|
||||
```
|
||||
|
||||
**Search type values to use:**
|
||||
- `sessions` - Searching sessions
|
||||
- `prompts` - Searching prompts
|
||||
- `files` - Searching files
|
||||
- `projects` - Searching projects
|
||||
|
||||
**Result count categories** (automatically categorized by backend):
|
||||
- `0-0` - No results
|
||||
- `1-5` - Few results
|
||||
- `6-10` - Some results
|
||||
- `11-25` - Many results
|
||||
- `26-50` - Lots of results
|
||||
- `51-100` - Very many results
|
||||
- `101+` - Tons of results
|
||||
|
||||
## Privacy Considerations
|
||||
|
||||
### Do NOT Track:
|
||||
- ❌ Actual search terms
|
||||
- ❌ File names or paths
|
||||
- ❌ Prompt content
|
||||
- ❌ User identifiable information
|
||||
- ❌ Exact counts (use categories)
|
||||
- ❌ Raw session IDs (always hash them)
|
||||
|
||||
### DO Track:
|
||||
- ✅ Event types (which button was clicked)
|
||||
- ✅ Categories and types
|
||||
- ✅ Hashed/anonymized identifiers
|
||||
- ✅ Boolean states (visible/hidden, enabled/disabled)
|
||||
- ✅ Categorized counts (0-5, 6-10, etc.)
|
||||
|
||||
## Testing
|
||||
|
||||
To test analytics integration:
|
||||
|
||||
1. **Enable analytics** in settings
|
||||
2. **Enable verbose logging** to see analytics events in the console
|
||||
3. **Perform actions** that should trigger events
|
||||
4. **Check logs** for messages like:
|
||||
```
|
||||
[Analytics] Tracked event: view_switched { from_view: 'output', to_view: 'diff', ... }
|
||||
```
|
||||
|
||||
## Type Safety
|
||||
|
||||
The `AnalyticsService` class provides type-safe methods for all events. TypeScript will enforce:
|
||||
- Correct event names
|
||||
- Required properties for each event type
|
||||
- Proper value types for each property
|
||||
|
||||
If you try to pass invalid data, you'll get a TypeScript error at compile time.
|
||||
|
||||
## Error Handling
|
||||
|
||||
All analytics methods:
|
||||
- Are non-blocking (use `async/await` but don't wait for responses)
|
||||
- Fail silently (errors are logged but don't break functionality)
|
||||
- Check if analytics is enabled before tracking
|
||||
- Handle cases where the electronAPI is not available
|
||||
|
||||
## Example: Complete Integration
|
||||
|
||||
Here's a complete example of integrating view switching in a component:
|
||||
|
||||
```typescript
|
||||
import React, { useState } from 'react';
|
||||
import { AnalyticsService } from '@/services/analyticsService';
|
||||
|
||||
export function SessionView({ sessionId }: { sessionId: string }) {
|
||||
const [currentView, setCurrentView] = useState<'output' | 'diff' | 'logs' | 'editor'>('output');
|
||||
|
||||
const switchView = async (newView: typeof currentView) => {
|
||||
// Track the view switch
|
||||
const sessionIdHash = await AnalyticsService.hashSessionId(sessionId);
|
||||
await AnalyticsService.trackViewSwitched({
|
||||
from_view: currentView,
|
||||
to_view: newView,
|
||||
session_id_hash: sessionIdHash,
|
||||
});
|
||||
|
||||
// Update the view
|
||||
setCurrentView(newView);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="tabs">
|
||||
<button onClick={() => switchView('output')}>Output</button>
|
||||
<button onClick={() => switchView('diff')}>Diff</button>
|
||||
<button onClick={() => switchView('logs')}>Logs</button>
|
||||
<button onClick={() => switchView('editor')}>Editor</button>
|
||||
</div>
|
||||
{/* View content here */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Summary
|
||||
|
||||
All backend infrastructure is complete. Frontend developers should:
|
||||
|
||||
1. Import `AnalyticsService` from `/frontend/src/services/analyticsService.ts`
|
||||
2. Call the appropriate tracking method when user actions occur
|
||||
3. Follow the privacy guidelines (no PII, use hashing/categorization)
|
||||
4. Test with verbose logging enabled to verify events are tracked
|
||||
|
||||
The tracking is opt-in (users can disable analytics in settings) and respects user privacy by design.
|
||||
336
docs/FEATURE_USAGE_TRACKING_INTEGRATION.md
Normal file
@ -0,0 +1,336 @@
|
||||
# Feature Usage Tracking Integration Guide
|
||||
|
||||
This document provides guidance on integrating the remaining feature usage tracking events into Crystal's frontend.
|
||||
|
||||
## Overview
|
||||
|
||||
The following feature usage events have been fully implemented:
|
||||
- ✅ `run_script_executed` - Tracked in backend (logsManager)
|
||||
- ✅ `notification_shown` - Tracked in frontend (useNotifications hook)
|
||||
|
||||
The following events require frontend integration:
|
||||
- ⏳ `keyboard_shortcut_used` - Integration points documented below
|
||||
- ⏳ `drag_drop_used` - Integration points documented below
|
||||
|
||||
## Keyboard Shortcut Tracking
|
||||
|
||||
### Event Properties
|
||||
```typescript
|
||||
{
|
||||
shortcut_key: string; // e.g., "Cmd+Enter", "Ctrl+K", "Escape"
|
||||
action: string; // e.g., "submit_input", "focus_search", "close_dialog"
|
||||
}
|
||||
```
|
||||
|
||||
### Integration Points
|
||||
|
||||
#### 1. AI Input Panels (Cmd/Ctrl+Enter)
|
||||
**File**: `/frontend/src/hooks/useAIInputPanel.ts` (line ~311)
|
||||
|
||||
**Current Code**:
|
||||
```typescript
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
**Add Tracking**:
|
||||
```typescript
|
||||
import { AnalyticsService } from '../services/analyticsService';
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
|
||||
// Track keyboard shortcut usage
|
||||
AnalyticsService.trackKeyboardShortcut({
|
||||
shortcut_key: `${e.metaKey ? 'Cmd' : 'Ctrl'}+Enter`,
|
||||
action: 'submit_ai_input',
|
||||
}).catch(console.error);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### 2. Session Input (Cmd/Ctrl+Enter)
|
||||
**File**: `/frontend/src/components/session/SessionInput.tsx` (line ~50-60)
|
||||
|
||||
**Similar pattern** - Add tracking when Cmd/Ctrl+Enter is pressed to submit session input.
|
||||
|
||||
#### 3. File Editor Shortcuts
|
||||
**File**: `/frontend/src/components/panels/editor/FileEditor.tsx`
|
||||
|
||||
**Keyboard shortcuts to track**:
|
||||
- Save file: `Cmd/Ctrl+S`
|
||||
- Close editor: `Escape`
|
||||
- Any other Monaco editor keyboard shortcuts
|
||||
|
||||
**Add event listener**:
|
||||
```typescript
|
||||
// In useEffect or Monaco configuration
|
||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
|
||||
handleSave();
|
||||
AnalyticsService.trackKeyboardShortcut({
|
||||
shortcut_key: 'Cmd+S',
|
||||
action: 'save_file',
|
||||
}).catch(console.error);
|
||||
});
|
||||
```
|
||||
|
||||
#### 4. Dialog Shortcuts (Escape to close)
|
||||
**Files to check**:
|
||||
- `/frontend/src/components/CreateSessionDialog.tsx`
|
||||
- `/frontend/src/components/CommitDialog.tsx`
|
||||
- `/frontend/src/components/ConfirmDialog.tsx`
|
||||
- `/frontend/src/components/Help.tsx`
|
||||
|
||||
**Pattern**:
|
||||
```typescript
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
handleClose();
|
||||
AnalyticsService.trackKeyboardShortcut({
|
||||
shortcut_key: 'Escape',
|
||||
action: 'close_dialog',
|
||||
}).catch(console.error);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### 5. Search/Navigation Shortcuts
|
||||
**File**: `/frontend/src/components/DraggableProjectTreeView.tsx`
|
||||
|
||||
If implementing keyboard shortcuts for search or navigation (e.g., `/` to focus search, arrow keys for navigation), track them here.
|
||||
|
||||
### Analytics Service Method to Add
|
||||
|
||||
**File**: `/frontend/src/services/analyticsService.ts`
|
||||
|
||||
```typescript
|
||||
export interface KeyboardShortcutProperties {
|
||||
shortcut_key: string;
|
||||
action: string;
|
||||
}
|
||||
|
||||
// In UIEventName type
|
||||
export type UIEventName =
|
||||
| 'view_switched'
|
||||
| 'help_dialog_opened'
|
||||
| 'settings_opened'
|
||||
| 'settings_saved'
|
||||
| 'sidebar_toggled'
|
||||
| 'search_used'
|
||||
| 'notification_shown'
|
||||
| 'keyboard_shortcut_used'; // Add this
|
||||
|
||||
// Add method to class
|
||||
static async trackKeyboardShortcut(properties: KeyboardShortcutProperties): Promise<void> {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
try {
|
||||
await window.electronAPI.analytics.trackUIEvent({
|
||||
event: 'keyboard_shortcut_used',
|
||||
properties,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[Analytics] Failed to track keyboard_shortcut_used:', error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Backend IPC Handler Update
|
||||
|
||||
**File**: `/main/src/ipc/analytics.ts`
|
||||
|
||||
```typescript
|
||||
interface KeyboardShortcutUsedEvent extends Record<string, string | number | boolean | string[] | undefined> {
|
||||
shortcut_key: string;
|
||||
action: string;
|
||||
}
|
||||
|
||||
type AnalyticsEventData =
|
||||
| { event: 'view_switched'; properties: ViewSwitchedEvent }
|
||||
| { event: 'help_dialog_opened'; properties: HelpDialogOpenedEvent }
|
||||
| { event: 'settings_opened'; properties: SettingsOpenedEvent }
|
||||
| { event: 'settings_saved'; properties: SettingsSavedEvent }
|
||||
| { event: 'sidebar_toggled'; properties: SidebarToggledEvent }
|
||||
| { event: 'search_used'; properties: SearchUsedEvent }
|
||||
| { event: 'notification_shown'; properties: NotificationShownEvent }
|
||||
| { event: 'keyboard_shortcut_used'; properties: KeyboardShortcutUsedEvent };
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Drag and Drop Tracking
|
||||
|
||||
### Event Properties
|
||||
```typescript
|
||||
{
|
||||
item_type: string; // "session" | "folder" | "project"
|
||||
target_type: string; // "session" | "folder" | "project" | "root"
|
||||
}
|
||||
```
|
||||
|
||||
### Integration Point
|
||||
|
||||
**File**: `/frontend/src/components/DraggableProjectTreeView.tsx`
|
||||
|
||||
This component already has comprehensive drag-and-drop functionality. The drag state is managed in the `dragState` state variable.
|
||||
|
||||
#### Key Handlers to Instrument
|
||||
|
||||
**1. handleDrop handler** (line ~800-1000)
|
||||
|
||||
This is the main drop handler where drag-and-drop actions are completed. Add tracking here.
|
||||
|
||||
**Current pattern**:
|
||||
```typescript
|
||||
const handleDrop = async (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
// ... existing drop logic ...
|
||||
|
||||
if (dragState.type && dragState.overType) {
|
||||
// Handle different drop scenarios
|
||||
// ... move session, move folder, etc. ...
|
||||
}
|
||||
|
||||
// Reset drag state
|
||||
setDragState({ ... });
|
||||
};
|
||||
```
|
||||
|
||||
**Add Tracking**:
|
||||
```typescript
|
||||
import { AnalyticsService } from '../services/analyticsService';
|
||||
|
||||
const handleDrop = async (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const sourceType = dragState.type;
|
||||
const targetType = dragState.overType;
|
||||
|
||||
// ... existing drop logic ...
|
||||
|
||||
if (sourceType && targetType) {
|
||||
// Track successful drag and drop
|
||||
AnalyticsService.trackDragDrop({
|
||||
item_type: sourceType,
|
||||
target_type: targetType,
|
||||
}).catch(console.error);
|
||||
}
|
||||
|
||||
// Reset drag state
|
||||
setDragState({ ... });
|
||||
};
|
||||
```
|
||||
|
||||
**2. Track only successful drops**
|
||||
|
||||
Make sure to only track when the drop is successful and changes are saved to the database. Place the tracking call after successful API calls:
|
||||
|
||||
```typescript
|
||||
// After successful session move
|
||||
await API.sessions.update(dragState.sessionId, { folder_id: targetFolderId });
|
||||
|
||||
// Track the drag-drop action
|
||||
AnalyticsService.trackDragDrop({
|
||||
item_type: 'session',
|
||||
target_type: targetType || 'root',
|
||||
}).catch(console.error);
|
||||
```
|
||||
|
||||
### Analytics Service Method to Add
|
||||
|
||||
**File**: `/frontend/src/services/analyticsService.ts`
|
||||
|
||||
```typescript
|
||||
export interface DragDropUsedProperties {
|
||||
item_type: string;
|
||||
target_type: string;
|
||||
}
|
||||
|
||||
// In UIEventName type
|
||||
export type UIEventName =
|
||||
| 'view_switched'
|
||||
| 'help_dialog_opened'
|
||||
| 'settings_opened'
|
||||
| 'settings_saved'
|
||||
| 'sidebar_toggled'
|
||||
| 'search_used'
|
||||
| 'notification_shown'
|
||||
| 'keyboard_shortcut_used'
|
||||
| 'drag_drop_used'; // Add this
|
||||
|
||||
// Add method to class
|
||||
static async trackDragDrop(properties: DragDropUsedProperties): Promise<void> {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
try {
|
||||
await window.electronAPI.analytics.trackUIEvent({
|
||||
event: 'drag_drop_used',
|
||||
properties,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[Analytics] Failed to track drag_drop_used:', error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Backend IPC Handler Update
|
||||
|
||||
**File**: `/main/src/ipc/analytics.ts`
|
||||
|
||||
```typescript
|
||||
interface DragDropUsedEvent extends Record<string, string | number | boolean | string[] | undefined> {
|
||||
item_type: string;
|
||||
target_type: string;
|
||||
}
|
||||
|
||||
type AnalyticsEventData =
|
||||
| { event: 'view_switched'; properties: ViewSwitchedEvent }
|
||||
| { event: 'help_dialog_opened'; properties: HelpDialogOpenedEvent }
|
||||
| { event: 'settings_opened'; properties: SettingsOpenedEvent }
|
||||
| { event: 'settings_saved'; properties: SettingsSavedEvent }
|
||||
| { event: 'sidebar_toggled'; properties: SidebarToggledEvent }
|
||||
| { event: 'search_used'; properties: SearchUsedEvent }
|
||||
| { event: 'notification_shown'; properties: NotificationShownEvent }
|
||||
| { event: 'keyboard_shortcut_used'; properties: KeyboardShortcutUsedEvent }
|
||||
| { event: 'drag_drop_used'; properties: DragDropUsedEvent };
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
After implementing the above tracking:
|
||||
|
||||
1. **Enable analytics** in Crystal settings
|
||||
2. **Configure PostHog API key** in settings
|
||||
3. **Use the features** that trigger the events:
|
||||
- Press keyboard shortcuts
|
||||
- Drag and drop sessions/folders
|
||||
4. **Verify in PostHog dashboard** that events are being tracked
|
||||
5. **Check console logs** for any tracking errors
|
||||
|
||||
## Privacy Considerations
|
||||
|
||||
- ✅ No user-identifiable information is tracked
|
||||
- ✅ All session IDs are hashed before sending
|
||||
- ✅ Only event counts and categorical data are tracked
|
||||
- ✅ Users can disable analytics in settings
|
||||
- ✅ Analytics respect the user's privacy preferences
|
||||
|
||||
## Summary
|
||||
|
||||
| Event | Status | Implementation |
|
||||
|-------|--------|---------------|
|
||||
| `run_script_executed` | ✅ Complete | Backend (logsManager.ts) |
|
||||
| `notification_shown` | ✅ Complete | Frontend (useNotifications.ts) |
|
||||
| `keyboard_shortcut_used` | ⏳ Documentation Ready | Follow integration guide above |
|
||||
| `drag_drop_used` | ⏳ Documentation Ready | Follow integration guide above |
|
||||
521
docs/IMPLEMENTING_NEW_CLI_AGENTS.md
Normal file
@ -0,0 +1,521 @@
|
||||
# Implementing New CLI Agents in Crystal
|
||||
|
||||
This guide provides step-by-step instructions for adding support for new CLI agent tools (like Aider, Continue, Cursor, etc.) to Crystal's architecture.
|
||||
|
||||
## Table of Contents
|
||||
- [Overview](#overview)
|
||||
- [Architecture Summary](#architecture-summary)
|
||||
- [Implementation Steps](#implementation-steps)
|
||||
- [File Structure](#file-structure)
|
||||
- [Code Examples](#code-examples)
|
||||
- [Testing Your Implementation](#testing-your-implementation)
|
||||
- [Common Patterns](#common-patterns)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
|
||||
## Overview
|
||||
|
||||
Crystal's architecture is designed to be extensible, allowing new CLI agents to be added with minimal modifications to existing code. The system follows a plugin-like pattern where each CLI tool is self-contained in its own directory structure.
|
||||
|
||||
### What You'll Need to Build
|
||||
|
||||
1. **New Files (90% of the work)**
|
||||
- Backend manager class extending `AbstractCliManager`
|
||||
- Frontend React panel component
|
||||
- Protocol handlers (if needed)
|
||||
- Utility functions specific to your CLI
|
||||
|
||||
2. **Minimal Modifications (10% of the work)**
|
||||
- Register your tool (~4 lines)
|
||||
- Update UI factory (~3 lines)
|
||||
- Add type definitions (~2 lines)
|
||||
|
||||
## Architecture Summary
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Crystal Application │
|
||||
├─────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Frontend (React) Backend (Electron) │
|
||||
│ ┌──────────────┐ ┌──────────────────┐ │
|
||||
│ │ YourCliPanel │◄──IPC──►│ YourCliManager │ │
|
||||
│ └──────────────┘ └──────────────────┘ │
|
||||
│ ▲ │ │
|
||||
│ │ ▼ │
|
||||
│ ┌──────────────┐ ┌──────────────────┐ │
|
||||
│ │CliPanelFactory│ │AbstractCliManager│ │
|
||||
│ └──────────────┘ └──────────────────┘ │
|
||||
│ │ │
|
||||
└────────────────────────────────────┼────────────┘
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ Your CLI │
|
||||
│ (External) │
|
||||
└──────────────┘
|
||||
```
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Create the Backend Manager
|
||||
|
||||
Create a new directory for your CLI in `main/src/services/panels/[your-cli]/` and implement the manager class:
|
||||
|
||||
```typescript
|
||||
// main/src/services/panels/aider/aiderManager.ts
|
||||
import { AbstractCliManager } from '../cli/AbstractCliManager';
|
||||
|
||||
export class AiderManager extends AbstractCliManager {
|
||||
// Implement required abstract methods
|
||||
protected getCliToolName(): string {
|
||||
return 'Aider';
|
||||
}
|
||||
|
||||
protected async testCliAvailability(customPath?: string): Promise<{
|
||||
available: boolean;
|
||||
error?: string;
|
||||
version?: string;
|
||||
path?: string;
|
||||
}> {
|
||||
// Test if CLI is installed
|
||||
}
|
||||
|
||||
protected buildCommandArgs(options: any): string[] {
|
||||
// Build command-line arguments
|
||||
}
|
||||
|
||||
protected async getCliExecutablePath(): Promise<string> {
|
||||
// Return path to CLI executable
|
||||
}
|
||||
|
||||
protected parseCliOutput(data: string, panelId: string, sessionId: string): Array<any> {
|
||||
// Parse CLI output into events
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Create the Frontend Panel Component
|
||||
|
||||
Create React components in `frontend/src/components/panels/[your-cli]/`:
|
||||
|
||||
```typescript
|
||||
// frontend/src/components/panels/aider/AiderPanel.tsx
|
||||
import React from 'react';
|
||||
|
||||
export const AiderPanel: React.FC<{ panel: ToolPanel; isActive: boolean }> = ({ panel, isActive }) => {
|
||||
// Implement your panel UI
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Your UI here */}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Make it the default export for lazy loading
|
||||
export default AiderPanel;
|
||||
```
|
||||
|
||||
### Step 3: Register Your CLI Tool
|
||||
|
||||
Modify `main/src/services/cliManagerFactory.ts` to register your tool:
|
||||
|
||||
```typescript
|
||||
// In registerBuiltInTools() method around line 149-159:
|
||||
private registerBuiltInTools(): void {
|
||||
// Existing registrations...
|
||||
this.registerClaudeTool();
|
||||
|
||||
// Add your registration
|
||||
this.registerAiderTool(); // ADD THIS LINE
|
||||
}
|
||||
|
||||
// Add a new registration method:
|
||||
private registerAiderTool(): void {
|
||||
const aiderDefinition: CliToolDefinition = {
|
||||
id: 'aider',
|
||||
name: 'Aider',
|
||||
description: 'AI pair programming in your terminal',
|
||||
// ... other configuration
|
||||
managerFactory: (sessionManager, logger, configManager) =>
|
||||
new AiderManager(sessionManager, logger, configManager)
|
||||
};
|
||||
|
||||
this.registry.registerTool(aiderDefinition);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Update the Frontend Panel Factory
|
||||
|
||||
Modify `frontend/src/components/panels/cli/CliPanelFactory.tsx`:
|
||||
|
||||
```typescript
|
||||
// Add lazy import at the top (around line 82-83):
|
||||
const AiderPanel = lazy(() => import('../aider/AiderPanel'));
|
||||
|
||||
// Add case in renderPanel() switch statement (around line 104-118):
|
||||
case 'aider':
|
||||
return (
|
||||
<Suspense fallback={<LoadingFallback cliToolId={cliToolId} />}>
|
||||
<AiderPanel panel={panel} isActive={isActive} />
|
||||
</Suspense>
|
||||
);
|
||||
|
||||
// Update supported tools list (around line 149):
|
||||
const supportedTools = ['claude', 'codex', 'aider']; // ADD 'aider'
|
||||
```
|
||||
|
||||
### Step 5: Update Type Definitions
|
||||
|
||||
Modify `shared/types/panels.ts`:
|
||||
|
||||
```typescript
|
||||
// Update ToolPanelType union (line 10):
|
||||
export type ToolPanelType = 'terminal' | 'claude' | 'codex' | 'aider' | 'diff' | 'editor' | 'logs' | 'dashboard';
|
||||
|
||||
// Add panel state interface if needed (optional):
|
||||
export interface AiderPanelState extends BaseAIPanelState {
|
||||
// Aider-specific state
|
||||
editFormat?: 'whole' | 'diff' | 'patch';
|
||||
autoCommits?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
Your implementation should follow this structure:
|
||||
|
||||
```
|
||||
crystal/
|
||||
├── main/src/services/panels/aider/ # Backend implementation
|
||||
│ ├── aiderManager.ts # Main manager class (required)
|
||||
│ ├── aiderProtocol.ts # Protocol handling (if needed)
|
||||
│ ├── aiderMessageParser.ts # Output parsing utilities
|
||||
│ └── types.ts # TypeScript interfaces
|
||||
│
|
||||
├── frontend/src/components/panels/aider/ # Frontend implementation
|
||||
│ ├── AiderPanel.tsx # Main panel component (required)
|
||||
│ ├── AiderOutput.tsx # Output display component
|
||||
│ ├── AiderInput.tsx # Input component
|
||||
│ ├── AiderToolCalls.tsx # Tool call visualization
|
||||
│ └── styles.css # Component-specific styles
|
||||
│
|
||||
└── shared/types/ # Shared type definitions
|
||||
└── aiderTypes.ts # Aider-specific types (optional)
|
||||
```
|
||||
|
||||
## Code Examples
|
||||
|
||||
### Example: Simple CLI Manager
|
||||
|
||||
For a basic CLI that just needs stdin/stdout:
|
||||
|
||||
```typescript
|
||||
export class SimpleCliManager extends AbstractCliManager {
|
||||
protected getCliToolName(): string {
|
||||
return 'SimpleCLI';
|
||||
}
|
||||
|
||||
protected async testCliAvailability(customPath?: string): Promise<any> {
|
||||
try {
|
||||
const { execSync } = require('child_process');
|
||||
const cmd = customPath || 'simple-cli';
|
||||
const version = execSync(`${cmd} --version`, { encoding: 'utf8' });
|
||||
return { available: true, version: version.trim(), path: cmd };
|
||||
} catch {
|
||||
return { available: false, error: 'CLI not found' };
|
||||
}
|
||||
}
|
||||
|
||||
protected buildCommandArgs(options: any): string[] {
|
||||
return [options.prompt]; // Simple args
|
||||
}
|
||||
|
||||
protected async getCliExecutablePath(): Promise<string> {
|
||||
return 'simple-cli';
|
||||
}
|
||||
|
||||
protected parseCliOutput(data: string, panelId: string, sessionId: string): Array<any> {
|
||||
return [{
|
||||
panelId,
|
||||
sessionId,
|
||||
type: 'stdout',
|
||||
data,
|
||||
timestamp: new Date()
|
||||
}];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Example: Protocol-Based CLI Manager
|
||||
|
||||
For CLIs using JSON-RPC or similar protocols:
|
||||
|
||||
```typescript
|
||||
export class ProtocolCliManager extends AbstractCliManager {
|
||||
private protocol: ProtocolHandler;
|
||||
|
||||
constructor(sessionManager: any, logger?: Logger, configManager?: ConfigManager) {
|
||||
super(sessionManager, logger, configManager);
|
||||
this.protocol = new ProtocolHandler();
|
||||
}
|
||||
|
||||
protected parseCliOutput(data: string, panelId: string, sessionId: string): Array<any> {
|
||||
try {
|
||||
const message = JSON.parse(data);
|
||||
return this.protocol.handleMessage(message, panelId, sessionId);
|
||||
} catch {
|
||||
// Fallback to plain text
|
||||
return super.parseCliOutput(data, panelId, sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
async sendInput(panelId: string, input: string): Promise<void> {
|
||||
const message = this.protocol.createInputMessage(input);
|
||||
const process = this.processes.get(panelId);
|
||||
process?.write(JSON.stringify(message) + '\n');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Example: Minimal Panel Component
|
||||
|
||||
```typescript
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Terminal } from 'lucide-react';
|
||||
|
||||
export const MinimalPanel: React.FC<{ panel: any; isActive: boolean }> = ({ panel, isActive }) => {
|
||||
const [output, setOutput] = useState<string[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
// Listen for output
|
||||
const handleOutput = (event: any, data: any) => {
|
||||
if (data.panelId === panel.id) {
|
||||
setOutput(prev => [...prev, data.data]);
|
||||
}
|
||||
};
|
||||
|
||||
window.electron.on('panel:output', handleOutput);
|
||||
|
||||
// Initialize panel when active
|
||||
if (isActive && !panel.state.isInitialized) {
|
||||
window.electron.invoke('panels:initialize', panel.id);
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.electron.off('panel:output', handleOutput);
|
||||
};
|
||||
}, [panel.id, isActive]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (input.trim()) {
|
||||
await window.electron.invoke('panels:send-input', panel.id, input);
|
||||
setInput('');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col bg-surface-primary">
|
||||
<div className="flex items-center gap-2 p-4 border-b border-border-primary">
|
||||
<Terminal className="w-4 h-4" />
|
||||
<span className="font-medium">My CLI Tool</span>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-auto p-4 font-mono text-sm">
|
||||
{output.map((line, i) => (
|
||||
<div key={i}>{line}</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="p-4 border-t border-border-primary">
|
||||
<input
|
||||
type="text"
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyPress={(e) => e.key === 'Enter' && handleSubmit()}
|
||||
placeholder="Enter command..."
|
||||
className="w-full px-3 py-2 bg-surface-secondary rounded"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MinimalPanel;
|
||||
```
|
||||
|
||||
## Testing Your Implementation
|
||||
|
||||
### 1. Test CLI Availability
|
||||
|
||||
```bash
|
||||
# In the Electron dev console or a test file
|
||||
const factory = require('./main/src/services/cliManagerFactory');
|
||||
const manager = factory.createManager('aider', { sessionManager });
|
||||
const result = await manager.testCliAvailability();
|
||||
console.log('Aider available:', result);
|
||||
```
|
||||
|
||||
### 2. Test Process Spawning
|
||||
|
||||
```typescript
|
||||
// Test spawning a process
|
||||
await manager.startPanel(
|
||||
'test-panel-1',
|
||||
'test-session-1',
|
||||
'/path/to/project',
|
||||
'Test prompt'
|
||||
);
|
||||
```
|
||||
|
||||
### 3. Test Frontend Integration
|
||||
|
||||
1. Run Crystal in development mode
|
||||
2. Create a new session
|
||||
3. Add a tool panel and select your CLI
|
||||
4. Verify the panel renders and accepts input
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Pattern: Handling Authentication
|
||||
|
||||
If your CLI requires authentication:
|
||||
|
||||
```typescript
|
||||
protected async initializeCliEnvironment(options: any): Promise<Record<string, string>> {
|
||||
const apiKey = this.configManager?.getConfig()?.aiderApiKey;
|
||||
if (!apiKey) {
|
||||
throw new Error('API key required. Please configure in Settings.');
|
||||
}
|
||||
|
||||
return {
|
||||
AIDER_API_KEY: apiKey,
|
||||
...process.env
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern: Session Resumption
|
||||
|
||||
For CLIs that support resuming conversations:
|
||||
|
||||
```typescript
|
||||
async continuePanel(panelId: string, sessionId: string, conversationHistory: any[]): Promise<void> {
|
||||
const resumeArgs = this.buildResumeArgs(conversationHistory);
|
||||
const options = {
|
||||
panelId,
|
||||
sessionId,
|
||||
additionalArgs: resumeArgs
|
||||
};
|
||||
return this.spawnCliProcess(options);
|
||||
}
|
||||
|
||||
private buildResumeArgs(history: any[]): string[] {
|
||||
// Convert history to CLI-specific format
|
||||
return ['--resume', JSON.stringify(history)];
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern: Handling Tool Calls
|
||||
|
||||
For CLIs that perform file operations:
|
||||
|
||||
```typescript
|
||||
protected parseCliOutput(data: string, panelId: string, sessionId: string): Array<any> {
|
||||
const events = [];
|
||||
|
||||
// Detect tool calls
|
||||
if (this.isToolCall(data)) {
|
||||
const toolCall = this.parseToolCall(data);
|
||||
events.push({
|
||||
type: 'tool_call',
|
||||
tool: toolCall.name,
|
||||
args: toolCall.args
|
||||
});
|
||||
|
||||
// Emit file change event if applicable
|
||||
if (toolCall.name === 'write_file') {
|
||||
this.emit('files:changed', {
|
||||
panelId,
|
||||
files: [toolCall.args.path]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues and Solutions
|
||||
|
||||
1. **CLI not found**
|
||||
- Ensure the CLI is installed and in PATH
|
||||
- Check `getCliExecutablePath()` returns correct path
|
||||
- Verify `testCliAvailability()` handles errors properly
|
||||
|
||||
2. **Panel not rendering**
|
||||
- Verify lazy import path is correct
|
||||
- Check panel is registered in `CliPanelFactory`
|
||||
- Ensure component has default export
|
||||
|
||||
3. **No output displayed**
|
||||
- Check `parseCliOutput()` returns proper event format
|
||||
- Verify IPC event listeners are set up
|
||||
- Ensure panel ID matches in events
|
||||
|
||||
4. **Input not working**
|
||||
- Verify process is running (`this.processes.get(panelId)`)
|
||||
- Check input formatting matches CLI expectations
|
||||
- Ensure write permissions on process stdin
|
||||
|
||||
### Debug Tips
|
||||
|
||||
1. **Enable verbose logging**:
|
||||
```typescript
|
||||
this.logger?.debug('[YourCli] Spawning process:', { command, args });
|
||||
```
|
||||
|
||||
2. **Add console output in frontend**:
|
||||
```typescript
|
||||
console.log('[YourCliPanel] Received output:', data);
|
||||
```
|
||||
|
||||
3. **Use Chrome DevTools**:
|
||||
- Open DevTools in Electron (Cmd/Ctrl+Shift+I)
|
||||
- Check Network tab for IPC calls
|
||||
- Monitor Console for errors
|
||||
|
||||
4. **Test CLI directly**:
|
||||
```bash
|
||||
# Test your CLI works outside Crystal
|
||||
your-cli --version
|
||||
echo "test prompt" | your-cli
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Error Handling**: Always provide clear error messages
|
||||
2. **Resource Cleanup**: Implement proper cleanup in `cleanupCliResources()`
|
||||
3. **State Persistence**: Store CLI-specific state for session resumption
|
||||
4. **User Feedback**: Show loading states and error messages in UI
|
||||
5. **Configuration**: Allow users to customize CLI behavior via settings
|
||||
6. **Documentation**: Comment complex parsing or protocol logic
|
||||
7. **Type Safety**: Use TypeScript interfaces for all data structures
|
||||
8. **Testing**: Write unit tests for parsing and protocol logic
|
||||
|
||||
## Next Steps
|
||||
|
||||
After implementing your CLI:
|
||||
|
||||
1. Test thoroughly in development mode
|
||||
2. Add configuration options to Settings UI
|
||||
3. Update Help documentation
|
||||
4. Consider contributing back to Crystal repository
|
||||
5. Share your implementation with the community
|
||||
|
||||
For more details on specific aspects:
|
||||
- [Abstract CLI Manager API](../main/src/services/panels/cli/AbstractCliManager.ts)
|
||||
- [CLI Tool Registry](../main/src/services/cliToolRegistry.ts)
|
||||
- [Example: Claude Implementation](../main/src/services/panels/claude/)
|
||||
- [Example: Codex Implementation](../main/src/services/panels/codex/)
|
||||
@ -35,7 +35,7 @@ The following licenses are **not** compatible with MIT distribution:
|
||||
|
||||
## How We Check
|
||||
|
||||
The `scripts/check-license-compatibility.sh` script automatically validates that all dependencies use compatible licenses. It:
|
||||
The `check-license-compatibility.sh` script automatically validates that all dependencies use compatible licenses. It:
|
||||
|
||||
1. Checks for truly incompatible licenses (GPL, AGPL, SSPL)
|
||||
2. Notes LGPL dependencies (compatible but worth tracking)
|
||||
|
||||
@ -1,204 +0,0 @@
|
||||
# Messages Tab Fix Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
This document details the fix implemented for the Messages tab in Crystal's session window. The Messages tab was intended to show JSON output from Claude Code for debugging purposes but was broken and not displaying any data.
|
||||
|
||||
## Problem Description
|
||||
|
||||
The Messages tab in the session view was supposed to display JSON messages from Claude Code instances for debugging, but it was showing "No messages yet" even when sessions had active Claude Code conversations. The issue was that there was no mechanism to load and populate the JSON messages data.
|
||||
|
||||
## Root Cause Analysis
|
||||
|
||||
1. **Missing Data Flow**: The `JsonMessageView` component expected `activeSession.jsonMessages` to be populated, but this array was always empty
|
||||
2. **No Loading Mechanism**: There was no IPC handler or frontend logic to fetch JSON messages separately from regular output
|
||||
3. **Data Transformation Issue**: The existing `sessions:get-output` handler was transforming JSON messages to formatted stdout for the Output tab, losing the original JSON structure
|
||||
|
||||
## Solution Architecture
|
||||
|
||||
The fix implements a complete end-to-end data flow:
|
||||
|
||||
```
|
||||
Frontend (Messages Tab) → API Layer → IPC Handler → Session Manager → Database
|
||||
```
|
||||
|
||||
### Key Components
|
||||
|
||||
1. **New IPC Handler**: `sessions:get-json-messages`
|
||||
2. **Frontend API Method**: `API.sessions.getJsonMessages()`
|
||||
3. **Session Store Method**: `setSessionJsonMessages()`
|
||||
4. **Auto-loading Logic**: Effect hook that loads JSON messages when switching to Messages view
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### 1. Backend IPC Handler (`main/src/ipc/session.ts`)
|
||||
|
||||
```typescript
|
||||
ipcMain.handle('sessions:get-json-messages', async (_event, sessionId: string) => {
|
||||
try {
|
||||
const outputs = await sessionManager.getSessionOutputs(sessionId);
|
||||
|
||||
// Filter to only JSON messages and include timestamp
|
||||
const jsonMessages = outputs
|
||||
.filter(output => output.type === 'json')
|
||||
.map(output => ({
|
||||
...output.data,
|
||||
timestamp: output.timestamp.toISOString()
|
||||
}));
|
||||
|
||||
return { success: true, data: jsonMessages };
|
||||
} catch (error) {
|
||||
return { success: false, error: 'Failed to get JSON messages' };
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**Purpose**: Extracts and returns only JSON-type outputs from session data, preserving the original JSON structure with timestamps.
|
||||
|
||||
### 2. Preload Script Update (`main/src/preload.ts`)
|
||||
|
||||
```typescript
|
||||
getJsonMessages: (sessionId: string): Promise<IPCResponse> =>
|
||||
ipcRenderer.invoke('sessions:get-json-messages', sessionId),
|
||||
```
|
||||
|
||||
**Purpose**: Exposes the new IPC handler to the frontend through the secure preload script.
|
||||
|
||||
### 3. Frontend API Layer (`frontend/src/utils/api.ts`)
|
||||
|
||||
```typescript
|
||||
async getJsonMessages(sessionId: string) {
|
||||
if (!isElectron()) throw new Error('Electron API not available');
|
||||
return window.electronAPI.sessions.getJsonMessages(sessionId);
|
||||
}
|
||||
```
|
||||
|
||||
**Purpose**: Provides a consistent API interface with error handling for the frontend to use.
|
||||
|
||||
### 4. Session Store Enhancement (`frontend/src/stores/sessionStore.ts`)
|
||||
|
||||
```typescript
|
||||
setSessionJsonMessages: (sessionId, jsonMessages) => set((state) => {
|
||||
// Update both regular sessions and activeMainRepoSession
|
||||
const updatedSessions = state.sessions.map(session => {
|
||||
if (session.id === sessionId) {
|
||||
return { ...session, jsonMessages };
|
||||
}
|
||||
return session;
|
||||
});
|
||||
|
||||
let updatedActiveMainRepoSession = state.activeMainRepoSession;
|
||||
if (state.activeMainRepoSession?.id === sessionId) {
|
||||
updatedActiveMainRepoSession = { ...state.activeMainRepoSession, jsonMessages };
|
||||
}
|
||||
|
||||
return { ...state, sessions: updatedSessions, activeMainRepoSession: updatedActiveMainRepoSession };
|
||||
})
|
||||
```
|
||||
|
||||
**Purpose**: Updates session state with JSON messages while maintaining consistency between regular sessions and main repo sessions.
|
||||
|
||||
### 5. Session View Hook (`frontend/src/hooks/useSessionView.ts`)
|
||||
|
||||
```typescript
|
||||
// Load JSON messages for the Messages tab
|
||||
const loadJsonMessages = useCallback(async (sessionId: string) => {
|
||||
try {
|
||||
const response = await API.sessions.getJsonMessages(sessionId);
|
||||
if (response.success) {
|
||||
const jsonMessages = response.data || [];
|
||||
useSessionStore.getState().setSessionJsonMessages(sessionId, jsonMessages);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error loading JSON messages:`, error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Load JSON messages when switching to messages view
|
||||
useEffect(() => {
|
||||
if (!activeSession || viewMode !== 'messages') return;
|
||||
loadJsonMessages(activeSession.id);
|
||||
}, [activeSession?.id, viewMode, loadJsonMessages]);
|
||||
```
|
||||
|
||||
**Purpose**: Automatically loads JSON messages when the user switches to the Messages tab, ensuring data is available when needed.
|
||||
|
||||
### 6. TypeScript Definitions (`frontend/src/types/electron.d.ts`)
|
||||
|
||||
```typescript
|
||||
interface ElectronAPI {
|
||||
sessions: {
|
||||
// ... other methods
|
||||
getJsonMessages: (sessionId: string) => Promise<IPCResponse>;
|
||||
// ... other methods
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Purpose**: Provides type safety for the new IPC method in TypeScript.
|
||||
|
||||
## Data Flow
|
||||
|
||||
1. **User Action**: User clicks on "Messages" tab in session view
|
||||
2. **View Mode Change**: `viewMode` state changes to 'messages'
|
||||
3. **Effect Trigger**: useEffect hook detects the view mode change
|
||||
4. **API Call**: `loadJsonMessages()` function calls `API.sessions.getJsonMessages()`
|
||||
5. **IPC Communication**: Frontend calls the `sessions:get-json-messages` IPC handler
|
||||
6. **Data Retrieval**: Backend fetches session outputs and filters for JSON messages
|
||||
7. **Response**: Filtered JSON messages returned to frontend
|
||||
8. **State Update**: `setSessionJsonMessages()` updates the session store
|
||||
9. **UI Update**: `JsonMessageView` component re-renders with the new data
|
||||
|
||||
## Message Structure
|
||||
|
||||
JSON messages are formatted with the following structure:
|
||||
|
||||
```typescript
|
||||
interface JsonMessage {
|
||||
type: string; // e.g., 'system', 'user', 'assistant'
|
||||
subtype?: string; // e.g., 'init', 'result'
|
||||
content?: string; // Message content
|
||||
data?: any; // Additional structured data
|
||||
timestamp: string; // ISO timestamp
|
||||
[key: string]: any; // Other fields from Claude Code
|
||||
}
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Debugging Capability**: Developers can now inspect raw JSON messages from Claude Code
|
||||
2. **Performance**: JSON messages are only loaded when the Messages tab is viewed
|
||||
3. **Real-time**: Messages are loaded fresh each time the tab is accessed
|
||||
4. **Type Safety**: Full TypeScript support for the new functionality
|
||||
5. **Consistency**: Follows existing patterns in the codebase
|
||||
|
||||
## Testing
|
||||
|
||||
The fix was tested by:
|
||||
|
||||
1. **Type Checking**: `pnpm typecheck` passes without errors
|
||||
2. **Compilation**: `pnpm build:main` succeeds
|
||||
3. **Runtime Testing**: Application starts successfully in development mode
|
||||
4. **Integration**: IPC handlers are properly registered and accessible
|
||||
|
||||
## Files Modified
|
||||
|
||||
- `main/src/ipc/session.ts` - Added new IPC handler
|
||||
- `main/src/preload.ts` - Exposed new method to frontend
|
||||
- `frontend/src/utils/api.ts` - Added API method
|
||||
- `frontend/src/stores/sessionStore.ts` - Added state management method
|
||||
- `frontend/src/hooks/useSessionView.ts` - Added loading logic
|
||||
- `frontend/src/types/electron.d.ts` - Added TypeScript definitions
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential improvements could include:
|
||||
|
||||
1. **Caching**: Cache JSON messages to avoid repeated API calls
|
||||
2. **Real-time Updates**: Listen for new JSON messages and update the tab live
|
||||
3. **Filtering**: Add filtering/search capabilities within the Messages tab
|
||||
4. **Export**: Allow exporting JSON messages for external debugging tools
|
||||
|
||||
## Conclusion
|
||||
|
||||
The Messages tab fix provides a complete solution for debugging Claude Code sessions by making the raw JSON messages accessible through a clean, type-safe interface. The implementation follows Crystal's architectural patterns and maintains consistency with existing code.
|
||||
47
docs/SESSION_OUTPUT_SYSTEM.md
Normal file
@ -0,0 +1,47 @@
|
||||
# Session Output Handling System
|
||||
|
||||
⚠️ **WARNING**: The session output handling system is complex and fragile. Modifying it frequently causes issues like duplicate messages, disappearing content, or blank screens. Any changes require explicit user permission.
|
||||
|
||||
## How It Works
|
||||
|
||||
### 1. Database Storage
|
||||
|
||||
- Raw JSON messages from Claude are stored as-is in the database
|
||||
- Stdout/stderr outputs are stored directly
|
||||
- No formatting or transformation happens at storage time
|
||||
|
||||
### 2. Real-time Streaming
|
||||
|
||||
- When Claude outputs data, it's saved to the database immediately
|
||||
- For JSON messages, a formatted stdout version is sent to the frontend for the Output view
|
||||
- The original JSON is also sent for the Messages view
|
||||
- This provides immediate visual feedback during active sessions
|
||||
|
||||
### 3. Session Loading
|
||||
|
||||
- When navigating to a session, outputs are loaded from the database
|
||||
- The `sessions:get-output` handler transforms JSON messages to formatted stdout on-the-fly
|
||||
- Uses `setSessionOutputs` for atomic updates to prevent race conditions
|
||||
|
||||
### 4. Frontend Display
|
||||
|
||||
- The useSessionView hook manages session view logic and state (extracted from SessionView component)
|
||||
- A mutex lock (`loadingRef`) prevents concurrent loads
|
||||
- Timing is carefully managed with `requestAnimationFrame` and delays
|
||||
- The `formattedOutput` state is NOT cleared on session switch - it updates naturally
|
||||
|
||||
### 5. Key Principles
|
||||
|
||||
- Database is the single source of truth
|
||||
- Transformations happen on-the-fly, not at storage time
|
||||
- Real-time updates supplement but don't replace database data
|
||||
- Session switches always reload from database to ensure consistency
|
||||
|
||||
## Common Issues and Solutions
|
||||
|
||||
- **Duplicate messages**: Usually caused by sending both formatted and raw versions
|
||||
- **Disappearing content**: Often due to clearing output states at the wrong time
|
||||
- **Black screens**: Typically from race conditions during session switching
|
||||
- **Content only loads once**: Results from improper state management or missing dependencies
|
||||
|
||||
The current implementation carefully balances real-time updates with data persistence to provide a smooth user experience.
|
||||
98
docs/STATE_MANAGEMENT.md
Normal file
@ -0,0 +1,98 @@
|
||||
# State Management Guidelines
|
||||
|
||||
⚠️ **IMPORTANT**: Crystal follows a targeted update pattern for state management to minimize unnecessary re-renders and network requests.
|
||||
|
||||
## Overview
|
||||
|
||||
Crystal uses a combination of Zustand stores, IPC events, and targeted updates to manage application state efficiently. The application prioritizes specific, targeted updates over global refreshes to improve performance and user experience.
|
||||
|
||||
## Key Principles
|
||||
|
||||
1. **Targeted Updates**: Always update only the specific data that changed
|
||||
2. **Event-Driven Updates**: Use IPC events to communicate changes between processes
|
||||
3. **Avoid Global Refreshes**: Never reload entire lists when only one item changes
|
||||
4. **Database as Source of Truth**: Frontend state should reflect backend state, not override it
|
||||
|
||||
## State Update Patterns
|
||||
|
||||
### Session Updates
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Global refresh
|
||||
const handleSessionCreated = () => {
|
||||
loadProjectsWithSessions(); // Reloads everything
|
||||
};
|
||||
|
||||
// ✅ GOOD: Targeted update
|
||||
const handleSessionCreated = (newSession: Session) => {
|
||||
setProjectsWithSessions(prevProjects => {
|
||||
return prevProjects.map(project => {
|
||||
if (project.id === newSession.projectId) {
|
||||
return {
|
||||
...project,
|
||||
sessions: [...project.sessions, newSession]
|
||||
};
|
||||
}
|
||||
return project;
|
||||
});
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
### Project Updates
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Reload all projects
|
||||
const handleProjectDeleted = () => {
|
||||
fetchProjects(); // Network request for all projects
|
||||
};
|
||||
|
||||
// ✅ GOOD: Remove from local state
|
||||
const handleProjectDeleted = () => {
|
||||
setProjects(prev => prev.filter(p => p.id !== deletedId));
|
||||
};
|
||||
```
|
||||
|
||||
## IPC Event Handling
|
||||
|
||||
The application uses IPC events to synchronize state between the main process and renderer:
|
||||
|
||||
### Session Events
|
||||
|
||||
- `session:created` - Add new session to appropriate project
|
||||
- `session:updated` - Update specific session properties
|
||||
- `session:deleted` - Remove session from project list
|
||||
|
||||
### Project Events (if implemented)
|
||||
|
||||
- `project:created` - Add new project to list
|
||||
- `project:updated` - Update specific project properties
|
||||
- `project:deleted` - Remove project from list
|
||||
|
||||
## When Global Refreshes Are Acceptable
|
||||
|
||||
- **Initial Load**: When component mounts for the first time
|
||||
- **User-Triggered Refresh**: When user explicitly requests a refresh
|
||||
- **Error Recovery**: After connection loss or critical errors
|
||||
- **Complex State Changes**: When multiple interdependent items change
|
||||
|
||||
## Implementation Examples
|
||||
|
||||
### DraggableProjectTreeView.tsx
|
||||
|
||||
- Uses targeted updates for session creation, update, and deletion
|
||||
- Only reloads all data on initial mount or when critical errors occur
|
||||
- Maintains local state synchronized with backend through IPC events
|
||||
|
||||
### ProjectSelector.tsx
|
||||
|
||||
- Updates project list locally when projects are deleted
|
||||
- Falls back to refresh only when necessary (e.g., complex updates)
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Use State Setters with Callbacks**: Always use the callback form of setState to ensure you're working with the latest state
|
||||
2. **Merge Updates**: When updating objects, spread existing properties to preserve data
|
||||
3. **Handle Edge Cases**: Always check if the item exists before updating
|
||||
4. **Log State Changes**: Add console logs for debugging state updates in development
|
||||
5. **Validate IPC Data**: Ensure IPC events contain expected data structure
|
||||
159
docs/TIMESTAMP_HANDLING.md
Normal file
@ -0,0 +1,159 @@
|
||||
# Timestamp Handling Guidelines
|
||||
|
||||
⚠️ **IMPORTANT**: Proper timestamp handling is critical for the application to function correctly, especially for prompt duration calculations.
|
||||
|
||||
## Overview
|
||||
|
||||
Crystal uses timestamps throughout the application for tracking session activity, prompt execution times, and displaying time-based information. Due to the mix of SQLite database storage and JavaScript Date objects, special care must be taken to ensure timezone consistency.
|
||||
|
||||
## Key Principles
|
||||
|
||||
1. **Database Storage**: All timestamps are stored in UTC using SQLite's `CURRENT_TIMESTAMP` or `datetime()` functions
|
||||
2. **Frontend Display**: Timestamps are parsed as UTC and converted to local time only for display
|
||||
3. **Consistency**: Always use the timestamp utility functions instead of manual date parsing
|
||||
4. **Validation**: Always validate timestamps before using them in calculations
|
||||
|
||||
## Timestamp Formats
|
||||
|
||||
- **SQLite DATETIME**: `YYYY-MM-DD HH:MM:SS` (stored in UTC without timezone indicator)
|
||||
- **ISO 8601**: `YYYY-MM-DDTHH:MM:SS.sssZ` (with explicit UTC timezone)
|
||||
- **JavaScript Date**: Local timezone by default (be careful!)
|
||||
|
||||
## Utility Functions
|
||||
|
||||
Crystal provides timestamp utilities in both frontend and backend:
|
||||
|
||||
### Backend (`main/src/utils/timestampUtils.ts`)
|
||||
|
||||
```typescript
|
||||
import { formatForDatabase, getCurrentTimestamp } from '../utils/timestampUtils';
|
||||
|
||||
// For database storage
|
||||
const timestamp = formatForDatabase(); // Returns ISO string
|
||||
const now = getCurrentTimestamp(); // Alias for formatForDatabase()
|
||||
|
||||
// For display formatting
|
||||
const displayTime = formatForDisplay(timestamp);
|
||||
```
|
||||
|
||||
### Frontend (`frontend/src/utils/timestampUtils.ts`)
|
||||
|
||||
```typescript
|
||||
import { parseTimestamp, formatDuration, getTimeDifference } from '../utils/timestampUtils';
|
||||
|
||||
// Parse SQLite timestamps correctly
|
||||
const date = parseTimestamp("2024-01-01 12:00:00"); // Handles UTC conversion
|
||||
|
||||
// Calculate durations
|
||||
const durationMs = getTimeDifference(startTime, endTime);
|
||||
const formatted = formatDuration(durationMs); // "2m 34s"
|
||||
|
||||
// Display relative time
|
||||
const ago = formatDistanceToNow(timestamp); // "5 minutes ago"
|
||||
```
|
||||
|
||||
## Database Operations
|
||||
|
||||
When working with timestamps in SQLite:
|
||||
|
||||
```sql
|
||||
-- Use datetime() for UTC timestamps
|
||||
INSERT INTO prompt_markers (timestamp) VALUES (datetime('now'));
|
||||
|
||||
-- When selecting, append 'Z' for proper UTC parsing
|
||||
SELECT datetime(timestamp) || 'Z' as timestamp FROM prompt_markers;
|
||||
|
||||
-- For completion timestamps with NULL handling
|
||||
SELECT
|
||||
CASE
|
||||
WHEN completion_timestamp IS NOT NULL
|
||||
THEN datetime(completion_timestamp) || 'Z'
|
||||
ELSE NULL
|
||||
END as completion_timestamp
|
||||
FROM prompt_markers;
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Creating a new timestamp
|
||||
|
||||
```typescript
|
||||
// Backend - for database storage
|
||||
const timestamp = formatForDatabase();
|
||||
|
||||
// Frontend - for immediate use
|
||||
const now = new Date();
|
||||
```
|
||||
|
||||
### Tracking prompt execution time
|
||||
|
||||
```typescript
|
||||
// When prompt starts
|
||||
db.addPromptMarker(sessionId, promptText, outputIndex);
|
||||
|
||||
// When prompt completes
|
||||
db.updatePromptMarkerCompletion(sessionId);
|
||||
```
|
||||
|
||||
### Calculating duration
|
||||
|
||||
```typescript
|
||||
// With completion timestamp
|
||||
if (prompt.completion_timestamp) {
|
||||
const duration = getTimeDifference(prompt.timestamp, prompt.completion_timestamp);
|
||||
return formatDuration(duration);
|
||||
}
|
||||
|
||||
// For ongoing prompts
|
||||
const duration = getTimeDifference(prompt.timestamp); // Uses current time as end
|
||||
return formatDuration(duration) + ' (ongoing)';
|
||||
```
|
||||
|
||||
## Common Pitfalls to Avoid
|
||||
|
||||
### 1. Never parse SQLite timestamps directly with `new Date()`
|
||||
|
||||
```typescript
|
||||
// ❌ WRONG - treats UTC as local time
|
||||
const date = new Date("2024-01-01 12:00:00");
|
||||
|
||||
// ✅ CORRECT - uses parseTimestamp utility
|
||||
const date = parseTimestamp("2024-01-01 12:00:00");
|
||||
```
|
||||
|
||||
### 2. Always validate timestamps before calculations
|
||||
|
||||
```typescript
|
||||
if (!isValidTimestamp(timestamp)) {
|
||||
return 'Unknown duration';
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Be careful with timezone conversions
|
||||
|
||||
```typescript
|
||||
// Database stores UTC, display shows local
|
||||
const dbTime = "2024-01-01 12:00:00"; // UTC
|
||||
const parsed = parseTimestamp(dbTime); // Correctly handled as UTC
|
||||
const display = formatForDisplay(parsed); // Converts to local for display
|
||||
```
|
||||
|
||||
### 4. Handle negative durations gracefully
|
||||
|
||||
```typescript
|
||||
const duration = endTime - startTime;
|
||||
if (duration < 0) {
|
||||
console.warn('Negative duration detected');
|
||||
return 'Invalid duration';
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Timestamp Code
|
||||
|
||||
When testing timestamp-related features:
|
||||
|
||||
1. Test with different timezones (especially negative UTC offsets)
|
||||
2. Test with daylight saving time transitions
|
||||
3. Test with very old and future timestamps
|
||||
4. Test with invalid/malformed timestamps
|
||||
5. Verify duration calculations are always positive
|
||||
106
docs/TOOL_PANEL_SYSTEM.md
Normal file
@ -0,0 +1,106 @@
|
||||
# Tool Panel System Implementation Guidelines
|
||||
|
||||
⚠️ **IMPORTANT**: The tool panel system implements a flexible, extensible architecture for managing multiple tool instances per session.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
The tool panel system consists of several key components:
|
||||
|
||||
1. **Panel Manager** (`main/src/services/panelManager.ts`): Central coordinator for panel lifecycle management
|
||||
2. **Terminal Panel Manager** (`main/src/services/terminalPanelManager.ts`): Specialized handler for terminal panel processes
|
||||
3. **Panel Event Bus** (`main/src/services/panelEventBus.ts`): Event communication system between panels
|
||||
4. **Panel Store** (`frontend/src/stores/panelStore.ts`): Frontend state management with Zustand
|
||||
5. **Panel Components**: React components for rendering different panel types
|
||||
|
||||
## Key Implementation Principles
|
||||
|
||||
1. **Lazy Initialization**: Panels are created in the database immediately but background processes (like terminal PTY) only start when the panel is first viewed
|
||||
2. **State Persistence**: All panel state including terminal scrollback, working directories, and configurations persist across application restarts
|
||||
3. **Memory Efficiency**: Inactive panels suspend rendering but maintain background processes
|
||||
4. **Event-Driven Updates**: Uses IPC events to synchronize state between main and renderer processes
|
||||
5. **Extensible Design**: Architecture supports future panel types beyond terminals
|
||||
|
||||
## Panel Lifecycle
|
||||
|
||||
1. **Creation**: User clicks "Add Tool" → Panel entry created in database → Added to UI
|
||||
2. **First View**: User clicks panel tab → Background process initializes → XTerm.js mounts
|
||||
3. **Switching**: User switches panels → Previous panel unmounts XTerm → New panel mounts
|
||||
4. **Background Operation**: Processes continue running even when panel is not visible
|
||||
5. **Deletion**: Panel closed → Process terminated → Database entry removed → UI updated
|
||||
|
||||
## Terminal Panel Specifics
|
||||
|
||||
- Each terminal panel spawns an independent PTY process using node-pty
|
||||
- Terminal state (scrollback, history, dimensions) persists in `tool_panels.state` as JSON
|
||||
- XTerm.js instances mount/unmount based on panel visibility to save memory
|
||||
- Working directories are maintained independently per panel
|
||||
- Command history and environment variables can be preserved across restarts
|
||||
|
||||
## Database Schema
|
||||
|
||||
- `tool_panels` table stores panel configuration and state
|
||||
- `sessions.active_panel_id` tracks the currently active panel per session
|
||||
- Foreign key constraints ensure panels are cleaned up when sessions are deleted
|
||||
|
||||
## Event System
|
||||
|
||||
- Terminal panels emit `terminal:command_executed`, `terminal:exit`, and `files:changed` events
|
||||
- Event bus routes events to subscribed panels (planned for future panel types)
|
||||
- Events support future inter-panel communication (e.g., diff panels reacting to file changes)
|
||||
|
||||
## Implemented Panel Types
|
||||
|
||||
The tool panel system currently supports 8 panel types:
|
||||
|
||||
1. **Terminal** (`terminal`) - Multiple PTY shells per session
|
||||
- Independent processes with command history and scrollback
|
||||
- File operation detection triggers `files:changed` events
|
||||
|
||||
2. **Claude** (`claude`) - Multiple Claude Code instances
|
||||
- Managed by `claudePanelManager.ts`
|
||||
- Permission mode: approve/ignore
|
||||
- Automatic context tracking with token usage display
|
||||
|
||||
3. **Codex** (`codex`) - Multiple Codex CLI instances
|
||||
- Managed by `codexPanelManager.ts`
|
||||
- Configurable model provider and approval policy
|
||||
- Sandbox mode and web search support
|
||||
|
||||
4. **Diff** (`diff`) - Git diff viewer (singleton, permanent)
|
||||
- View modes: split/unified
|
||||
- Whitespace and context line configuration
|
||||
- Auto-refreshes on file changes
|
||||
|
||||
5. **Editor** (`editor`) - In-app file editor
|
||||
- Syntax highlighting with Monaco
|
||||
- File tree with expanded directory tracking
|
||||
- Cursor position and scroll persistence
|
||||
|
||||
6. **Logs** (`logs`) - Script execution panel (singleton)
|
||||
- Process management with PID tracking
|
||||
- Output buffer with error/warning counts
|
||||
- Start/end time and exit code tracking
|
||||
|
||||
7. **Dashboard** (`dashboard`) - Project overview (singleton, permanent, projects-only)
|
||||
- Session health monitoring
|
||||
- Filter by status: all/stale/changes/pr
|
||||
- Cached data persistence
|
||||
|
||||
8. **Setup Tasks** (`setup-tasks`) - Project setup checklist (singleton, permanent, projects-only)
|
||||
- Task completion tracking
|
||||
- Dismissible tasks
|
||||
- Last check timestamp
|
||||
|
||||
## Panel Capabilities
|
||||
|
||||
Each panel type has specific capabilities defined in `PANEL_CAPABILITIES`:
|
||||
|
||||
- **requiresProcess**: Whether panel needs background process (terminal, claude, codex, logs)
|
||||
- **singleton**: Only one instance per session (diff, logs, dashboard, setup-tasks)
|
||||
- **permanent**: Cannot be closed by user (diff, dashboard, setup-tasks)
|
||||
- **canAppearInProjects**: Available in project view (all except diff)
|
||||
- **canAppearInWorktrees**: Available in worktree sessions (all except dashboard, setup-tasks)
|
||||
- **canEmit**: Events this panel can produce
|
||||
- **canConsume**: Events this panel listens to
|
||||
|
||||
Example: Diff panels are singleton + permanent + worktree-only, consuming `files:changed` and `terminal:command_executed` events to auto-refresh.
|
||||
45
docs/troubleshooting/DIFF_VIEWER_CSS.md
Normal file
@ -0,0 +1,45 @@
|
||||
# Diff Viewer CSS Troubleshooting
|
||||
|
||||
⚠️ **IMPORTANT**: The diff viewer (react-diff-viewer-continued) has specific CSS requirements that can be tricky to debug.
|
||||
|
||||
## Common Issue: No Scrollbars on Diff Viewer
|
||||
|
||||
If the diff viewer content is cut off and scrollbars don't appear:
|
||||
|
||||
1. **DO NOT add complex CSS overrides** - This often makes the problem worse
|
||||
2. **Check parent containers for `overflow-hidden`** - This is usually the root cause
|
||||
3. **Use simple `overflow: 'auto'`** on the immediate diff container
|
||||
4. **Remove any forced widths or min-widths** unless absolutely necessary
|
||||
|
||||
## The Solution That Works
|
||||
|
||||
```tsx
|
||||
// In DiffViewer.tsx - Keep it simple!
|
||||
<div className="border border-t-0 border-gray-600 rounded-b-lg" style={{ overflow: 'auto', maxHeight: '600px' }}>
|
||||
<ReactDiffViewer
|
||||
oldValue={file.oldValue || ''}
|
||||
newValue={file.newValue || ''}
|
||||
splitView={viewType === 'split'}
|
||||
useDarkTheme={isDarkMode}
|
||||
styles={currentStyles}
|
||||
// Don't add complex style overrides here
|
||||
/>
|
||||
</div>
|
||||
```
|
||||
|
||||
## What NOT to Do
|
||||
|
||||
- Don't add multiple wrapper divs with conflicting overflow settings
|
||||
- Don't use CSS-in-JS to override react-diff-viewer's internal styles
|
||||
- Don't add global CSS selectors targeting generated class names
|
||||
- Don't use JavaScript hacks to force reflows
|
||||
|
||||
## Root Cause
|
||||
|
||||
The issue is typically caused by parent containers having `overflow-hidden` which prevents child scrollbars from appearing. Check these files:
|
||||
|
||||
- `SessionView.tsx` - Look for `overflow-hidden` classes
|
||||
- `CombinedDiffView.tsx` - Check both the main container and flex containers
|
||||
- `App.tsx` - Sometimes the issue starts at the app root level
|
||||
|
||||
The react-diff-viewer-continued library uses emotion/styled-components internally, which makes CSS overrides unreliable. The best approach is to ensure proper overflow handling in parent containers and keep the diff viewer wrapper simple.
|
||||
75
docs/troubleshooting/SETUP_TROUBLESHOOTING.md
Normal file
@ -0,0 +1,75 @@
|
||||
# Setup Troubleshooting Guide
|
||||
|
||||
## Python distutils Error
|
||||
|
||||
If you encounter this error during `pnpm run setup`:
|
||||
```
|
||||
ModuleNotFoundError: No module named 'distutils'
|
||||
```
|
||||
|
||||
This happens because Python 3.12+ removed the `distutils` module that `node-gyp` depends on.
|
||||
|
||||
### Quick Fix:
|
||||
```bash
|
||||
brew install python-setuptools
|
||||
```
|
||||
|
||||
### Alternative Solutions:
|
||||
|
||||
1. **Use Python 3.11 with pyenv**:
|
||||
```bash
|
||||
brew install pyenv
|
||||
pyenv install 3.11.9
|
||||
pyenv global 3.11.9
|
||||
```
|
||||
|
||||
2. **Use the setup script**:
|
||||
```bash
|
||||
./setup-dev.sh
|
||||
```
|
||||
|
||||
## Other Common Issues
|
||||
|
||||
### electron-rebuild failures
|
||||
- Ensure Xcode Command Line Tools are installed: `xcode-select --install`
|
||||
- Clear node_modules and reinstall: `rm -rf node_modules && pnpm install`
|
||||
|
||||
### pnpm permission errors
|
||||
- Never use `sudo` with pnpm
|
||||
- Fix npm permissions: `npm config set prefix ~/.npm-global`
|
||||
|
||||
## Windows Build Requirements
|
||||
|
||||
### Spectre-mitigated Libraries Error
|
||||
|
||||
If you encounter this error during `pnpm run setup` on Windows:
|
||||
```
|
||||
LINK : fatal error LNK1181: cannot open input file 'MSVCRT.lib'
|
||||
```
|
||||
|
||||
Or similar errors mentioning missing `.lib` files, this means you need to install the Spectre-mitigated libraries in Visual Studio.
|
||||
|
||||
### Solution:
|
||||
|
||||
1. **Install Visual Studio 2022** (Community Edition is free):
|
||||
- Download from [https://visualstudio.microsoft.com/](https://visualstudio.microsoft.com/)
|
||||
|
||||
2. **Install Required Components**:
|
||||
- Open **Visual Studio Installer**
|
||||
- Click **Modify** on your Visual Studio 2022 installation
|
||||
- Go to the **Individual components** tab
|
||||
- Search for "Spectre" in the search box
|
||||
- Check the following components:
|
||||
- `MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs (Latest)`
|
||||
- `MSVC v143 - VS 2022 C++ ARM64/ARM64EC Spectre-mitigated libs (Latest)` (if building for ARM64)
|
||||
- Click **Modify** to install
|
||||
|
||||
3. **Restart your terminal** and run `pnpm run setup` again
|
||||
|
||||
### Why is this needed?
|
||||
|
||||
Node.js native modules on Windows are built with Visual Studio's C++ compiler. Recent security updates require Spectre-mitigated libraries to be installed separately. These libraries provide protection against Spectre vulnerability exploits.
|
||||
|
||||
### Alternative: Use Pre-built Binaries
|
||||
|
||||
If you're having trouble with the build process, consider waiting for official Windows binaries to be released in future versions of Crystal.
|
||||
@ -27,7 +27,7 @@ export default [
|
||||
'react-hooks/exhaustive-deps': 'warn',
|
||||
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
|
||||
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'no-console': ['warn', { allow: ['warn', 'error'] }],
|
||||
'no-useless-escape': 'warn' // Downgrade to warning for now
|
||||
|
||||
@ -7,8 +7,18 @@
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="./apple-touch-icon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Crystal</title>
|
||||
<script>
|
||||
// Apply theme class before React loads to prevent flash
|
||||
const savedTheme = localStorage.getItem('theme');
|
||||
const theme = savedTheme === 'light' ? 'light' : 'dark';
|
||||
document.documentElement.classList.add(theme);
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
// Also apply to body
|
||||
document.body.classList.add(localStorage.getItem('theme') === 'light' ? 'light' : 'dark');
|
||||
</script>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
|
||||
8647
frontend/package-lock.json
generated
Normal file
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.1.16",
|
||||
"version": "0.3.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@ -21,25 +21,30 @@
|
||||
"@radix-ui/react-switch": "^1.1.2",
|
||||
"@radix-ui/react-tabs": "^1.1.2",
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@xterm/addon-fit": "^0.10.0",
|
||||
"@xterm/addon-search": "^0.15.0",
|
||||
"@xterm/addon-web-links": "^0.11.0",
|
||||
"@xterm/xterm": "^5.5.0",
|
||||
"ansi-to-html": "^0.7.2",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"dompurify": "^3.2.6",
|
||||
"immer": "^10.1.3",
|
||||
"lucide-react": "^0.468.0",
|
||||
"mermaid": "^11.8.1",
|
||||
"mermaid": "^11.10.0",
|
||||
"monaco-editor": "^0.52.2",
|
||||
"react": "^19.0.0",
|
||||
"react-diff-viewer-continued": "^3.4.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-error-boundary": "^6.0.0",
|
||||
"react-json-view-lite": "^1.5.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^2.6.0",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"uuid": "^13.0.0",
|
||||
"zustand": "^5.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 68 KiB |
|
Before Width: | Height: | Size: 6.3 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 1.9 MiB After Width: | Height: | Size: 2.6 KiB |
58
frontend/public/nimbalyst-logo.svg
Normal file
@ -0,0 +1,58 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="940.23798mm"
|
||||
height="259.70303mm"
|
||||
viewBox="0 0 940.2378 259.70299"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs1">
|
||||
<linearGradient
|
||||
id="swatch194">
|
||||
<stop
|
||||
style="stop-color:#4d4d4d;stop-opacity:1;"
|
||||
offset="0"
|
||||
id="stop194" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id="swatch39">
|
||||
<stop
|
||||
style="stop-color:#999999;stop-opacity:1;"
|
||||
offset="0"
|
||||
id="stop39" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<g
|
||||
id="layer1"
|
||||
transform="translate(-106.07445,-87.677157)">
|
||||
<g
|
||||
id="g1"
|
||||
transform="matrix(0.25222225,0,0,0.25222225,142.37667,88.683763)">
|
||||
<path
|
||||
style="fill:#6395ff;fill-opacity:1;stroke:none;stroke-width:6;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1;paint-order:fill markers stroke"
|
||||
id="path65-5-5-5-5-5-7-5"
|
||||
d="m 196.40239,23.285532 c -0.54602,8.293741 -12.43549,6.934573 -14.77155,14.911232 -1.80051,6.147936 9.8144,9.871544 6.00441,15.021586 -4.94327,6.681938 -14.21051,-0.889398 -20.48824,4.558023 -4.8385,4.198549 2.91945,13.610539 -3.07004,15.883196 -7.77108,2.948667 -11.4738,-8.430992 -19.70006,-7.242327 -6.34031,0.916152 -4.90242,13.028284 -11.16979,11.702004 -8.13162,-1.720786 -5.09423,-13.295805 -12.65725,-16.74329 -5.82912,-2.657116 -11.1678,8.309642 -15.7232,3.80551 C 98.916245,59.337564 107.72938,51.24217 103.23082,44.253089 99.763598,38.86632 89.343337,45.205836 87.946205,38.953881 86.133492,30.842262 97.924274,28.796724 97.918427,20.48503 97.913921,14.078869 85.720439,13.77839 87.925159,7.7635646 90.785679,-0.04039043 101.81062,4.613372 106.29934,-2.3820311 c 3.45964,-5.3916419 -6.635717,-12.2367149 -1.52913,-16.1047469 6.62556,-5.01859 13.38432,4.856936 20.94247,1.398815 5.82538,-2.665315 1.03335,-13.881719 7.4205,-14.374885 8.28703,-0.639859 8.63374,11.322021 16.86167,12.499111 6.34159,0.907231 8.37433,-11.119376 14.01417,-8.081098 7.31742,3.942023 1.14202,14.192444 7.42741,19.6310273 4.8444,4.1917375 13.05652,-4.8267093 16.15844,0.7783797 4.02459,7.27234109 -6.71229,12.5568672 -4.365,20.530232 1.80914,6.145397 13.59336,2.998403 13.17252,9.390728 z"
|
||||
transform="matrix(7.5995429,0,0,7.5995429,-560.09045,326.96861)" />
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-weight:bold;font-size:527.974px;font-family:'Chalkboard SE';-inkscape-font-specification:'Chalkboard SE Bold';text-align:start;writing-mode:lr-tb;direction:ltr;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:#999999;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1;paint-order:markers fill stroke"
|
||||
x="306.01437"
|
||||
y="668.91577"
|
||||
id="text7-7-2-7-5-0-9-1"><tspan
|
||||
id="tspan7-5-2-2-5-2-7-0"
|
||||
style="fill:#ffffff;fill-opacity:1;stroke:#999999;stroke-width:0;stroke-opacity:1"
|
||||
x="306.01437"
|
||||
y="668.91577">#</tspan></text>
|
||||
</g>
|
||||
<path
|
||||
d="m 1382.5082,590.27527 h 36.5334 v 15.20002 q 5.3333,-8.00001 15.2,-13.06668 9.8667,-5.06668 22.9334,-5.06668 12,0 21.6,4.26668 9.6,4.26667 16.2667,12.00001 6.6667,7.46668 10.1333,18.13336 3.4667,10.66668 3.4667,23.73336 v 78.13343 h -36.5334 v -72.00009 q 0,-14.40002 -6.1333,-22.6667 -5.8667,-8.26667 -17.3334,-8.26667 -12.8,0 -21.3333,9.33334 -8.2667,9.33335 -8.2667,28.53337 v 65.06675 h -36.5334 z m 177.8672,-21.86669 q -4.8,0 -9.0667,-1.86667 -4,-1.86667 -7.2,-4.80001 -3.2,-3.2 -5.0667,-7.46667 -1.8667,-4.26668 -1.8667,-9.06668 0,-4.80001 1.8667,-9.06668 1.8667,-4.26667 5.0667,-7.20001 3.2,-3.2 7.2,-5.06667 4.2667,-1.86667 9.0667,-1.86667 9.8666,0 16.5333,6.93334 6.9334,6.66668 6.9334,16.26669 0,9.60001 -6.9334,16.53335 -6.6667,6.66668 -16.5333,6.66668 z m -18.1334,21.86669 h 36.5334 v 133.3335 h -36.5334 z m 239.7334,62.13341 q 0,-14.93335 -5.0667,-23.20003 -4.8,-8.53334 -15.7333,-8.53334 -11.7334,0 -18.9334,8.80001 -7.2,8.80001 -7.7333,27.20003 v 66.93342 h -36.5334 v -71.20009 q 0,-14.93335 -5.0667,-23.20003 -4.8,-8.53334 -15.7333,-8.53334 -12.0001,0 -19.4667,9.33334 -7.2,9.33335 -7.2,28.53337 v 65.06675 h -36.5334 v -133.3335 h 36.5334 v 15.20002 q 5.3333,-7.73334 14.1333,-12.80002 9.0667,-5.33334 21.3334,-5.33334 14.4,0 24.8,6.66668 10.4,6.40001 16.5333,17.86669 3.2,-6.13334 7.7334,-10.66668 4.8,-4.53334 10.4,-7.46668 5.6,-3.2 11.4667,-4.8 6.1333,-1.60001 11.7333,-1.60001 24.0001,0 36.8001,16.00002 13.0667,15.73336 13.0667,42.93339 v 77.33343 h -36.5334 z m 145.3334,74.13342 q -13.8667,0 -24,-5.6 -10.1334,-5.86668 -14.6667,-12.26668 v 14.93335 h -36.5334 V 523.60852 h 36.5334 v 81.6001 q 4.5333,-6.40001 14.6667,-12.00001 10.1333,-5.86668 24,-5.86668 13.3334,0 24.8,5.60001 11.4667,5.60001 19.7334,15.20002 8.5333,9.33334 13.3333,22.13336 4.8001,12.53335 4.8001,26.6667 0,14.13335 -4.8001,26.93336 -4.8,12.53335 -13.3333,22.13337 -8.2667,9.33334 -19.7334,14.93335 -11.4666,5.6 -24.8,5.6 z m -8,-33.33337 q 15.2,0 24.2667,-10.13335 9.3333,-10.40001 9.3333,-26.13336 0,-15.73335 -9.3333,-25.8667 -9.0667,-10.40001 -24.2667,-10.40001 -15.2,0 -24.5334,10.40001 -9.0666,10.13335 -9.0666,25.8667 0,15.73335 9.0666,26.13336 9.3334,10.13335 24.5334,10.13335 z m 151.467,33.33337 q -13.3334,0 -24.8001,-5.6 -11.4666,-5.60001 -20,-14.93335 -8.2667,-9.60002 -13.0667,-22.13337 -4.8,-12.80001 -4.8,-26.93336 0,-14.13335 4.8,-26.6667 4.8,-12.80002 13.0667,-22.13336 8.5334,-9.60001 20,-15.20002 11.4667,-5.60001 24.8001,-5.60001 13.8667,0 23.7333,5.86668 10.1334,5.6 14.6667,12.00001 v -14.93335 h 36.5334 v 133.3335 h -36.5334 v -14.93335 q -4.5333,6.4 -14.6667,12.26668 -9.8666,5.6 -23.7333,5.6 z m 7.7333,-33.33337 q 15.2,0 24.2667,-10.13335 9.3334,-10.40001 9.3334,-26.13336 0,-15.73335 -9.3334,-25.8667 -9.0667,-10.40001 -24.2667,-10.40001 -15.2,0 -24.5333,10.40001 -9.0667,10.13335 -9.0667,25.8667 0,15.73335 9.0667,26.13336 9.3333,10.13335 24.5333,10.13335 z m 102.667,-169.60021 h 36.5333 v 200.00025 h -36.5333 z m 82.6665,255.73365 28.0001,-63.20008 -56.0001,-125.86682 h 40 l 35.7334,86.40011 35.4667,-86.40011 h 40.2668 l -83.7335,189.0669 z m 190.1333,-52.80007 q -12.8,0 -23.7333,-3.46667 -10.9334,-3.46667 -18.9334,-9.33334 -7.7333,-6.13334 -12.5333,-14.40002 -4.5334,-8.26668 -5.0667,-18.13336 h 38.1334 q 1.0666,8.80002 7.7333,13.06669 6.6667,4.26667 15.4667,4.26667 8.5333,0 12.8,-2.93334 4.5334,-2.93333 4.5334,-7.73334 0,-5.33334 -4.0001,-8.26668 -4,-2.93333 -12.8,-5.06667 l -25.0667,-6.40001 q -17.6,-4.53334 -25.8667,-15.46668 -8,-11.20002 -8,-25.8667 0,-8.53335 3.7334,-15.73335 3.7333,-7.46668 10.6666,-12.53335 6.9334,-5.33334 16.8001,-8.26668 9.8666,-2.93334 22.4,-2.93334 10.9333,0 20.2667,2.93334 9.6,2.66667 16.8,8.26668 7.2,5.33334 11.4667,13.33335 4.5333,7.73334 5.3333,17.60002 h -36.8 q -1.3334,-7.73334 -6.4,-10.66668 -5.0667,-2.93334 -11.2,-2.93334 -6.9334,0 -11.4667,2.66667 -4.2667,2.66667 -4.2667,7.46668 0,5.6 4.5333,8.26667 4.5334,2.66667 10.6667,4.00001 l 23.4667,6.40001 q 19.7334,5.06667 28.2667,15.46668 8.8,10.13335 8.8,25.8667 0,9.33335 -4.2666,17.06669 -4,7.46667 -11.4667,12.80001 -7.4667,5.06668 -17.8667,7.73335 -10.1334,2.93333 -22.1334,2.93333 z m 143.4669,-1.33333 q -10.6667,0 -20.0001,-2.93334 -9.0666,-2.93334 -16,-8.80001 -6.9333,-6.13334 -10.9333,-15.20002 -4,-9.06668 -4,-21.33336 v -54.66673 h -26.9334 v -32.00004 h 26.9334 v -37.06671 h 36.5333 v 37.06671 h 37.6001 v 32.00004 h -37.6001 v 47.46672 q 0,12.26669 5.3334,17.60003 5.3333,5.06667 17.3333,5.06667 8.5334,0 14.9334,-2.4 v 32.2667 q -4.5334,1.33334 -10.1334,2.13334 -5.3333,0.8 -13.0666,0.8 z"
|
||||
id="text1"
|
||||
style="font-weight:600;font-size:266.667px;font-family:'Euclid Circular A';-inkscape-font-specification:'Euclid Circular A, Semi-Bold';white-space:pre;fill:#241d71;stroke-width:22.9493;stroke-linecap:round;stroke-linejoin:round;paint-order:fill markers stroke"
|
||||
transform="matrix(0.46320516,0,0,0.46320516,-237.3201,-85.864407)"
|
||||
aria-label="nimbalyst" />
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 7.9 KiB |
@ -7,6 +7,7 @@ import { SessionView } from './components/SessionView';
|
||||
import { PromptHistoryModal } from './components/PromptHistoryModal';
|
||||
import Help from './components/Help';
|
||||
import Welcome from './components/Welcome';
|
||||
import AnalyticsConsentDialog from './components/AnalyticsConsentDialog';
|
||||
import { AboutDialog } from './components/AboutDialog';
|
||||
import { UpdateDialog } from './components/UpdateDialog';
|
||||
import { MainProcessLogger } from './components/MainProcessLogger';
|
||||
@ -15,31 +16,46 @@ import { PermissionDialog } from './components/PermissionDialog';
|
||||
import { DiscordPopup } from './components/DiscordPopup';
|
||||
import { useErrorStore } from './stores/errorStore';
|
||||
import { useSessionStore } from './stores/sessionStore';
|
||||
import { useConfigStore } from './stores/configStore';
|
||||
import { API } from './utils/api';
|
||||
import { ContextMenuProvider } from './contexts/ContextMenuContext';
|
||||
import { TokenTest } from './components/TokenTest';
|
||||
import type { VersionUpdateInfo, PermissionInput } from './types/session';
|
||||
|
||||
// Type for IPC response
|
||||
interface IPCResponse<T = unknown> {
|
||||
success: boolean;
|
||||
data?: T;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface PermissionRequest {
|
||||
id: string;
|
||||
sessionId: string;
|
||||
toolName: string;
|
||||
input: any;
|
||||
input: PermissionInput;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [isHelpOpen, setIsHelpOpen] = useState(false);
|
||||
const [isWelcomeOpen, setIsWelcomeOpen] = useState(false);
|
||||
const [isAnalyticsConsentOpen, setIsAnalyticsConsentOpen] = useState(false);
|
||||
const [hasCheckedAnalyticsConsent, setHasCheckedAnalyticsConsent] = useState(false);
|
||||
const [isAboutOpen, setIsAboutOpen] = useState(false);
|
||||
const [isUpdateDialogOpen, setIsUpdateDialogOpen] = useState(false);
|
||||
const [updateVersionInfo, setUpdateVersionInfo] = useState<any>(null);
|
||||
const [updateVersionInfo, setUpdateVersionInfo] = useState<VersionUpdateInfo | null>(null);
|
||||
const [currentPermissionRequest, setCurrentPermissionRequest] = useState<PermissionRequest | null>(null);
|
||||
const [isDiscordOpen, setIsDiscordOpen] = useState(false);
|
||||
const [hasCheckedWelcome, setHasCheckedWelcome] = useState(false);
|
||||
const [isPromptHistoryOpen, setIsPromptHistoryOpen] = useState(false);
|
||||
const [isTokenTestOpen, setIsTokenTestOpen] = useState(false);
|
||||
const { currentError, clearError } = useErrorStore();
|
||||
const { sessions, isLoaded } = useSessionStore();
|
||||
const { fetchConfig } = useConfigStore();
|
||||
|
||||
const { width: sidebarWidth, startResize } = useResizable({
|
||||
defaultWidth: 320, // Increased from 256px (w-64)
|
||||
defaultWidth: 500, // Increased to show git status labels without truncation
|
||||
minWidth: 200,
|
||||
maxWidth: 600,
|
||||
storageKey: 'crystal-sidebar-width'
|
||||
@ -47,6 +63,81 @@ function App() {
|
||||
|
||||
useIPCEvents();
|
||||
const { showNotification } = useNotifications();
|
||||
|
||||
// Load config on app startup
|
||||
useEffect(() => {
|
||||
fetchConfig();
|
||||
}, [fetchConfig]);
|
||||
|
||||
// Check if analytics consent dialog should be shown (before other dialogs)
|
||||
useEffect(() => {
|
||||
if (hasCheckedAnalyticsConsent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkAnalyticsConsent = async () => {
|
||||
if (!window.electron?.invoke) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if consent has already been shown
|
||||
const consentResult = await window.electron.invoke('preferences:get', 'analytics_consent_shown') as IPCResponse<string>;
|
||||
const hasShownConsent = consentResult?.data === 'true';
|
||||
|
||||
if (!hasShownConsent) {
|
||||
// Show consent dialog
|
||||
setIsAnalyticsConsentOpen(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[App] Error checking analytics consent:', error);
|
||||
}
|
||||
};
|
||||
|
||||
setHasCheckedAnalyticsConsent(true);
|
||||
checkAnalyticsConsent();
|
||||
}, [hasCheckedAnalyticsConsent]);
|
||||
|
||||
// CRITICAL PERFORMANCE FIX: Very aggressive cleanup to prevent V8 array iteration issues
|
||||
useEffect(() => {
|
||||
// Run cleanup every 30 seconds to prevent array buildup that causes CPU spikes
|
||||
const cleanupInterval = setInterval(() => {
|
||||
const store = useSessionStore.getState();
|
||||
// Always cleanup when we have multiple sessions to prevent memory issues
|
||||
if (store.sessions.length > 0) {
|
||||
store.cleanupInactiveSessions();
|
||||
}
|
||||
}, 30 * 1000); // 30 seconds - much more frequent to prevent V8 optimization failures
|
||||
|
||||
// Immediate cleanup when switching sessions
|
||||
const handleSessionSwitch = () => {
|
||||
// Immediate cleanup to free memory right away
|
||||
const store = useSessionStore.getState();
|
||||
if (store.sessions.length > 0) {
|
||||
store.cleanupInactiveSessions();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('session-switched', handleSessionSwitch);
|
||||
|
||||
// Also cleanup on visibility change to free memory when app is in background
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.hidden) {
|
||||
const store = useSessionStore.getState();
|
||||
if (store.sessions.length > 0) {
|
||||
store.cleanupInactiveSessions();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
|
||||
return () => {
|
||||
clearInterval(cleanupInterval);
|
||||
window.removeEventListener('session-switched', handleSessionSwitch);
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Add keyboard shortcut for prompt history
|
||||
useEffect(() => {
|
||||
@ -65,37 +156,33 @@ function App() {
|
||||
useEffect(() => {
|
||||
// Show welcome screen and Discord popup intelligently based on user state
|
||||
// This should only run once when the app is loaded, not when sessions change
|
||||
// Don't show welcome while analytics consent dialog is open
|
||||
if (!isLoaded || hasCheckedWelcome || isAnalyticsConsentOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkInitialState = async () => {
|
||||
if (!window.electron?.invoke) {
|
||||
console.log('[Welcome Debug] Electron API not available');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Get preferences from database
|
||||
const hideWelcomeResult = await window.electron.invoke('preferences:get', 'hide_welcome');
|
||||
const welcomeShownResult = await window.electron.invoke('preferences:get', 'welcome_shown');
|
||||
const hideDiscordResult = await window.electron.invoke('preferences:get', 'hide_discord');
|
||||
const hideWelcomeResult = await window.electron.invoke('preferences:get', 'hide_welcome') as IPCResponse<string>;
|
||||
const welcomeShownResult = await window.electron.invoke('preferences:get', 'welcome_shown') as IPCResponse<string>;
|
||||
const hideDiscordResult = await window.electron.invoke('preferences:get', 'hide_discord') as IPCResponse<string>;
|
||||
|
||||
const hideWelcome = hideWelcomeResult?.data === 'true';
|
||||
const hasSeenWelcome = welcomeShownResult?.data === 'true';
|
||||
const hideDiscord = hideDiscordResult?.data === 'true';
|
||||
|
||||
console.log('[Welcome Debug] Checking welcome screen state:', {
|
||||
hideWelcomeRaw: hideWelcomeResult?.data,
|
||||
hideWelcome,
|
||||
hasSeenWelcome,
|
||||
hideDiscord,
|
||||
isLoaded
|
||||
});
|
||||
|
||||
// Track whether we're showing the welcome screen
|
||||
let welcomeScreenShown = false;
|
||||
|
||||
// If user explicitly said "don't show again", respect that preference
|
||||
if (hideWelcome) {
|
||||
console.log('[Welcome Debug] User has hidden welcome screen, not showing');
|
||||
welcomeScreenShown = false;
|
||||
} else if (isLoaded) {
|
||||
} else {
|
||||
try {
|
||||
const projectsResponse = await API.projects.getAll();
|
||||
const hasProjects = projectsResponse.success && projectsResponse.data && projectsResponse.data.length > 0;
|
||||
@ -109,21 +196,13 @@ function App() {
|
||||
const isFirstTimeUser = !hasProjects && !hasSeenWelcome;
|
||||
const isReturningUserWithNoData = !hasProjects && !hasSessions && hasSeenWelcome;
|
||||
|
||||
console.log('[Welcome Debug] Conditions:', {
|
||||
hasProjects,
|
||||
hasSessions,
|
||||
isFirstTimeUser,
|
||||
isReturningUserWithNoData
|
||||
});
|
||||
|
||||
if (isFirstTimeUser || isReturningUserWithNoData) {
|
||||
console.log('[Welcome Debug] Showing welcome screen');
|
||||
setIsWelcomeOpen(true);
|
||||
welcomeScreenShown = true;
|
||||
// Mark that welcome has been shown at least once
|
||||
await window.electron.invoke('preferences:set', 'welcome_shown', 'true');
|
||||
} else {
|
||||
console.log('[Welcome Debug] Not showing welcome screen');
|
||||
welcomeScreenShown = false;
|
||||
}
|
||||
} catch (error) {
|
||||
@ -133,46 +212,40 @@ function App() {
|
||||
}
|
||||
|
||||
// If welcome screen is not shown and Discord hasn't been hidden, check if we should show Discord popup
|
||||
if (!welcomeScreenShown && !hideDiscord && isLoaded) {
|
||||
console.log('[Discord Debug] Welcome screen not shown, checking Discord popup...');
|
||||
if (!welcomeScreenShown && !hideDiscord) {
|
||||
|
||||
try {
|
||||
// Get the last app open to see if Discord was already shown
|
||||
const result = await window.electron.invoke('app:get-last-open');
|
||||
console.log('[Discord Debug] Last app open result:', result);
|
||||
const result = await window.electron.invoke('app:get-last-open') as IPCResponse<{ discord_shown?: boolean }>;
|
||||
|
||||
if (result?.success && result.data) {
|
||||
const lastOpen = result.data;
|
||||
console.log('[Discord Debug] Last app open data:', lastOpen);
|
||||
|
||||
// Show Discord popup if it hasn't been shown yet
|
||||
if (!lastOpen.discord_shown) {
|
||||
console.log('[Discord Debug] Showing Discord popup!');
|
||||
setIsDiscordOpen(true);
|
||||
// Mark that we're showing the Discord popup
|
||||
if (window.electron?.invoke) {
|
||||
await window.electron.invoke('app:update-discord-shown');
|
||||
}
|
||||
} else {
|
||||
console.log('[Discord Debug] Not showing Discord popup because it was already shown');
|
||||
// Discord already shown
|
||||
}
|
||||
} else {
|
||||
// No previous app open - show Discord popup
|
||||
console.log('[Discord Debug] No previous app open found, showing Discord popup');
|
||||
setIsDiscordOpen(true);
|
||||
// Will update discord shown status after recording app open
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Discord Debug] Error checking Discord popup:', error);
|
||||
// Error checking Discord popup
|
||||
}
|
||||
|
||||
// Record this app open
|
||||
console.log('[Discord Debug] Recording current app open');
|
||||
if (window.electron?.invoke) {
|
||||
await window.electron.invoke('app:record-open', hideWelcome, false);
|
||||
|
||||
// If we showed Discord popup and there was no previous app open, update the status
|
||||
const result = await window.electron.invoke('app:get-last-open');
|
||||
const result = await window.electron.invoke('app:get-last-open') as IPCResponse<{ discord_shown?: boolean }>;
|
||||
if (!result?.data?.discord_shown && isDiscordOpen) {
|
||||
await window.electron.invoke('app:update-discord-shown');
|
||||
}
|
||||
@ -180,18 +253,17 @@ function App() {
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoaded && !hasCheckedWelcome) {
|
||||
checkInitialState();
|
||||
setHasCheckedWelcome(true);
|
||||
}
|
||||
}, [isLoaded, hasCheckedWelcome]); // Remove sessions.length from dependencies to prevent re-runs
|
||||
// Set the flag first to prevent re-runs
|
||||
setHasCheckedWelcome(true);
|
||||
checkInitialState();
|
||||
}, [isLoaded, isAnalyticsConsentOpen]); // Also wait for analytics consent dialog to close
|
||||
|
||||
// Discord popup logic is now combined with welcome screen logic above
|
||||
|
||||
useEffect(() => {
|
||||
// Set up permission request listener
|
||||
const handlePermissionRequest = (request: PermissionRequest) => {
|
||||
console.log('[App] Received permission request:', request);
|
||||
const handlePermissionRequest = (...args: unknown[]) => {
|
||||
const request = args[0] as PermissionRequest;
|
||||
setCurrentPermissionRequest(request);
|
||||
};
|
||||
|
||||
@ -206,14 +278,16 @@ function App() {
|
||||
// Set up version update listener
|
||||
if (!window.electronAPI?.events) return;
|
||||
|
||||
const handleVersionUpdate = (versionInfo: any) => {
|
||||
const handleVersionUpdate = (versionInfo: VersionUpdateInfo) => {
|
||||
console.log('[App] Version update available:', versionInfo);
|
||||
setUpdateVersionInfo(versionInfo);
|
||||
setIsUpdateDialogOpen(true);
|
||||
showNotification(
|
||||
`🚀 Update Available - Crystal v${versionInfo.latest}`,
|
||||
'A new version of Crystal is available!',
|
||||
'/favicon.ico'
|
||||
'/favicon.ico',
|
||||
'version_update',
|
||||
`update:${versionInfo.latest}` // Deduplicate by version - only track once per version
|
||||
);
|
||||
};
|
||||
|
||||
@ -226,13 +300,28 @@ function App() {
|
||||
}
|
||||
};
|
||||
}, [showNotification]);
|
||||
|
||||
// Add keyboard shortcut for token test page (Cmd/Ctrl + Shift + T) - Development only
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'T') {
|
||||
// Only allow in development mode
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
e.preventDefault();
|
||||
setIsTokenTestOpen(prev => !prev);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, []);
|
||||
|
||||
const handlePermissionResponse = async (requestId: string, behavior: 'allow' | 'deny', updatedInput?: any, message?: string) => {
|
||||
const handlePermissionResponse = async (requestId: string, behavior: 'allow' | 'deny', _updatedInput?: PermissionInput, message?: string) => {
|
||||
try {
|
||||
await API.permissions.respond(requestId, {
|
||||
behavior,
|
||||
updatedInput,
|
||||
message
|
||||
allow: behavior === 'allow',
|
||||
reason: message
|
||||
});
|
||||
setCurrentPermissionRequest(null);
|
||||
} catch (error) {
|
||||
@ -241,52 +330,79 @@ function App() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-screen flex overflow-hidden bg-gray-50 dark:bg-gray-900">
|
||||
<MainProcessLogger />
|
||||
{/* Draggable title bar area */}
|
||||
<div
|
||||
className="fixed top-0 left-0 right-0 h-8 z-50 flex items-center justify-end pr-4"
|
||||
style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
|
||||
>
|
||||
<ContextMenuProvider>
|
||||
<div className="h-screen flex overflow-hidden bg-bg-primary">
|
||||
<MainProcessLogger />
|
||||
{/* Draggable title bar area */}
|
||||
<div
|
||||
className="fixed top-0 left-0 right-0 h-8 z-50 flex items-center justify-end pr-4"
|
||||
style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
|
||||
>
|
||||
</div>
|
||||
<Sidebar
|
||||
onHelpClick={() => setIsHelpOpen(true)}
|
||||
onAboutClick={() => setIsAboutOpen(true)}
|
||||
onPromptHistoryClick={() => setIsPromptHistoryOpen(true)}
|
||||
width={sidebarWidth}
|
||||
onResize={startResize}
|
||||
/>
|
||||
<SessionView />
|
||||
<Help isOpen={isHelpOpen} onClose={() => setIsHelpOpen(false)} />
|
||||
<AnalyticsConsentDialog
|
||||
isOpen={isAnalyticsConsentOpen}
|
||||
onClose={() => setIsAnalyticsConsentOpen(false)}
|
||||
/>
|
||||
<Welcome isOpen={isWelcomeOpen} onClose={() => setIsWelcomeOpen(false)} />
|
||||
<AboutDialog isOpen={isAboutOpen} onClose={() => setIsAboutOpen(false)} />
|
||||
<UpdateDialog
|
||||
isOpen={isUpdateDialogOpen}
|
||||
onClose={() => setIsUpdateDialogOpen(false)}
|
||||
versionInfo={updateVersionInfo || undefined}
|
||||
/>
|
||||
<ErrorDialog
|
||||
isOpen={!!currentError}
|
||||
onClose={clearError}
|
||||
title={currentError?.title}
|
||||
error={currentError?.error || ''}
|
||||
details={currentError?.details}
|
||||
command={currentError?.command}
|
||||
/>
|
||||
<PermissionDialog
|
||||
request={currentPermissionRequest}
|
||||
onRespond={handlePermissionResponse}
|
||||
session={currentPermissionRequest ? sessions.find(s => s.id === currentPermissionRequest.sessionId) : undefined}
|
||||
/>
|
||||
<DiscordPopup
|
||||
isOpen={isDiscordOpen}
|
||||
onClose={() => setIsDiscordOpen(false)}
|
||||
/>
|
||||
<PromptHistoryModal
|
||||
isOpen={isPromptHistoryOpen}
|
||||
onClose={() => setIsPromptHistoryOpen(false)}
|
||||
/>
|
||||
|
||||
{/* Token Test Modal - Toggle with Cmd/Ctrl + Shift + T (Development Only) */}
|
||||
{isTokenTestOpen && process.env.NODE_ENV === 'development' && (
|
||||
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-50 p-4 overflow-y-auto">
|
||||
<div className="bg-bg-primary w-full max-w-6xl max-h-[90vh] overflow-y-auto rounded-lg relative border border-border-primary shadow-2xl">
|
||||
<button
|
||||
onClick={() => setIsTokenTestOpen(false)}
|
||||
className="absolute top-4 right-4 p-2 hover:bg-surface-hover rounded-lg transition-colors text-text-secondary hover:text-text-primary"
|
||||
title="Close Token Test (Cmd/Ctrl + Shift + T)"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<div className="absolute top-4 left-4 text-xs text-text-muted bg-surface-secondary px-2 py-1 rounded">
|
||||
DEV ONLY
|
||||
</div>
|
||||
<TokenTest />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Sidebar
|
||||
onHelpClick={() => setIsHelpOpen(true)}
|
||||
onAboutClick={() => setIsAboutOpen(true)}
|
||||
onPromptHistoryClick={() => setIsPromptHistoryOpen(true)}
|
||||
width={sidebarWidth}
|
||||
onResize={startResize}
|
||||
/>
|
||||
<SessionView />
|
||||
<Help isOpen={isHelpOpen} onClose={() => setIsHelpOpen(false)} />
|
||||
<Welcome isOpen={isWelcomeOpen} onClose={() => setIsWelcomeOpen(false)} />
|
||||
<AboutDialog isOpen={isAboutOpen} onClose={() => setIsAboutOpen(false)} />
|
||||
<UpdateDialog
|
||||
isOpen={isUpdateDialogOpen}
|
||||
onClose={() => setIsUpdateDialogOpen(false)}
|
||||
versionInfo={updateVersionInfo}
|
||||
/>
|
||||
<ErrorDialog
|
||||
isOpen={!!currentError}
|
||||
onClose={clearError}
|
||||
title={currentError?.title}
|
||||
error={currentError?.error || ''}
|
||||
details={currentError?.details}
|
||||
command={currentError?.command}
|
||||
/>
|
||||
<PermissionDialog
|
||||
request={currentPermissionRequest}
|
||||
onRespond={handlePermissionResponse}
|
||||
session={currentPermissionRequest ? sessions.find(s => s.id === currentPermissionRequest.sessionId) : undefined}
|
||||
/>
|
||||
<DiscordPopup
|
||||
isOpen={isDiscordOpen}
|
||||
onClose={() => setIsDiscordOpen(false)}
|
||||
/>
|
||||
<PromptHistoryModal
|
||||
isOpen={isPromptHistoryOpen}
|
||||
onClose={() => setIsPromptHistoryOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
</ContextMenuProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 1.9 MiB After Width: | Height: | Size: 2.6 KiB |
47
frontend/src/assets/nimbalyst-icon.svg
Normal file
@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="1024mm"
|
||||
height="1024mm"
|
||||
viewBox="0 0 1024 1024"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs1">
|
||||
<linearGradient
|
||||
id="swatch194">
|
||||
<stop
|
||||
style="stop-color:#4d4d4d;stop-opacity:1;"
|
||||
offset="0"
|
||||
id="stop194" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id="swatch39">
|
||||
<stop
|
||||
style="stop-color:#999999;stop-opacity:1;"
|
||||
offset="0"
|
||||
id="stop39" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<g
|
||||
id="layer1">
|
||||
<path
|
||||
style="fill:#6395ff;fill-opacity:1;stroke:none;stroke-width:6;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1;paint-order:fill markers stroke"
|
||||
id="path65-5-5-5-5-5-7-5"
|
||||
d="m 196.40239,23.285532 c -0.54602,8.293741 -12.43549,6.934573 -14.77155,14.911232 -1.80051,6.147936 9.8144,9.871544 6.00441,15.021586 -4.94327,6.681938 -14.21051,-0.889398 -20.48824,4.558023 -4.8385,4.198549 2.91945,13.610539 -3.07004,15.883196 -7.77108,2.948667 -11.4738,-8.430992 -19.70006,-7.242327 -6.34031,0.916152 -4.90242,13.028284 -11.16979,11.702004 -8.13162,-1.720786 -5.09423,-13.295805 -12.65725,-16.74329 -5.82912,-2.657116 -11.1678,8.309642 -15.7232,3.80551 C 98.916245,59.337564 107.72938,51.24217 103.23082,44.253089 99.763598,38.86632 89.343337,45.205836 87.946205,38.953881 86.133492,30.842262 97.924274,28.796724 97.918427,20.48503 97.913921,14.078869 85.720439,13.77839 87.925159,7.7635646 90.785679,-0.04039043 101.81062,4.613372 106.29934,-2.3820311 c 3.45964,-5.3916419 -6.635717,-12.2367149 -1.52913,-16.1047469 6.62556,-5.01859 13.38432,4.856936 20.94247,1.398815 5.82538,-2.665315 1.03335,-13.881719 7.4205,-14.374885 8.28703,-0.639859 8.63374,11.322021 16.86167,12.499111 6.34159,0.907231 8.37433,-11.119376 14.01417,-8.081098 7.31742,3.942023 1.14202,14.192444 7.42741,19.6310273 4.8444,4.1917375 13.05652,-4.8267093 16.15844,0.7783797 4.02459,7.27234109 -6.71229,12.5568672 -4.365,20.530232 1.80914,6.145397 13.59336,2.998403 13.17252,9.390728 z"
|
||||
transform="matrix(7.5995429,0,0,7.5995429,-560.09045,326.96861)" />
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-weight:bold;font-size:527.974px;font-family:'Chalkboard SE';-inkscape-font-specification:'Chalkboard SE Bold';text-align:start;writing-mode:lr-tb;direction:ltr;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:#999999;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1;paint-order:markers fill stroke"
|
||||
x="306.01437"
|
||||
y="668.91577"
|
||||
id="text7-7-2-7-5-0-9-1"><tspan
|
||||
id="tspan7-5-2-2-5-2-7-0"
|
||||
style="fill:#ffffff;fill-opacity:1;stroke:#999999;stroke-width:0;stroke-opacity:1"
|
||||
x="306.01437"
|
||||
y="668.91577">#</tspan></text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.9 KiB |
@ -10,9 +10,11 @@ interface VersionInfo {
|
||||
releaseNotes?: string;
|
||||
publishedAt?: string;
|
||||
workingDirectory?: string;
|
||||
crystalDirectory?: string;
|
||||
buildDate?: string;
|
||||
gitCommit?: string;
|
||||
buildTimestamp?: number;
|
||||
worktreeName?: string;
|
||||
}
|
||||
|
||||
interface AboutDialogProps {
|
||||
@ -42,9 +44,11 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
latest: result.data.current,
|
||||
hasUpdate: false,
|
||||
workingDirectory: result.data.workingDirectory,
|
||||
crystalDirectory: result.data.crystalDirectory,
|
||||
buildDate: result.data.buildDate,
|
||||
gitCommit: result.data.gitCommit,
|
||||
buildTimestamp: result.data.buildTimestamp
|
||||
buildTimestamp: result.data.buildTimestamp,
|
||||
worktreeName: result.data.worktreeName
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
@ -106,10 +110,10 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full mx-4 max-h-[80vh] overflow-hidden">
|
||||
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-50">
|
||||
<div className="bg-surface-primary rounded-lg shadow-xl max-w-md w-full mx-4 max-h-[80vh] overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center justify-between p-6 border-b border-border-primary">
|
||||
<div className="flex items-center space-x-3">
|
||||
<img
|
||||
src="/crystal-logo.svg"
|
||||
@ -120,13 +124,13 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
(e.target as HTMLImageElement).style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">
|
||||
<h2 className="text-xl font-semibold text-text-primary">
|
||||
About Crystal
|
||||
</h2>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
|
||||
className="text-text-tertiary hover:text-text-secondary transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
@ -136,19 +140,19 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
<div className="p-6 space-y-6">
|
||||
{/* App Info */}
|
||||
<div className="text-center space-y-2">
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-white">
|
||||
<h3 className="text-lg font-medium text-text-primary">
|
||||
Crystal
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
<p className="text-sm text-text-secondary">
|
||||
Multi-Session Claude Code Manager
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-500">
|
||||
<p className="text-xs text-text-tertiary">
|
||||
Created by{' '}
|
||||
<a
|
||||
href="https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 dark:text-blue-400 hover:underline"
|
||||
className="text-interactive hover:underline"
|
||||
>
|
||||
Stravu
|
||||
</a>
|
||||
@ -158,31 +162,53 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
{/* Version Info */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
<span className="text-sm font-medium text-text-secondary">
|
||||
Current Version
|
||||
</span>
|
||||
<span className="text-sm text-gray-900 dark:text-white font-mono">
|
||||
<span className="text-sm text-text-primary font-mono">
|
||||
{versionInfo?.current || 'Loading...'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{versionInfo?.crystalDirectory && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-text-secondary">
|
||||
Crystal Directory
|
||||
</span>
|
||||
<span className="text-sm text-text-primary font-mono truncate max-w-[200px]" title={versionInfo.crystalDirectory}>
|
||||
{versionInfo.crystalDirectory.replace(/^\/Users\/[^/]+/, '~')}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{versionInfo?.workingDirectory && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
<span className="text-sm font-medium text-text-secondary">
|
||||
Working Directory
|
||||
</span>
|
||||
<span className="text-sm text-gray-900 dark:text-white font-mono truncate max-w-[200px]" title={versionInfo.workingDirectory}>
|
||||
<span className="text-sm text-text-primary font-mono truncate max-w-[200px]" title={versionInfo.workingDirectory}>
|
||||
{versionInfo.workingDirectory.split('/').pop() || versionInfo.workingDirectory}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{versionInfo?.worktreeName && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Worktree
|
||||
</span>
|
||||
<span className="text-sm text-gray-900 dark:text-white font-mono">
|
||||
{versionInfo.worktreeName}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{versionInfo?.gitCommit && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
<span className="text-sm font-medium text-text-secondary">
|
||||
Git Commit
|
||||
</span>
|
||||
<span className="text-sm text-gray-900 dark:text-white font-mono">
|
||||
<span className="text-sm text-text-primary font-mono">
|
||||
{versionInfo.gitCommit}
|
||||
</span>
|
||||
</div>
|
||||
@ -190,26 +216,26 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
|
||||
{versionInfo?.buildDate && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
<span className="text-sm font-medium text-text-secondary">
|
||||
Build Date
|
||||
</span>
|
||||
<span className="text-sm text-gray-900 dark:text-white">
|
||||
<span className="text-sm text-text-primary">
|
||||
{formatDateTime(versionInfo.buildDate)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{versionInfo?.hasUpdate && (
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
|
||||
<div className="bg-interactive/10 border border-interactive/30 rounded-lg p-4">
|
||||
<div className="flex items-start space-x-3">
|
||||
<Download className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" />
|
||||
<Download className="w-5 h-5 text-interactive mt-0.5 flex-shrink-0" />
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-blue-900 dark:text-blue-100">
|
||||
<p className="text-sm font-medium text-interactive">
|
||||
Update Available: v{versionInfo.latest}
|
||||
</p>
|
||||
{versionInfo.publishedAt && (
|
||||
<p className="text-xs text-blue-700 dark:text-blue-300">
|
||||
<p className="text-xs text-interactive/80">
|
||||
Released {formatDate(versionInfo.publishedAt)}
|
||||
</p>
|
||||
)}
|
||||
@ -217,7 +243,7 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<button
|
||||
onClick={() => setShowUpdateDialog(true)}
|
||||
className="inline-flex items-center justify-center space-x-2 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-md transition-colors"
|
||||
className="inline-flex items-center justify-center space-x-2 px-3 py-1.5 bg-interactive hover:bg-interactive-hover text-on-interactive text-sm font-medium rounded-md transition-colors"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
<span>Download Update</span>
|
||||
@ -227,7 +253,7 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
href={versionInfo.releaseUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center justify-center space-x-1 px-3 py-1.5 text-sm text-blue-600 dark:text-blue-400 hover:underline"
|
||||
className="inline-flex items-center justify-center space-x-1 px-3 py-1.5 text-sm text-interactive hover:underline"
|
||||
>
|
||||
<span>View Release Notes</span>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
@ -240,14 +266,14 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
)}
|
||||
|
||||
{!versionInfo?.hasUpdate && versionInfo?.current && !isChecking && (
|
||||
<div className="flex items-center space-x-2 text-sm text-green-600 dark:text-green-400">
|
||||
<div className="flex items-center space-x-2 text-sm text-status-success">
|
||||
<Check className="w-4 h-4" />
|
||||
<span>You're running the latest version</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="flex items-center space-x-2 text-sm text-red-600 dark:text-red-400">
|
||||
<div className="flex items-center space-x-2 text-sm text-status-error">
|
||||
<AlertCircle className="w-4 h-4" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
@ -257,7 +283,7 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
<button
|
||||
onClick={checkForUpdates}
|
||||
disabled={isChecking}
|
||||
className="w-full flex items-center justify-center space-x-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white text-sm font-medium rounded-lg transition-colors"
|
||||
className="w-full flex items-center justify-center space-x-2 px-4 py-2 bg-interactive hover:bg-interactive-hover disabled:bg-interactive/50 text-on-interactive text-sm font-medium rounded-lg transition-colors"
|
||||
>
|
||||
{isChecking ? (
|
||||
<>
|
||||
@ -274,7 +300,7 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
</div>
|
||||
|
||||
{/* Discord Community Button */}
|
||||
<div className="pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<div className="pt-4 border-t border-border-primary">
|
||||
<a
|
||||
href="https://discord.gg/XrVa6q7DPY"
|
||||
target="_blank"
|
||||
@ -294,8 +320,7 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
href="https://github.com/stravu/crystal"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-between w-full text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
|
||||
>
|
||||
className="flex items-center justify-between w-full text-sm text-text-secondary hover:text-text-primary transition-colors">
|
||||
<span>View on GitHub</span>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</a>
|
||||
@ -303,16 +328,15 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
href="https://docs.anthropic.com/en/docs/claude-code"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-between w-full text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
|
||||
>
|
||||
className="flex items-center justify-between w-full text-sm text-text-secondary hover:text-text-primary transition-colors">
|
||||
<span>Claude Code Documentation</span>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Disclaimer */}
|
||||
<div className="pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<p className="text-xs text-gray-500 dark:text-gray-500 leading-relaxed">
|
||||
<div className="pt-4 border-t border-border-primary">
|
||||
<p className="text-xs text-text-tertiary leading-relaxed">
|
||||
Crystal is an independent project created by Stravu. Claude™ is a trademark of Anthropic, PBC.
|
||||
Crystal is not affiliated with, endorsed by, or sponsored by Anthropic.
|
||||
</p>
|
||||
|
||||
120
frontend/src/components/AnalyticsConsentDialog.tsx
Normal file
@ -0,0 +1,120 @@
|
||||
import React from 'react';
|
||||
import { BarChart3 } from 'lucide-react';
|
||||
import crystalLogo from '../assets/crystal-logo.svg';
|
||||
import { Modal, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { Button } from './ui/Button';
|
||||
import { useConfigStore } from '../stores/configStore';
|
||||
import { analyticsService } from '../services/analyticsService';
|
||||
|
||||
interface AnalyticsConsentDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: (accepted: boolean) => void;
|
||||
}
|
||||
|
||||
export default function AnalyticsConsentDialog({ isOpen, onClose }: AnalyticsConsentDialogProps) {
|
||||
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||
const { config, updateConfig } = useConfigStore();
|
||||
|
||||
const handleAccept = async () => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
// Enable analytics
|
||||
await updateConfig({
|
||||
analytics: {
|
||||
...config?.analytics,
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Track opt-in event
|
||||
await analyticsService.trackAnalyticsOptedIn();
|
||||
|
||||
// Mark consent as shown
|
||||
if (window.electron?.invoke) {
|
||||
await window.electron.invoke('preferences:set', 'analytics_consent_shown', 'true');
|
||||
}
|
||||
|
||||
onClose(true);
|
||||
} catch (error) {
|
||||
console.error('[AnalyticsConsent] Error accepting analytics:', error);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDecline = async () => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
// Track opt-out event FIRST (before disabling analytics)
|
||||
// This uses a special minimal tracking that works even when analytics is being disabled
|
||||
await analyticsService.trackAnalyticsOptedOut();
|
||||
|
||||
// Disable analytics (keep it disabled since it's opt-in)
|
||||
await updateConfig({
|
||||
analytics: {
|
||||
...config?.analytics,
|
||||
enabled: false,
|
||||
},
|
||||
});
|
||||
|
||||
// Mark consent as shown
|
||||
if (window.electron?.invoke) {
|
||||
await window.electron.invoke('preferences:set', 'analytics_consent_shown', 'true');
|
||||
}
|
||||
|
||||
onClose(false);
|
||||
} catch (error) {
|
||||
console.error('[AnalyticsConsent] Error declining analytics:', error);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={() => {}} size="md" closeOnOverlayClick={false} closeOnEscape={false} showCloseButton={false}>
|
||||
{/* Header with gradient */}
|
||||
<div className="bg-gradient-to-r from-interactive to-interactive-active p-6 text-on-interactive rounded-t-lg">
|
||||
<div className="flex items-center">
|
||||
<img src={crystalLogo} alt="Crystal" className="h-10 w-10 mr-3" />
|
||||
<h1 className="text-2xl font-bold">Help Improve Crystal</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ModalBody>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<BarChart3 className="h-6 w-6 text-interactive flex-shrink-0 mt-0.5" />
|
||||
<div className="space-y-3">
|
||||
<p className="text-text-primary">
|
||||
We do not collect any code, prompts, or identifying information.
|
||||
</p>
|
||||
<p className="text-text-secondary">
|
||||
Your data helps us make Crystal better. You can change this anytime in Settings.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
<ModalFooter className="flex justify-between items-center">
|
||||
<Button
|
||||
onClick={handleDecline}
|
||||
variant="ghost"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
No thanks
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAccept}
|
||||
variant="primary"
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
>
|
||||
Enable analytics
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
197
frontend/src/components/ArchiveProgress.tsx
Normal file
@ -0,0 +1,197 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import type { IpcRendererEvent } from 'electron';
|
||||
import { Loader2, Archive, CheckCircle, AlertCircle } from 'lucide-react';
|
||||
|
||||
interface ArchiveTask {
|
||||
sessionId: string;
|
||||
sessionName: string;
|
||||
worktreeName: string;
|
||||
projectName: string;
|
||||
status: 'pending' | 'queued' | 'removing-worktree' | 'cleaning-artifacts' | 'completed' | 'failed';
|
||||
startTime: string;
|
||||
endTime?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface ArchiveProgressData {
|
||||
tasks: ArchiveTask[];
|
||||
activeCount: number;
|
||||
totalCount: number;
|
||||
}
|
||||
|
||||
export function ArchiveProgress() {
|
||||
const [progress, setProgress] = useState<ArchiveProgressData | null>(null);
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Initial load
|
||||
loadProgress();
|
||||
|
||||
// Listen for progress updates
|
||||
const handleProgress = (_event: IpcRendererEvent, data: ArchiveProgressData) => {
|
||||
setProgress(data);
|
||||
// Auto-expand when there are active tasks
|
||||
if (data.activeCount > 0 && !isExpanded) {
|
||||
setIsExpanded(true);
|
||||
}
|
||||
};
|
||||
|
||||
window.electron?.on('archive:progress', handleProgress);
|
||||
|
||||
// Poll for initial state in case we missed events
|
||||
const interval = setInterval(loadProgress, 2000);
|
||||
|
||||
return () => {
|
||||
window.electron?.off('archive:progress', handleProgress);
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, [isExpanded]);
|
||||
|
||||
const loadProgress = async () => {
|
||||
if (!window.electron) return;
|
||||
try {
|
||||
const response = await window.electron.invoke('archive:get-progress');
|
||||
if (response.success) {
|
||||
setProgress(response.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load archive progress:', error);
|
||||
}
|
||||
};
|
||||
|
||||
if (!progress || progress.totalCount === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const getStatusIcon = (status: ArchiveTask['status']) => {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return <CheckCircle className="w-3 h-3 text-status-success" />;
|
||||
case 'failed':
|
||||
return <AlertCircle className="w-3 h-3 text-status-error" />;
|
||||
case 'queued':
|
||||
return <Archive className="w-3 h-3 text-status-waiting" />;
|
||||
default:
|
||||
return <Loader2 className="w-3 h-3 text-status-info animate-spin" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusText = (status: ArchiveTask['status']) => {
|
||||
switch (status) {
|
||||
case 'queued':
|
||||
return 'Queued (waiting for other archives to complete)...';
|
||||
case 'pending':
|
||||
return 'Preparing...';
|
||||
case 'removing-worktree':
|
||||
return 'Removing worktree (this may take a while)...';
|
||||
case 'cleaning-artifacts':
|
||||
return 'Cleaning artifacts...';
|
||||
case 'completed':
|
||||
return 'Completed';
|
||||
case 'failed':
|
||||
return 'Failed';
|
||||
default:
|
||||
return status;
|
||||
}
|
||||
};
|
||||
|
||||
const formatElapsedTime = (startTime: string, endTime?: string) => {
|
||||
const start = new Date(startTime).getTime();
|
||||
const end = endTime ? new Date(endTime).getTime() : Date.now();
|
||||
const elapsed = Math.floor((end - start) / 1000);
|
||||
|
||||
if (elapsed < 60) {
|
||||
return `${elapsed}s`;
|
||||
}
|
||||
const minutes = Math.floor(elapsed / 60);
|
||||
const seconds = elapsed % 60;
|
||||
return `${minutes}m ${seconds}s`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border-t border-border-primary flex-shrink-0">
|
||||
<button
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
className="w-full px-4 py-2 flex items-center justify-between hover:bg-surface-hover transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Archive className="w-3.5 h-3.5 text-text-tertiary" />
|
||||
<span className="text-xs text-text-tertiary">
|
||||
Archive Tasks
|
||||
</span>
|
||||
{progress.activeCount > 0 && (
|
||||
<span className="px-1.5 py-0.5 bg-status-info/20 text-status-info text-xs rounded-full animate-pulse">
|
||||
{progress.activeCount} active
|
||||
</span>
|
||||
)}
|
||||
{progress.tasks.filter(t => t.status === 'queued').length > 0 && (
|
||||
<span className="px-1.5 py-0.5 bg-status-waiting/20 text-status-waiting text-xs rounded-full">
|
||||
{progress.tasks.filter(t => t.status === 'queued').length} queued
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<svg
|
||||
className={`w-3.5 h-3.5 text-text-tertiary transition-transform ${
|
||||
isExpanded ? 'rotate-180' : ''
|
||||
}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="border-t border-border-primary max-h-48 overflow-y-auto bg-surface-secondary">
|
||||
{progress.tasks.length === 0 ? (
|
||||
<div className="px-4 py-2 text-xs text-text-tertiary">
|
||||
No archive tasks
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-border-primary">
|
||||
{progress.tasks.map((task) => (
|
||||
<div key={task.sessionId} className="px-4 py-2 space-y-1">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-start gap-2 flex-1 min-w-0">
|
||||
{getStatusIcon(task.status)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-xs text-text-secondary truncate" title={task.sessionName}>
|
||||
{task.sessionName}
|
||||
</div>
|
||||
<div className="text-xs text-text-tertiary truncate">
|
||||
{task.projectName} / {task.worktreeName}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-xs text-text-tertiary whitespace-nowrap">
|
||||
{formatElapsedTime(task.startTime, task.endTime)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-text-tertiary pl-5">
|
||||
{getStatusText(task.status)}
|
||||
</div>
|
||||
{task.error && (
|
||||
<div className="text-xs text-status-error pl-5 mt-1">
|
||||
{task.error}
|
||||
</div>
|
||||
)}
|
||||
{task.status === 'removing-worktree' && (
|
||||
<div className="text-xs text-status-warning/80 pl-5 mt-1 italic">
|
||||
⚠️ Worktree removal can take several minutes for large repositories
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,5 +1,8 @@
|
||||
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { GitCommit, X } from 'lucide-react';
|
||||
import { GitCommit } from 'lucide-react';
|
||||
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { Button } from './ui/Button';
|
||||
import { Textarea } from './ui/Textarea';
|
||||
|
||||
interface CommitDialogProps {
|
||||
isOpen: boolean;
|
||||
@ -63,89 +66,53 @@ export const CommitDialog: React.FC<CommitDialogProps> = ({
|
||||
}
|
||||
}, [handleCommit, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className="absolute inset-0 bg-black bg-opacity-50"
|
||||
onClick={onClose}
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="md">
|
||||
<ModalHeader
|
||||
icon={<GitCommit className="w-5 h-5" />}
|
||||
title="Commit Changes"
|
||||
onClose={onClose}
|
||||
/>
|
||||
|
||||
{/* Dialog */}
|
||||
<div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md mx-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitCommit className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
Commit Changes
|
||||
</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<ModalBody>
|
||||
<p className="text-sm text-text-secondary mb-4">
|
||||
Committing {fileCount} file{fileCount > 1 ? 's' : ''} with changes
|
||||
</p>
|
||||
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={commitMessage}
|
||||
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setCommitMessage(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Enter commit message..."
|
||||
rows={4}
|
||||
error={error}
|
||||
/>
|
||||
|
||||
<p className="mt-2 text-xs text-text-tertiary">
|
||||
Press Ctrl+Enter (Cmd+Enter on Mac) to commit
|
||||
</p>
|
||||
</ModalBody>
|
||||
|
||||
{/* Body */}
|
||||
<div className="px-6 py-4">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
|
||||
Committing {fileCount} file{fileCount > 1 ? 's' : ''} with changes
|
||||
</p>
|
||||
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={commitMessage}
|
||||
onChange={(e) => setCommitMessage(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Enter commit message..."
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"
|
||||
rows={4}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<p className="mt-2 text-sm text-red-600 dark:text-red-400">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
|
||||
Press Ctrl+Enter (Cmd+Enter on Mac) to commit
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
onClick={onClose}
|
||||
disabled={isCommitting}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCommit}
|
||||
disabled={isCommitting || !commitMessage.trim()}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
|
||||
>
|
||||
{isCommitting ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
Committing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitCommit className="w-4 h-4" />
|
||||
Commit
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ModalFooter>
|
||||
<Button
|
||||
onClick={onClose}
|
||||
disabled={isCommitting}
|
||||
variant="secondary"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleCommit}
|
||||
disabled={isCommitting || !commitMessage.trim()}
|
||||
variant="primary"
|
||||
loading={isCommitting}
|
||||
loadingText="Committing..."
|
||||
>
|
||||
<GitCommit className="w-4 h-4" />
|
||||
Commit
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
@ -2,6 +2,12 @@ import { useState, useEffect } from 'react';
|
||||
import { GitCommit, Shield, Zap, AlertTriangle, Info } from 'lucide-react';
|
||||
import type { CommitMode, CommitModeSettings, ProjectCharacteristics } from '../../../shared/types';
|
||||
import { DEFAULT_STRUCTURED_PROMPT_TEMPLATE, DEFAULT_COMMIT_MODE_SETTINGS } from '../../../shared/types';
|
||||
import { Card } from './ui/Card';
|
||||
import { Badge } from './ui/Badge';
|
||||
import { Input } from './ui/Input';
|
||||
import { Textarea } from './ui/Textarea';
|
||||
import { Checkbox } from './ui/Input';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
interface CommitModeSettingsProps {
|
||||
projectId?: number;
|
||||
@ -41,7 +47,7 @@ export function CommitModeSettings({
|
||||
onChange(chars.suggestedMode, newSettings);
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
.catch((error: unknown) => {
|
||||
console.error('Failed to detect project characteristics:', error);
|
||||
})
|
||||
.finally(() => {
|
||||
@ -57,7 +63,7 @@ export function CommitModeSettings({
|
||||
.then((result: { shouldWarn: boolean; reason?: string }) => {
|
||||
setShowWarning(result.shouldWarn);
|
||||
})
|
||||
.catch((error: any) => {
|
||||
.catch((error: unknown) => {
|
||||
console.error('Failed to check checkpoint warning:', error);
|
||||
});
|
||||
} else {
|
||||
@ -84,16 +90,16 @@ export function CommitModeSettings({
|
||||
<div className={`space-y-4 ${className}`}>
|
||||
{/* Mode Selection */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
<label className="block text-sm font-medium text-text-primary mb-2">
|
||||
Commit Mode
|
||||
</label>
|
||||
|
||||
{/* Recommendation Banner */}
|
||||
{characteristics && !loadingCharacteristics && (
|
||||
<div className="mb-3 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
|
||||
<Card variant="bordered" className="mb-3 bg-interactive/10 border-interactive/30" padding="sm">
|
||||
<div className="flex items-start gap-2">
|
||||
<Info className="w-4 h-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" />
|
||||
<div className="text-sm text-blue-700 dark:text-blue-300">
|
||||
<Info className="w-4 h-4 text-interactive mt-0.5 flex-shrink-0" />
|
||||
<div className="text-sm text-interactive">
|
||||
<p className="font-medium">Recommended: {characteristics.suggestedMode} mode</p>
|
||||
<p className="text-xs mt-1 opacity-90">
|
||||
{characteristics.hasHusky && 'Pre-commit hooks detected (.husky). '}
|
||||
@ -104,151 +110,169 @@ export function CommitModeSettings({
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
{/* Structured Mode */}
|
||||
<label className="relative flex items-start p-3 border rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
|
||||
<input
|
||||
type="radio"
|
||||
name="commitMode"
|
||||
value="structured"
|
||||
checked={localSettings.mode === 'structured'}
|
||||
onChange={() => handleModeChange('structured')}
|
||||
className="mt-1 mr-3"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4 text-blue-600 dark:text-blue-400" />
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">Structured Mode</span>
|
||||
{characteristics?.suggestedMode === 'structured' && (
|
||||
<span className="text-xs bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 px-2 py-0.5 rounded">
|
||||
Recommended
|
||||
</span>
|
||||
)}
|
||||
<Card
|
||||
variant="interactive"
|
||||
className={cn(
|
||||
"cursor-pointer transition-all",
|
||||
localSettings.mode === 'structured'
|
||||
? "bg-interactive/10 border-interactive"
|
||||
: "hover:border-interactive/30"
|
||||
)}
|
||||
onClick={() => handleModeChange('structured')}
|
||||
padding="md"
|
||||
>
|
||||
<label className="relative flex items-start cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="commitMode"
|
||||
value="structured"
|
||||
checked={localSettings.mode === 'structured'}
|
||||
onChange={() => handleModeChange('structured')}
|
||||
className="mt-1 mr-3 text-interactive focus:ring-interactive"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4 text-interactive" />
|
||||
<span className="font-medium text-text-primary">Structured Mode</span>
|
||||
{characteristics?.suggestedMode === 'structured' && (
|
||||
<Badge variant="primary" size="sm">
|
||||
Recommended
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-text-secondary mt-1">
|
||||
Claude creates commits with proper messages. Respects pre-commit hooks and project conventions.
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
Claude creates commits with proper messages. Respects pre-commit hooks and project conventions.
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
</label>
|
||||
</Card>
|
||||
|
||||
{/* Checkpoint Mode */}
|
||||
<label className="relative flex items-start p-3 border rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
|
||||
<input
|
||||
type="radio"
|
||||
name="commitMode"
|
||||
value="checkpoint"
|
||||
checked={localSettings.mode === 'checkpoint'}
|
||||
onChange={() => handleModeChange('checkpoint')}
|
||||
className="mt-1 mr-3"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="w-4 h-4 text-green-600 dark:text-green-400" />
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">Checkpoint Mode</span>
|
||||
{characteristics?.suggestedMode === 'checkpoint' && (
|
||||
<span className="text-xs bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 px-2 py-0.5 rounded">
|
||||
Recommended
|
||||
</span>
|
||||
)}
|
||||
<Card
|
||||
variant="interactive"
|
||||
className={cn(
|
||||
"cursor-pointer transition-all",
|
||||
localSettings.mode === 'checkpoint'
|
||||
? "bg-status-success/10 border-status-success"
|
||||
: "hover:border-status-success/30"
|
||||
)}
|
||||
onClick={() => handleModeChange('checkpoint')}
|
||||
padding="md"
|
||||
>
|
||||
<label className="relative flex items-start cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="commitMode"
|
||||
value="checkpoint"
|
||||
checked={localSettings.mode === 'checkpoint'}
|
||||
onChange={() => handleModeChange('checkpoint')}
|
||||
className="mt-1 mr-3 text-status-success focus:ring-status-success"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="w-4 h-4 text-status-success" />
|
||||
<span className="font-medium text-text-primary">Checkpoint Mode</span>
|
||||
{characteristics?.suggestedMode === 'checkpoint' && (
|
||||
<Badge variant="success" size="sm">
|
||||
Recommended
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-text-secondary mt-1">
|
||||
Auto-commit after each prompt. Fast and simple, bypasses hooks with --no-verify.
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
Auto-commit after each prompt. Fast and simple, bypasses hooks with --no-verify.
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
</label>
|
||||
</Card>
|
||||
|
||||
{/* Disabled Mode */}
|
||||
<label className="relative flex items-start p-3 border rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
|
||||
<input
|
||||
type="radio"
|
||||
name="commitMode"
|
||||
value="disabled"
|
||||
checked={localSettings.mode === 'disabled'}
|
||||
onChange={() => handleModeChange('disabled')}
|
||||
className="mt-1 mr-3"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitCommit className="w-4 h-4 text-gray-600 dark:text-gray-400" />
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">Disabled Mode</span>
|
||||
<Card
|
||||
variant="interactive"
|
||||
className={cn(
|
||||
"cursor-pointer transition-all",
|
||||
localSettings.mode === 'disabled'
|
||||
? "bg-surface-tertiary border-border-secondary"
|
||||
: "hover:border-border-primary"
|
||||
)}
|
||||
onClick={() => handleModeChange('disabled')}
|
||||
padding="md"
|
||||
>
|
||||
<label className="relative flex items-start cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="commitMode"
|
||||
value="disabled"
|
||||
checked={localSettings.mode === 'disabled'}
|
||||
onChange={() => handleModeChange('disabled')}
|
||||
className="mt-1 mr-3 text-text-tertiary focus:ring-text-tertiary"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitCommit className="w-4 h-4 text-text-muted" />
|
||||
<span className="font-medium text-text-primary">Disabled Mode</span>
|
||||
</div>
|
||||
<p className="text-sm text-text-secondary mt-1">
|
||||
No auto-commits. You handle all commits manually.
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
No auto-commits. You handle all commits manually.
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
</label>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Warning for checkpoint mode */}
|
||||
{showWarning && localSettings.mode === 'checkpoint' && (
|
||||
<div className="p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
|
||||
<Card variant="bordered" className="bg-status-warning/10 border-status-warning/30" padding="sm">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertTriangle className="w-4 h-4 text-amber-600 dark:text-amber-400 mt-0.5 flex-shrink-0" />
|
||||
<div className="text-sm text-amber-700 dark:text-amber-300">
|
||||
<AlertTriangle className="w-4 h-4 text-status-warning mt-0.5 flex-shrink-0" />
|
||||
<div className="text-sm text-status-warning">
|
||||
<p className="font-medium">Warning: Pre-commit hooks detected</p>
|
||||
<p className="text-xs mt-1">
|
||||
<p className="text-xs mt-1 opacity-90">
|
||||
Checkpoint commits will bypass pre-commit hooks. This may cause CI failures.
|
||||
Consider using Structured mode for this project.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Mode-specific settings */}
|
||||
{localSettings.mode === 'structured' && (
|
||||
<div className="space-y-3 pt-2">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Commit Prompt Template
|
||||
</label>
|
||||
<textarea
|
||||
value={localSettings.structuredPromptTemplate || DEFAULT_STRUCTURED_PROMPT_TEMPLATE}
|
||||
onChange={(e) => handleSettingChange('structuredPromptTemplate', e.target.value)}
|
||||
rows={4}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-700 text-sm"
|
||||
placeholder="Instructions for Claude on how to commit..."
|
||||
/>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
This will be appended to Claude's prompts to guide commit behavior.
|
||||
</p>
|
||||
</div>
|
||||
<Textarea
|
||||
label="Commit Prompt Template"
|
||||
value={localSettings.structuredPromptTemplate || DEFAULT_STRUCTURED_PROMPT_TEMPLATE}
|
||||
onChange={(e) => handleSettingChange('structuredPromptTemplate', e.target.value)}
|
||||
rows={4}
|
||||
placeholder="Instructions for Claude on how to commit..."
|
||||
helperText="This will be appended to Claude's prompts to guide commit behavior."
|
||||
fullWidth
|
||||
/>
|
||||
|
||||
<div>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={localSettings.allowClaudeTools || false}
|
||||
onChange={(e) => handleSettingChange('allowClaudeTools', e.target.checked)}
|
||||
className="h-4 w-4 text-blue-600 rounded border-gray-300 dark:border-gray-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">
|
||||
Allow Claude to run tools (e.g., pnpm changeset)
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<Checkbox
|
||||
id="allowClaudeTools"
|
||||
label="Allow Claude to run tools (e.g., pnpm changeset)"
|
||||
checked={localSettings.allowClaudeTools || false}
|
||||
onChange={(e) => handleSettingChange('allowClaudeTools', e.target.checked)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{localSettings.mode === 'checkpoint' && (
|
||||
<div className="pt-2">
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Commit Prefix
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
<Input
|
||||
label="Commit Prefix"
|
||||
value={localSettings.checkpointPrefix || DEFAULT_COMMIT_MODE_SETTINGS.checkpointPrefix}
|
||||
onChange={(e) => handleSettingChange('checkpointPrefix', e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-700"
|
||||
placeholder="checkpoint: "
|
||||
helperText="Prefix for automatic checkpoint commits."
|
||||
fullWidth
|
||||
/>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Prefix for automatic checkpoint commits.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -1,7 +1,12 @@
|
||||
import React, { useState } from 'react';
|
||||
import { GitCommit, Shield, Zap, ChevronDown, Settings } from 'lucide-react';
|
||||
import { FileText, RotateCcw, ChevronDown, Settings, GitCommit } from 'lucide-react';
|
||||
import type { CommitMode, CommitModeSettings } from '../../../shared/types';
|
||||
import { CommitModeSettings as CommitModeSettingsComponent } from './CommitModeSettings';
|
||||
import { Dropdown, DropdownMenuItem, type DropdownItem } from './ui/Dropdown';
|
||||
import { Button } from './ui/Button';
|
||||
import { Pill } from './ui/Pill';
|
||||
import { SwitchSimple as Switch } from './ui/SwitchSimple';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
interface CommitModeToggleProps {
|
||||
sessionId: string;
|
||||
@ -12,7 +17,26 @@ interface CommitModeToggleProps {
|
||||
onModeChange?: (mode: CommitMode, settings: CommitModeSettings) => void;
|
||||
}
|
||||
|
||||
export const CommitModeToggle: React.FC<CommitModeToggleProps> = ({
|
||||
interface CommitModePillProps {
|
||||
sessionId: string;
|
||||
currentMode?: CommitMode;
|
||||
currentSettings?: string;
|
||||
autoCommit?: boolean;
|
||||
projectId?: number;
|
||||
onModeChange?: (mode: CommitMode, settings: CommitModeSettings) => void;
|
||||
isAutoCommitEnabled?: boolean; // Made optional since it's no longer used
|
||||
}
|
||||
|
||||
interface AutoCommitSwitchProps {
|
||||
sessionId: string;
|
||||
currentMode?: CommitMode;
|
||||
currentSettings?: string;
|
||||
autoCommit?: boolean;
|
||||
onModeChange?: (mode: CommitMode, settings: CommitModeSettings) => void;
|
||||
}
|
||||
|
||||
// Auto-Commit Mode Pill Component
|
||||
export const CommitModePill: React.FC<CommitModePillProps> = ({
|
||||
sessionId,
|
||||
currentMode,
|
||||
currentSettings,
|
||||
@ -33,37 +57,31 @@ export const CommitModeToggle: React.FC<CommitModeToggleProps> = ({
|
||||
|
||||
// Determine effective mode (backwards compatibility)
|
||||
const effectiveMode = currentMode || (autoCommit === false ? 'disabled' : 'checkpoint');
|
||||
|
||||
// Get the active commit mode
|
||||
const activeCommitMode: CommitMode = effectiveMode;
|
||||
|
||||
const getModeConfig = () => {
|
||||
switch (effectiveMode) {
|
||||
const getModeConfig = (mode: CommitMode) => {
|
||||
switch (mode) {
|
||||
case 'structured':
|
||||
return {
|
||||
icon: Shield,
|
||||
icon: FileText,
|
||||
label: 'Structured',
|
||||
color: 'bg-blue-50 dark:bg-blue-950/20 text-blue-700 dark:text-blue-300 hover:bg-blue-100 dark:hover:bg-blue-950/30 border-blue-200 dark:border-blue-800',
|
||||
iconColor: 'text-blue-600 dark:text-blue-400',
|
||||
};
|
||||
case 'checkpoint':
|
||||
return {
|
||||
icon: Zap,
|
||||
icon: RotateCcw,
|
||||
label: 'Checkpoint',
|
||||
color: 'bg-green-50 dark:bg-green-950/20 text-green-700 dark:text-green-300 hover:bg-green-100 dark:hover:bg-green-950/30 border-green-200 dark:border-green-800',
|
||||
iconColor: 'text-green-600 dark:text-green-400',
|
||||
};
|
||||
case 'disabled':
|
||||
return {
|
||||
icon: GitCommit,
|
||||
label: 'Disabled',
|
||||
color: 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600 border-gray-300 dark:border-gray-600',
|
||||
iconColor: 'text-gray-600 dark:text-gray-400',
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const config = getModeConfig();
|
||||
const Icon = config.icon;
|
||||
|
||||
const handleQuickModeChange = async (newMode: CommitMode) => {
|
||||
const handleCommitModeChange = async (newMode: CommitMode) => {
|
||||
const newSettings: CommitModeSettings = {
|
||||
...parsedSettings,
|
||||
mode: newMode,
|
||||
@ -96,107 +114,88 @@ export const CommitModeToggle: React.FC<CommitModeToggleProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
// Create dropdown items for commit modes
|
||||
const dropdownItems: DropdownItem[] = [
|
||||
{
|
||||
id: 'structured',
|
||||
label: 'Structured',
|
||||
description: 'Claude creates commits',
|
||||
icon: FileText,
|
||||
iconColor: 'text-text-secondary',
|
||||
onClick: () => handleCommitModeChange('structured'),
|
||||
variant: 'default',
|
||||
},
|
||||
{
|
||||
id: 'checkpoint',
|
||||
label: 'Checkpoint',
|
||||
description: 'Auto-commit after each prompt',
|
||||
icon: RotateCcw,
|
||||
iconColor: 'text-text-secondary',
|
||||
onClick: () => handleCommitModeChange('checkpoint'),
|
||||
variant: 'success',
|
||||
},
|
||||
{
|
||||
id: 'disabled',
|
||||
label: 'Disabled',
|
||||
description: 'No automatic commits',
|
||||
icon: GitCommit,
|
||||
iconColor: 'text-text-secondary',
|
||||
onClick: () => handleCommitModeChange('disabled'),
|
||||
variant: 'default',
|
||||
},
|
||||
];
|
||||
|
||||
const config = getModeConfig(activeCommitMode);
|
||||
const Icon = config.icon;
|
||||
|
||||
const modeSelectorPill = (
|
||||
<Pill
|
||||
variant="default"
|
||||
isActive={activeCommitMode !== 'disabled'} // Show active styling when commits are enabled
|
||||
icon={<Icon className={cn(
|
||||
'w-3.5 h-3.5',
|
||||
activeCommitMode !== 'disabled' ? 'text-text-on-interactive' : 'text-text-secondary'
|
||||
)} />}
|
||||
className="transition-all duration-200 shadow-sm"
|
||||
>
|
||||
{config.label}
|
||||
<ChevronDown className={cn(
|
||||
'w-3 h-3 transition-transform',
|
||||
showDropdown ? 'rotate-180' : '',
|
||||
activeCommitMode !== 'disabled' ? 'text-text-on-interactive' : 'text-text-secondary'
|
||||
)} />
|
||||
</Pill>
|
||||
);
|
||||
|
||||
// Create the footer with settings button
|
||||
const dropdownFooter = (
|
||||
<DropdownMenuItem
|
||||
icon={Settings}
|
||||
label="Commit Mode Settings..."
|
||||
onClick={() => {
|
||||
setShowDropdown(false);
|
||||
setShowSettings(true);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative" style={{ overflow: 'visible' }}>
|
||||
<button
|
||||
onClick={() => setShowDropdown(!showDropdown)}
|
||||
className={`
|
||||
px-3.5 py-1.5 rounded-full text-xs font-medium
|
||||
transition-all duration-200 flex items-center gap-1.5
|
||||
hover:scale-105 active:scale-95
|
||||
focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-50 dark:focus:ring-offset-gray-950
|
||||
border ${config.color}
|
||||
`}
|
||||
>
|
||||
<Icon className={`w-3.5 h-3.5 ${config.iconColor}`} />
|
||||
<span className="leading-none">{config.label}</span>
|
||||
<ChevronDown className={`w-3 h-3 ${showDropdown ? 'rotate-180' : ''} transition-transform`} />
|
||||
</button>
|
||||
|
||||
{/* Dropdown Menu */}
|
||||
{showDropdown && (
|
||||
<>
|
||||
<div
|
||||
className="fixed inset-0 z-[9998]"
|
||||
onClick={() => setShowDropdown(false)}
|
||||
/>
|
||||
<div className="absolute right-0 bottom-full mb-2 w-56 bg-white dark:bg-gray-800 rounded-lg shadow-2xl border border-gray-200 dark:border-gray-600 z-[9999]">
|
||||
<div className="p-1.5">
|
||||
{/* Quick Mode Selection */}
|
||||
<button
|
||||
onClick={() => handleQuickModeChange('structured')}
|
||||
className={`w-full text-left px-3 py-2.5 rounded-md transition-colors flex items-center gap-2 ${
|
||||
effectiveMode === 'structured' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300' : 'text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<Shield className="w-4 h-4 text-blue-600 dark:text-blue-400" />
|
||||
<div className="flex-1">
|
||||
<div className="text-sm font-semibold">Structured</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-300">Claude creates commits</div>
|
||||
</div>
|
||||
{effectiveMode === 'structured' && (
|
||||
<div className="w-2 h-2 bg-blue-500 rounded-full" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleQuickModeChange('checkpoint')}
|
||||
className={`w-full text-left px-3 py-2.5 rounded-md transition-colors flex items-center gap-2 ${
|
||||
effectiveMode === 'checkpoint' ? 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300' : 'text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<Zap className="w-4 h-4 text-green-600 dark:text-green-400" />
|
||||
<div className="flex-1">
|
||||
<div className="text-sm font-semibold">Checkpoint</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-300">Auto-commit after each prompt</div>
|
||||
</div>
|
||||
{effectiveMode === 'checkpoint' && (
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleQuickModeChange('disabled')}
|
||||
className={`w-full text-left px-3 py-2.5 rounded-md transition-colors flex items-center gap-2 ${
|
||||
effectiveMode === 'disabled' ? 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300' : 'text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<GitCommit className="w-4 h-4 text-gray-600 dark:text-gray-400" />
|
||||
<div className="flex-1">
|
||||
<div className="text-sm font-semibold">Disabled</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-300">Manual commits only</div>
|
||||
</div>
|
||||
{effectiveMode === 'disabled' && (
|
||||
<div className="w-2 h-2 bg-gray-500 rounded-full" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="border-t border-gray-200 dark:border-gray-600 my-1.5" />
|
||||
|
||||
{/* Settings Button */}
|
||||
<button
|
||||
onClick={() => {
|
||||
setShowDropdown(false);
|
||||
setShowSettings(true);
|
||||
}}
|
||||
className="w-full text-left px-3 py-2.5 rounded-md text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex items-center gap-2"
|
||||
>
|
||||
<Settings className="w-4 h-4 text-gray-600 dark:text-gray-400" />
|
||||
<span className="text-sm font-medium">Commit Mode Settings...</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<Dropdown
|
||||
trigger={modeSelectorPill}
|
||||
items={dropdownItems}
|
||||
selectedId={activeCommitMode}
|
||||
footer={dropdownFooter}
|
||||
position="auto"
|
||||
onOpenChange={setShowDropdown}
|
||||
/>
|
||||
|
||||
{/* Settings Dialog */}
|
||||
{showSettings && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[10000]">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
|
||||
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-modal-backdrop">
|
||||
<div className="bg-surface-primary rounded-lg shadow-modal max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto z-modal">
|
||||
<div className="p-6">
|
||||
<h2 className="text-xl font-bold mb-4">Commit Mode Settings</h2>
|
||||
<h2 className="text-xl font-bold mb-4 text-text-primary">Commit Mode Settings</h2>
|
||||
|
||||
<CommitModeSettingsComponent
|
||||
projectId={projectId}
|
||||
@ -206,12 +205,12 @@ export const CommitModeToggle: React.FC<CommitModeToggleProps> = ({
|
||||
/>
|
||||
|
||||
<div className="flex justify-end gap-3 mt-6">
|
||||
<button
|
||||
<Button
|
||||
onClick={() => setShowSettings(false)}
|
||||
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-300 dark:hover:bg-gray-600"
|
||||
variant="secondary"
|
||||
>
|
||||
Done
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -219,4 +218,97 @@ export const CommitModeToggle: React.FC<CommitModeToggleProps> = ({
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Auto-Commit Switch Component
|
||||
//
|
||||
// NOTE: This component is currently HIDDEN from the UI (commented out in input panels).
|
||||
//
|
||||
// REASON: The autoCommit boolean field is a legacy system that has been superseded
|
||||
// by the more sophisticated CommitMode system (structured/checkpoint/disabled).
|
||||
//
|
||||
// BACKWARDS COMPATIBILITY: The legacy autoCommit field still works through the
|
||||
// executionTracker.ts conversion logic, but this UI component actually calls the
|
||||
// modern commit-mode system rather than updating the legacy autoCommit field.
|
||||
//
|
||||
// CURRENT STATE:
|
||||
// - UI shows AutoCommitSwitch (when enabled) -> calls commit-mode:update-session-settings
|
||||
// - Legacy autoCommit field may become stale
|
||||
// - executionTracker.ts converts legacy autoCommit to commitMode for backwards compatibility
|
||||
//
|
||||
// DECISION: Hide the toggle to avoid confusion. Users should use the CommitModePill
|
||||
// to select between structured/checkpoint/disabled modes instead of a simple on/off toggle.
|
||||
//
|
||||
// FUTURE: The autoCommit database column will be dropped as part of the database cleanup.
|
||||
export const AutoCommitSwitch: React.FC<AutoCommitSwitchProps> = ({
|
||||
sessionId,
|
||||
currentMode,
|
||||
currentSettings,
|
||||
autoCommit,
|
||||
onModeChange,
|
||||
}) => {
|
||||
// Parse current settings or use defaults
|
||||
let parsedSettings: CommitModeSettings;
|
||||
try {
|
||||
parsedSettings = currentSettings ? JSON.parse(currentSettings) : { mode: 'checkpoint' };
|
||||
} catch {
|
||||
parsedSettings = { mode: 'checkpoint' };
|
||||
}
|
||||
|
||||
// Determine effective mode (backwards compatibility)
|
||||
const effectiveMode = currentMode || (autoCommit === false ? 'disabled' : 'checkpoint');
|
||||
|
||||
// Auto-Commit is enabled when mode is not 'disabled'
|
||||
const isAutoCommitEnabled = effectiveMode !== 'disabled';
|
||||
|
||||
// Get the active commit mode (defaults to checkpoint if enabled)
|
||||
const activeCommitMode: 'structured' | 'checkpoint' = isAutoCommitEnabled
|
||||
? (effectiveMode === 'structured' ? 'structured' : 'checkpoint')
|
||||
: 'checkpoint'; // Default for when auto-commit gets enabled
|
||||
|
||||
const handleAutoCommitToggle = async (enabled: boolean) => {
|
||||
const newMode: CommitMode = enabled ? activeCommitMode : 'disabled';
|
||||
const newSettings: CommitModeSettings = {
|
||||
...parsedSettings,
|
||||
mode: newMode,
|
||||
};
|
||||
|
||||
// Update via IPC
|
||||
try {
|
||||
await window.electronAPI.invoke('commit-mode:update-session-settings', sessionId, newSettings);
|
||||
|
||||
// Notify parent component
|
||||
if (onModeChange) {
|
||||
onModeChange(newMode, newSettings);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to update commit mode:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Switch
|
||||
checked={isAutoCommitEnabled}
|
||||
onCheckedChange={handleAutoCommitToggle}
|
||||
label="Auto-Commit"
|
||||
icon={<GitCommit />}
|
||||
size="sm"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
// Legacy wrapper component for backwards compatibility
|
||||
export const CommitModeToggle: React.FC<CommitModeToggleProps> = (props) => {
|
||||
// Determine effective mode for isAutoCommitEnabled calculation
|
||||
const effectiveMode = props.currentMode || (props.autoCommit === false ? 'disabled' : 'checkpoint');
|
||||
const isAutoCommitEnabled = effectiveMode !== 'disabled';
|
||||
|
||||
return (
|
||||
<div className="inline-flex flex-col items-start gap-0.5">
|
||||
<AutoCommitSwitch {...props} />
|
||||
<div className="ml-5 mt-0">
|
||||
<CommitModePill {...props} isAutoCommitEnabled={isAutoCommitEnabled} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
99
frontend/src/components/ConfirmDialog.tsx
Normal file
@ -0,0 +1,99 @@
|
||||
import { useEffect } from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
interface ConfirmDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onConfirm: () => void;
|
||||
title: string;
|
||||
message: string;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
confirmButtonClass?: string;
|
||||
icon?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function ConfirmDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onConfirm,
|
||||
title,
|
||||
message,
|
||||
confirmText = 'Confirm',
|
||||
cancelText = 'Cancel',
|
||||
confirmButtonClass = 'bg-red-600 hover:bg-red-700 text-white',
|
||||
icon
|
||||
}: ConfirmDialogProps) {
|
||||
// Handle keyboard events
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
onConfirm();
|
||||
onClose();
|
||||
} else if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}
|
||||
}, [isOpen, onConfirm, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleConfirm = () => {
|
||||
onConfirm();
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full mx-4 p-6">
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
{icon && (
|
||||
<div className="flex-shrink-0">
|
||||
{icon}
|
||||
</div>
|
||||
)}
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-white">
|
||||
{title}
|
||||
</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mb-6">
|
||||
<p className="text-gray-700 dark:text-gray-300 whitespace-pre-line leading-relaxed">
|
||||
{message}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors"
|
||||
>
|
||||
{cancelText}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleConfirm}
|
||||
className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${confirmButtonClass}`}
|
||||
autoFocus
|
||||
>
|
||||
{confirmText}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,9 +1,13 @@
|
||||
import { useState } from 'react';
|
||||
import { CreateSessionDialog } from './CreateSessionDialog';
|
||||
import { API } from '../utils/api';
|
||||
import { Button } from './ui/Button';
|
||||
import { Plus, Zap } from 'lucide-react';
|
||||
import { getCodexModelConfig } from '../../../shared/types/models';
|
||||
|
||||
export function CreateSessionButton() {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isCreatingQuick, setIsCreatingQuick] = useState(false);
|
||||
|
||||
const handleClick = async () => {
|
||||
try {
|
||||
@ -23,18 +27,77 @@ export function CreateSessionButton() {
|
||||
alert('Error checking project status. Please try again.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleQuickAdd = async () => {
|
||||
try {
|
||||
setIsCreatingQuick(true);
|
||||
|
||||
// Check if there's an active project
|
||||
const projectResponse = await API.projects.getActive();
|
||||
|
||||
if (!projectResponse.success || !projectResponse.data) {
|
||||
alert('Please select or create a project first before creating a session.');
|
||||
return;
|
||||
}
|
||||
|
||||
const activeProject = projectResponse.data;
|
||||
|
||||
// Create a session with minimal configuration
|
||||
// The backend will handle making "untitled" unique (untitled-1, untitled-2, etc.)
|
||||
const lastModel = activeProject.lastUsedModel || 'auto';
|
||||
const toolType = getCodexModelConfig(lastModel) ? 'codex' : 'claude';
|
||||
|
||||
const response = await API.sessions.create({
|
||||
prompt: '', // No initial prompt
|
||||
worktreeTemplate: 'untitled', // Simple name - backend will make it unique
|
||||
count: 1,
|
||||
permissionMode: 'ignore', // Use default permission mode
|
||||
toolType,
|
||||
projectId: activeProject.id,
|
||||
autoCommit: true,
|
||||
commitMode: 'checkpoint',
|
||||
commitModeSettings: JSON.stringify({
|
||||
mode: 'checkpoint',
|
||||
checkpointPrefix: 'checkpoint: '
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
console.error('Failed to create quick session:', response.error);
|
||||
alert('Failed to create session. Please try again.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creating quick session:', error);
|
||||
alert('Error creating session. Please try again.');
|
||||
} finally {
|
||||
setIsCreatingQuick(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
onClick={handleClick}
|
||||
data-testid="create-session-button"
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
|
||||
>
|
||||
New Session
|
||||
</button>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
data-testid="create-session-button"
|
||||
variant="primary"
|
||||
fullWidth
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
New Session
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleQuickAdd}
|
||||
data-testid="quick-add-session-button"
|
||||
variant="secondary"
|
||||
disabled={isCreatingQuick}
|
||||
title="Quick add new session"
|
||||
>
|
||||
<Zap className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<CreateSessionDialog isOpen={isOpen} onClose={() => setIsOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,12 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
import { Modal, ModalBody } from './ui/Modal';
|
||||
|
||||
// Type for preferences IPC response
|
||||
interface IPCResponse<T = unknown> {
|
||||
success: boolean;
|
||||
data?: T;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface DiscordPopupProps {
|
||||
isOpen: boolean;
|
||||
@ -15,7 +22,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
|
||||
if (window.electron?.invoke) {
|
||||
try {
|
||||
console.log('[Discord] Loading hide_discord preference...');
|
||||
const result = await window.electron.invoke('preferences:get', 'hide_discord');
|
||||
const result = await window.electron.invoke('preferences:get', 'hide_discord') as IPCResponse<string>;
|
||||
console.log('[Discord] Preference result:', result);
|
||||
|
||||
if (result?.success) {
|
||||
@ -39,7 +46,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
|
||||
const handleClose = async () => {
|
||||
if (window.electron?.invoke) {
|
||||
try {
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_discord', dontShowAgain ? 'true' : 'false');
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_discord', dontShowAgain ? 'true' : 'false') as IPCResponse;
|
||||
if (!result?.success) {
|
||||
console.error('[Discord] Failed to set preference on close:', result?.error);
|
||||
}
|
||||
@ -54,7 +61,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
|
||||
// Just close without setting the hide flag
|
||||
if (window.electron?.invoke) {
|
||||
try {
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_discord', 'false');
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_discord', 'false') as IPCResponse;
|
||||
if (!result?.success) {
|
||||
console.error('[Discord] Failed to set preference on remind later:', result?.error);
|
||||
}
|
||||
@ -75,7 +82,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
|
||||
}
|
||||
if (dontShowAgain && window.electron?.invoke) {
|
||||
try {
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_discord', 'true');
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_discord', 'true') as IPCResponse;
|
||||
if (!result?.success) {
|
||||
console.error('[Discord] Failed to set preference on join discord:', result?.error);
|
||||
}
|
||||
@ -86,45 +93,34 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-[#1e1e1e] rounded-xl border border-gray-700 max-w-md w-full shadow-2xl transform transition-all">
|
||||
{/* Header */}
|
||||
<div className="relative overflow-hidden rounded-t-xl">
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-[#5865F2] to-[#7289DA] opacity-90" />
|
||||
<div className="relative px-6 py-8 text-center">
|
||||
<div className="flex items-center justify-center mb-4">
|
||||
<svg className="w-12 h-12 text-white" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold text-white mb-2">Join the Crystal Community!</h2>
|
||||
<p className="text-white/90">Connect with other Crystal users, get help, and stay updated</p>
|
||||
<Modal isOpen={isOpen} onClose={handleClose} size="md">
|
||||
<div className="relative overflow-hidden -m-6 mb-0">
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-[#5865F2] to-[#7289DA] opacity-90" />
|
||||
<div className="relative px-6 py-8 text-center">
|
||||
<div className="flex items-center justify-center mb-4">
|
||||
<svg className="w-12 h-12 text-white" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleClose}
|
||||
className="absolute top-4 right-4 text-white/80 hover:text-white transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
<h2 className="text-2xl font-bold text-white mb-2">Join the Crystal Community!</h2>
|
||||
<p className="text-white/90">Connect with other Crystal users, get help, and stay updated</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="px-6 py-6">
|
||||
<ModalBody>
|
||||
<div className="space-y-4 mb-6">
|
||||
<div className="flex items-start space-x-3">
|
||||
<div className="w-2 h-2 rounded-full bg-[#5865F2] mt-2 flex-shrink-0" />
|
||||
<p className="text-gray-300">Get help with Crystal and Claude Code</p>
|
||||
<p className="text-text-secondary">Get help with Crystal and Claude Code</p>
|
||||
</div>
|
||||
<div className="flex items-start space-x-3">
|
||||
<div className="w-2 h-2 rounded-full bg-[#5865F2] mt-2 flex-shrink-0" />
|
||||
<p className="text-gray-300">Share your workflows and learn from others</p>
|
||||
<p className="text-text-secondary">Share your workflows and learn from others</p>
|
||||
</div>
|
||||
<div className="flex items-start space-x-3">
|
||||
<div className="w-2 h-2 rounded-full bg-[#5865F2] mt-2 flex-shrink-0" />
|
||||
<p className="text-gray-300">Be the first to know about updates and features</p>
|
||||
<p className="text-text-secondary">Be the first to know about updates and features</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -142,7 +138,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
|
||||
|
||||
<button
|
||||
onClick={handleRemindLater}
|
||||
className="w-full px-4 py-3 bg-gray-700 hover:bg-gray-600 text-gray-300 font-medium rounded-lg transition-colors"
|
||||
className="w-full px-4 py-3 bg-surface-tertiary hover:bg-surface-hover text-text-secondary font-medium rounded-lg transition-colors"
|
||||
>
|
||||
Remind Me Later
|
||||
</button>
|
||||
@ -156,7 +152,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
|
||||
setDontShowAgain(newValue);
|
||||
if (window.electron?.invoke) {
|
||||
try {
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_discord', newValue ? 'true' : 'false');
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_discord', newValue ? 'true' : 'false') as IPCResponse;
|
||||
if (result?.success) {
|
||||
console.log('[Discord] Successfully set hide_discord preference to', newValue);
|
||||
} else {
|
||||
@ -173,15 +169,14 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
|
||||
}}
|
||||
className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
|
||||
dontShowAgain
|
||||
? 'bg-gray-700 text-gray-100 hover:bg-gray-600'
|
||||
: 'bg-gray-800 text-gray-400 hover:bg-gray-700 hover:text-gray-300'
|
||||
? 'bg-surface-tertiary text-text-primary hover:bg-surface-hover'
|
||||
: 'bg-surface-primary text-text-tertiary hover:bg-surface-secondary hover:text-text-secondary'
|
||||
}`}
|
||||
>
|
||||
{dontShowAgain ? "Will hide permanently" : "Don't show this again"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalBody>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
@ -1,4 +1,6 @@
|
||||
import { LucideIcon } from 'lucide-react';
|
||||
import { Button } from './ui/Button';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
interface EmptyStateProps {
|
||||
icon: LucideIcon;
|
||||
@ -11,21 +13,18 @@ interface EmptyStateProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function EmptyState({ icon: Icon, title, description, action, className = '' }: EmptyStateProps) {
|
||||
export function EmptyState({ icon: Icon, title, description, action, className }: EmptyStateProps) {
|
||||
return (
|
||||
<div className={`flex flex-col items-center justify-center p-12 text-center ${className}`}>
|
||||
<div className="w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mb-4">
|
||||
<Icon className="w-8 h-8 text-gray-600 dark:text-gray-400" />
|
||||
<div className={cn('flex flex-col items-center justify-center p-12 text-center', className)}>
|
||||
<div className="w-16 h-16 bg-surface-secondary rounded-full flex items-center justify-center mb-4">
|
||||
<Icon className="w-8 h-8 text-text-tertiary" />
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">{title}</h3>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 max-w-sm mb-6">{description}</p>
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-2">{title}</h3>
|
||||
<p className="text-sm text-text-secondary max-w-sm mb-6">{description}</p>
|
||||
{action && (
|
||||
<button
|
||||
onClick={action.onClick}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
|
||||
>
|
||||
<Button onClick={action.onClick} variant="primary">
|
||||
{action.label}
|
||||
</button>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import React, { Component, ReactNode } from 'react';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
import { Button } from './ui/Button';
|
||||
|
||||
interface ErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
@ -24,7 +25,17 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
|
||||
|
||||
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
|
||||
console.error('Error caught by boundary:', error, errorInfo);
|
||||
console.error('Component stack:', errorInfo.componentStack);
|
||||
this.setState({ errorInfo });
|
||||
|
||||
// Log to file in development mode for debugging
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.log('[ErrorBoundary] Full error details:', {
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
componentStack: errorInfo.componentStack
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
@ -36,21 +47,56 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
|
||||
|
||||
// Default error UI
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full p-8">
|
||||
<div className="text-center">
|
||||
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
|
||||
<div className="flex items-center justify-center h-screen p-8 bg-bg-primary">
|
||||
<div className="text-center max-w-2xl">
|
||||
<AlertCircle className="w-16 h-16 text-status-error mx-auto mb-6" />
|
||||
<h2 className="text-2xl font-semibold text-text-primary mb-3">
|
||||
Something went wrong
|
||||
</h2>
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-4">
|
||||
The editor encountered an error. Please try refreshing the page.
|
||||
<p className="text-text-secondary mb-6">
|
||||
Crystal encountered an unexpected error and needs to reload.
|
||||
</p>
|
||||
|
||||
{/* Error details */}
|
||||
{this.state.error && (
|
||||
<div className="bg-surface-secondary border border-border-primary rounded-lg p-4 mb-6 text-left">
|
||||
<p className="font-mono text-sm text-status-error mb-2">
|
||||
{this.state.error.message}
|
||||
</p>
|
||||
{process.env.NODE_ENV === 'development' && this.state.error.stack && (
|
||||
<details className="text-xs text-text-muted mt-2">
|
||||
<summary className="cursor-pointer hover:text-text-secondary">
|
||||
Stack trace (dev only)
|
||||
</summary>
|
||||
<pre className="mt-2 overflow-x-auto whitespace-pre-wrap">
|
||||
{this.state.error.stack}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3 justify-center">
|
||||
<Button
|
||||
onClick={() => window.location.reload()}
|
||||
variant="primary"
|
||||
>
|
||||
Reload Application
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
// Try to reset state and recover
|
||||
this.setState({ hasError: false, error: null, errorInfo: null });
|
||||
}}
|
||||
variant="secondary"
|
||||
>
|
||||
Try to Continue
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-text-muted mt-6">
|
||||
If this keeps happening, please report it on GitHub
|
||||
</p>
|
||||
<button
|
||||
onClick={() => window.location.reload()}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
|
||||
>
|
||||
Refresh Page
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -1,5 +1,8 @@
|
||||
import { useState } from 'react';
|
||||
import { AlertCircle, X, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { AlertCircle, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { Button } from './ui/Button';
|
||||
import { Card } from './ui/Card';
|
||||
|
||||
interface ErrorDialogProps {
|
||||
isOpen: boolean;
|
||||
@ -20,8 +23,6 @@ export function ErrorDialog({
|
||||
}: ErrorDialogProps) {
|
||||
const [isDetailsExpanded, setIsDetailsExpanded] = useState(false);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
// Check if details are long enough to warrant collapsing
|
||||
const shouldCollapse = details && details.length > 500;
|
||||
const displayDetails = shouldCollapse && !isDetailsExpanded
|
||||
@ -29,74 +30,71 @@ export function ErrorDialog({
|
||||
: details;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-2xl w-full mx-4 max-h-[80vh] flex flex-col border border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
<AlertCircle className="w-6 h-6 text-red-500 flex-shrink-0" />
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-200">{title}</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="xl">
|
||||
<ModalHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<AlertCircle className="w-6 h-6 text-status-error flex-shrink-0" />
|
||||
<span>{title}</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 overflow-y-auto">
|
||||
</ModalHeader>
|
||||
|
||||
<ModalBody>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<p className="text-gray-700 dark:text-gray-300">{error}</p>
|
||||
<p className="text-text-secondary">{error}</p>
|
||||
</div>
|
||||
|
||||
{command && (
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-1">Command:</h4>
|
||||
<pre className="bg-gray-100 dark:bg-gray-900 p-3 rounded text-sm text-gray-800 dark:text-gray-300 font-mono overflow-x-auto border border-gray-200 dark:border-gray-700">
|
||||
{command}
|
||||
</pre>
|
||||
<h4 className="text-sm font-medium text-text-tertiary mb-1">Command:</h4>
|
||||
<Card variant="bordered" padding="sm" className="bg-surface-secondary">
|
||||
<pre className="text-sm text-text-primary font-mono overflow-x-auto">
|
||||
{command}
|
||||
</pre>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{details && (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<h4 className="text-sm font-medium text-gray-600 dark:text-gray-400">Error Details:</h4>
|
||||
<h4 className="text-sm font-medium text-text-tertiary">Error Details:</h4>
|
||||
{shouldCollapse && (
|
||||
<button
|
||||
<Button
|
||||
onClick={() => setIsDetailsExpanded(!isDetailsExpanded)}
|
||||
className="text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 flex items-center space-x-1"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-xs"
|
||||
>
|
||||
{isDetailsExpanded ? (
|
||||
<>
|
||||
<span>Show less</span>
|
||||
<ChevronUp className="w-3 h-3" />
|
||||
<ChevronUp className="w-3 h-3 ml-1" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>Show more</span>
|
||||
<ChevronDown className="w-3 h-3" />
|
||||
<ChevronDown className="w-3 h-3 ml-1" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<pre className="bg-red-50 dark:bg-gray-900 p-3 rounded text-sm text-red-700 dark:text-red-400 font-mono overflow-x-auto whitespace-pre-wrap border border-red-200 dark:border-gray-700">
|
||||
{displayDetails}
|
||||
</pre>
|
||||
<Card variant="bordered" padding="sm" className="bg-status-error/10 border-status-error/30">
|
||||
<pre className="text-sm text-status-error font-mono overflow-x-auto whitespace-pre-wrap">
|
||||
{displayDetails}
|
||||
</pre>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex justify-end">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-800 dark:text-white rounded-md transition-colors"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
<ModalFooter>
|
||||
<Button onClick={onClose} variant="secondary">
|
||||
Close
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -1,6 +1,8 @@
|
||||
import React, { useState, memo } from 'react';
|
||||
import { GitCommit, RotateCcw, RefreshCw } from 'lucide-react';
|
||||
import type { ExecutionListProps } from '../types/diff';
|
||||
import { Button } from './ui/Button';
|
||||
import { Card } from './ui/Card';
|
||||
|
||||
const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
executions,
|
||||
@ -8,9 +10,12 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
onSelectionChange,
|
||||
onCommit,
|
||||
onRevert,
|
||||
onRestore
|
||||
onRestore,
|
||||
historyLimitReached = false,
|
||||
historyLimit
|
||||
}) => {
|
||||
const [rangeStart, setRangeStart] = useState<number | null>(null);
|
||||
const limitDisplay = historyLimit ?? 50;
|
||||
|
||||
const handleCommitClick = (executionId: number, event: React.MouseEvent) => {
|
||||
if (event.shiftKey && rangeStart !== null) {
|
||||
@ -46,14 +51,14 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
const getStatsDisplay = (exec: { stats_additions: number; stats_deletions: number; stats_files_changed: number }) => {
|
||||
const { stats_additions, stats_deletions, stats_files_changed } = exec;
|
||||
if (stats_files_changed === 0) {
|
||||
return <span className="text-gray-500 dark:text-gray-400 text-sm">No changes</span>;
|
||||
return <span className="text-text-tertiary text-sm">No changes</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-sm space-x-3">
|
||||
<span className="text-green-600 dark:text-green-400">+{stats_additions}</span>
|
||||
<span className="text-red-600 dark:text-red-400">-{stats_deletions}</span>
|
||||
<span className="text-gray-600 dark:text-gray-400">{stats_files_changed} {stats_files_changed === 1 ? 'file' : 'files'}</span>
|
||||
<span className="text-status-success">+{stats_additions}</span>
|
||||
<span className="text-status-error">-{stats_deletions}</span>
|
||||
<span className="text-text-tertiary">{stats_files_changed} {stats_files_changed === 1 ? 'file' : 'files'}</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -70,7 +75,7 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
|
||||
if (executions.length === 0) {
|
||||
return (
|
||||
<div className="p-4 text-gray-500 dark:text-gray-400 text-center">
|
||||
<div className="p-4 text-text-tertiary text-center">
|
||||
No commits found for this session
|
||||
</div>
|
||||
);
|
||||
@ -79,20 +84,23 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
return (
|
||||
<div className="execution-list h-full flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">
|
||||
Commits ({executions.filter(e => e.id !== 0).length})
|
||||
</h3>
|
||||
<button
|
||||
onClick={handleSelectAll}
|
||||
className="text-sm px-3 py-1 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
Select All Commits
|
||||
</button>
|
||||
</div>
|
||||
<Card variant="bordered" className="rounded-b-none border-b-0">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-medium text-text-primary">
|
||||
Commits ({executions.filter(e => e.id !== 0).length})
|
||||
</h3>
|
||||
<Button
|
||||
onClick={handleSelectAll}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
>
|
||||
Select All Commits
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Instructions */}
|
||||
<div className="px-4 py-2 bg-gray-100 dark:bg-gray-700 text-xs text-gray-600 dark:text-gray-400 border-b border-gray-300 dark:border-gray-600">
|
||||
<div className="px-4 py-2 bg-bg-secondary text-xs text-text-tertiary border-b border-border-secondary">
|
||||
Click to select a single commit, Shift+Click to select a range
|
||||
</div>
|
||||
|
||||
@ -106,59 +114,63 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
<div
|
||||
key={execution.id}
|
||||
className={`
|
||||
flex items-center p-4 border-b border-gray-200 dark:border-gray-700 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors
|
||||
${isSelected ? 'bg-blue-100 dark:bg-blue-900/20 border-l-4 border-l-blue-500' : ''}
|
||||
${isUncommitted ? 'bg-yellow-100 dark:bg-yellow-900/20' : ''}
|
||||
flex items-center p-4 border-b border-border-secondary cursor-pointer hover:bg-bg-hover transition-colors
|
||||
${isSelected ? 'bg-bg-accent border-l-4 border-l-interactive' : ''}
|
||||
${isUncommitted ? 'bg-status-warning/20' : ''}
|
||||
`}
|
||||
onClick={(e) => handleCommitClick(execution.id, e)}
|
||||
>
|
||||
<div className="mr-3 w-4 h-4 flex items-center justify-center">
|
||||
{isSelected && (
|
||||
<div className="w-3 h-3 bg-blue-600 rounded-full" />
|
||||
<div className="w-3 h-3 bg-interactive rounded-full" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<div className="text-sm font-medium text-text-primary">
|
||||
{isUncommitted ? (
|
||||
<span className="text-yellow-700 dark:text-yellow-300">Uncommitted changes</span>
|
||||
<span className="text-status-warning">Uncommitted changes</span>
|
||||
) : (
|
||||
<span>{truncateMessage(execution.prompt_text || `Commit ${execution.execution_sequence}`)}</span>
|
||||
<span>{truncateMessage(execution.commit_message || execution.prompt_text || `Commit ${execution.execution_sequence}`)}</span>
|
||||
)}
|
||||
</div>
|
||||
{isUncommitted && (
|
||||
<div className="flex items-center gap-2">
|
||||
{onCommit && execution.stats_files_changed > 0 && (
|
||||
<button
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onCommit();
|
||||
}}
|
||||
className="text-xs bg-green-600 hover:bg-green-700 text-white px-2 py-1 rounded flex items-center gap-1 transition-colors"
|
||||
size="sm"
|
||||
variant="primary"
|
||||
className="!bg-status-success hover:!bg-status-success-hover !text-white text-xs"
|
||||
>
|
||||
<GitCommit className="w-3 h-3" />
|
||||
Commit
|
||||
</button>
|
||||
</Button>
|
||||
)}
|
||||
{onRestore && execution.stats_files_changed > 0 && (
|
||||
<button
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRestore();
|
||||
}}
|
||||
className="text-xs bg-orange-600 hover:bg-orange-700 text-white px-2 py-1 rounded flex items-center gap-1 transition-colors"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="!bg-status-warning hover:!bg-status-warning-hover !text-white text-xs"
|
||||
title="Restore all uncommitted changes to their last committed state"
|
||||
>
|
||||
<RefreshCw className="w-3 h-3" />
|
||||
Restore
|
||||
</button>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
<div className="text-xs text-text-tertiary">
|
||||
{formatTimestamp(execution.timestamp)}
|
||||
</div>
|
||||
</div>
|
||||
@ -171,21 +183,23 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
<div className="flex items-center gap-2">
|
||||
{execution.after_commit_hash && execution.after_commit_hash !== 'UNCOMMITTED' && (
|
||||
<>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 font-mono">
|
||||
<div className="text-xs text-text-tertiary font-mono">
|
||||
{execution.after_commit_hash.substring(0, 7)}
|
||||
</div>
|
||||
{onRevert && !isUncommitted && (
|
||||
<button
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRevert(execution.after_commit_hash!);
|
||||
}}
|
||||
className="text-xs bg-red-600 hover:bg-red-700 text-white px-2 py-1 rounded flex items-center gap-1 transition-colors"
|
||||
size="sm"
|
||||
variant="danger"
|
||||
className="text-xs"
|
||||
title="Revert this commit"
|
||||
>
|
||||
<RotateCcw className="w-3 h-3" />
|
||||
Revert
|
||||
</button>
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
@ -195,12 +209,19 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{historyLimitReached && (
|
||||
<div
|
||||
className="flex items-center p-4 border-b border-border-secondary bg-bg-secondary text-text-tertiary text-xs"
|
||||
>
|
||||
Showing the most recent {limitDisplay} commits. Older commits are hidden.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Selection summary */}
|
||||
{selectedExecutions.length > 0 && (
|
||||
<div className="p-4 bg-blue-100 dark:bg-blue-900/20 border-t border-blue-300 dark:border-blue-800">
|
||||
<div className="text-sm text-blue-800 dark:text-blue-200">
|
||||
<div className="p-4 bg-bg-accent border-t border-interactive">
|
||||
<div className="text-sm text-text-accent">
|
||||
{selectedExecutions.length === 1 ? (
|
||||
`1 commit selected`
|
||||
) : selectedExecutions.length === 2 ? (
|
||||
@ -217,4 +238,4 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
|
||||
ExecutionList.displayName = 'ExecutionList';
|
||||
|
||||
export default ExecutionList;
|
||||
export default ExecutionList;
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
import React, { memo } from 'react';
|
||||
import { FileText, FileCode, FileImage, File, Trash2 } from 'lucide-react';
|
||||
import { IconButton } from './ui/IconButton';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
interface FileInfo {
|
||||
path: string;
|
||||
@ -18,7 +20,7 @@ interface FileListProps {
|
||||
|
||||
const getFileIcon = (fileName: string) => {
|
||||
const ext = fileName.split('.').pop()?.toLowerCase();
|
||||
const iconClass = "w-4 h-4 text-gray-600 dark:text-gray-400";
|
||||
const iconClass = "w-4 h-4 text-text-tertiary";
|
||||
|
||||
if (!ext) return <File className={iconClass} />;
|
||||
|
||||
@ -43,15 +45,15 @@ const getFileIcon = (fileName: string) => {
|
||||
const getTypeColor = (type: FileInfo['type']) => {
|
||||
switch (type) {
|
||||
case 'added':
|
||||
return 'text-green-600 dark:text-green-400';
|
||||
return 'text-status-success';
|
||||
case 'deleted':
|
||||
return 'text-red-600 dark:text-red-400';
|
||||
return 'text-status-error';
|
||||
case 'modified':
|
||||
return 'text-blue-600 dark:text-blue-400';
|
||||
return 'text-interactive';
|
||||
case 'renamed':
|
||||
return 'text-purple-600 dark:text-purple-400';
|
||||
return 'text-interactive';
|
||||
default:
|
||||
return 'text-gray-600 dark:text-gray-400';
|
||||
return 'text-text-tertiary';
|
||||
}
|
||||
};
|
||||
|
||||
@ -73,7 +75,7 @@ const getTypeLabel = (type: FileInfo['type']) => {
|
||||
export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onFileDelete, selectedFile }) => {
|
||||
if (files.length === 0) {
|
||||
return (
|
||||
<div className="p-4 text-center text-gray-500 dark:text-gray-400 text-sm">
|
||||
<div className="p-4 text-center text-text-tertiary text-sm">
|
||||
No files changed
|
||||
</div>
|
||||
);
|
||||
@ -81,8 +83,8 @@ export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onF
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="px-4 py-2 border-b border-gray-200 dark:border-gray-700 bg-gray-100 dark:bg-gray-800">
|
||||
<h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
|
||||
<div className="px-4 py-2 border-b border-border-secondary bg-bg-secondary">
|
||||
<h3 className="text-sm font-semibold text-text-secondary">
|
||||
Files Changed ({files.length})
|
||||
</h3>
|
||||
</div>
|
||||
@ -92,9 +94,10 @@ export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onF
|
||||
{files.map((file, index) => (
|
||||
<div
|
||||
key={`${file.path}-${index}`}
|
||||
className={`w-full px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex items-center justify-between group ${
|
||||
selectedFile === file.path ? 'bg-blue-50 dark:bg-blue-900/20' : ''
|
||||
}`}
|
||||
className={cn(
|
||||
'w-full px-4 py-2 hover:bg-bg-hover transition-colors flex items-center justify-between group',
|
||||
selectedFile === file.path && 'bg-bg-accent'
|
||||
)}
|
||||
>
|
||||
<button
|
||||
onClick={() => onFileClick(file.path, index)}
|
||||
@ -104,24 +107,24 @@ export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onF
|
||||
{getTypeLabel(file.type)}
|
||||
</span>
|
||||
{getFileIcon(file.path)}
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300 truncate">
|
||||
<span className="text-sm text-text-primary truncate">
|
||||
{file.path}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-2 ml-2 flex-shrink-0">
|
||||
{file.additions > 0 && (
|
||||
<span className="text-xs text-green-600 dark:text-green-400">
|
||||
<span className="text-xs text-status-success">
|
||||
+{file.additions}
|
||||
</span>
|
||||
)}
|
||||
{file.deletions > 0 && (
|
||||
<span className="text-xs text-red-600 dark:text-red-400">
|
||||
<span className="text-xs text-status-error">
|
||||
-{file.deletions}
|
||||
</span>
|
||||
)}
|
||||
{onFileDelete && (
|
||||
<button
|
||||
<IconButton
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (file.type !== 'deleted' && window.confirm(`Are you sure you want to delete ${file.path}?`)) {
|
||||
@ -129,19 +132,16 @@ export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onF
|
||||
}
|
||||
}}
|
||||
disabled={file.type === 'deleted'}
|
||||
className={`opacity-0 group-hover:opacity-100 p-1 rounded transition-all ${
|
||||
file.type === 'deleted'
|
||||
? 'cursor-not-allowed'
|
||||
: 'hover:bg-red-100 dark:hover:bg-red-900/30'
|
||||
}`}
|
||||
variant={file.type === 'deleted' ? 'ghost' : 'danger'}
|
||||
size="sm"
|
||||
className={cn(
|
||||
'opacity-0 group-hover:opacity-100 transition-opacity',
|
||||
file.type === 'deleted' && 'cursor-not-allowed !text-text-disabled'
|
||||
)}
|
||||
aria-label={file.type === 'deleted' ? 'File already deleted' : 'Delete file'}
|
||||
title={file.type === 'deleted' ? 'File already deleted' : 'Delete file'}
|
||||
>
|
||||
<Trash2 className={`w-4 h-4 ${
|
||||
file.type === 'deleted'
|
||||
? 'text-gray-400 dark:text-gray-600'
|
||||
: 'text-red-600 dark:text-red-400'
|
||||
}`} />
|
||||
</button>
|
||||
icon={<Trash2 className="w-4 h-4" />}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { FileText, Folder } from 'lucide-react';
|
||||
import { FileText, Folder, Zap } from 'lucide-react';
|
||||
|
||||
interface FileItem {
|
||||
path: string;
|
||||
@ -48,7 +48,7 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
const [showSuggestions, setShowSuggestions] = useState(false);
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [cursorPosition, setCursorPosition] = useState(0);
|
||||
const [activePattern, setActivePattern] = useState<{ start: number; pattern: string } | null>(null);
|
||||
const [activePattern, setActivePattern] = useState<{ start: number; pattern: string; type: 'file' | 'slash' } | null>(null);
|
||||
const [dropdownPosition, setDropdownPosition] = useState<{
|
||||
left?: number;
|
||||
right?: number;
|
||||
@ -69,13 +69,20 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
return inputRef.current;
|
||||
};
|
||||
|
||||
// Detect @ pattern in the text
|
||||
// Detect @ pattern (file paths) or / pattern (slash commands) in the text
|
||||
const detectPattern = useCallback((text: string, cursorPos: number) => {
|
||||
// Find the last @ before the cursor
|
||||
let lastAtIndex = -1;
|
||||
// Find the last @ or / before the cursor
|
||||
let lastPatternIndex = -1;
|
||||
let patternType: 'file' | 'slash' | null = null;
|
||||
|
||||
for (let i = cursorPos - 1; i >= 0; i--) {
|
||||
if (text[i] === '@') {
|
||||
lastAtIndex = i;
|
||||
lastPatternIndex = i;
|
||||
patternType = 'file';
|
||||
break;
|
||||
} else if (text[i] === '/') {
|
||||
lastPatternIndex = i;
|
||||
patternType = 'slash';
|
||||
break;
|
||||
}
|
||||
// Stop if we hit whitespace or newline
|
||||
@ -84,12 +91,12 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
}
|
||||
}
|
||||
|
||||
if (lastAtIndex !== -1) {
|
||||
// Extract the pattern from @ to cursor
|
||||
const pattern = text.substring(lastAtIndex + 1, cursorPos);
|
||||
// Check if there's no whitespace after the @
|
||||
if (lastPatternIndex !== -1 && patternType) {
|
||||
// Extract the pattern from @ or / to cursor
|
||||
const pattern = text.substring(lastPatternIndex + 1, cursorPos);
|
||||
// Check if there's no whitespace after the trigger
|
||||
if (!pattern.includes(' ') && !pattern.includes('\n')) {
|
||||
return { start: lastAtIndex, pattern };
|
||||
return { start: lastPatternIndex, pattern, type: patternType };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@ -173,6 +180,40 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Get available slash commands for the current session
|
||||
const getSlashCommands = useCallback((): FileItem[] => {
|
||||
if (!sessionId) return [];
|
||||
|
||||
try {
|
||||
const slashCommandsKey = `slashCommands_${sessionId}`;
|
||||
const stored = localStorage.getItem(slashCommandsKey);
|
||||
if (stored) {
|
||||
const commands: string[] = JSON.parse(stored);
|
||||
console.log('[slash-debug] Retrieved slash commands from localStorage:', commands);
|
||||
return commands.map(cmd => ({
|
||||
path: cmd,
|
||||
isDirectory: false,
|
||||
name: cmd
|
||||
}));
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[slash-debug] Failed to retrieve slash commands:', e);
|
||||
}
|
||||
|
||||
return [];
|
||||
}, [sessionId]);
|
||||
|
||||
// Search for slash commands
|
||||
const searchSlashCommands = useCallback((pattern: string) => {
|
||||
const commands = getSlashCommands();
|
||||
const filtered = commands.filter(cmd =>
|
||||
cmd.path.toLowerCase().includes(pattern.toLowerCase())
|
||||
);
|
||||
console.log('[slash-debug] Filtered slash commands:', filtered);
|
||||
setSuggestions(filtered);
|
||||
setSelectedIndex(0);
|
||||
}, [getSlashCommands]);
|
||||
|
||||
// Search for files
|
||||
const searchFiles = useCallback(async (pattern: string) => {
|
||||
if (!sessionId && !projectId) return;
|
||||
@ -199,33 +240,54 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
const newValue = e.target.value;
|
||||
const cursorPos = e.target.selectionStart || 0;
|
||||
|
||||
|
||||
onChange(newValue);
|
||||
setCursorPosition(cursorPos);
|
||||
|
||||
// Check for @ pattern
|
||||
const pattern = detectPattern(newValue, cursorPos);
|
||||
setActivePattern(pattern);
|
||||
// Only check for pattern if value contains "@" or "/" - performance optimization
|
||||
if (newValue.includes('@') || newValue.includes('/')) {
|
||||
setCursorPosition(cursorPos);
|
||||
|
||||
if (pattern) {
|
||||
// Clear existing timeout
|
||||
if (searchTimeoutRef.current) {
|
||||
clearTimeout(searchTimeoutRef.current);
|
||||
// Check for @ pattern (file paths) or / pattern (slash commands)
|
||||
const pattern = detectPattern(newValue, cursorPos);
|
||||
setActivePattern(pattern);
|
||||
|
||||
if (pattern) {
|
||||
// Clear existing timeout
|
||||
if (searchTimeoutRef.current) {
|
||||
clearTimeout(searchTimeoutRef.current);
|
||||
}
|
||||
|
||||
// Debounce the search
|
||||
searchTimeoutRef.current = setTimeout(() => {
|
||||
if (pattern.type === 'slash') {
|
||||
console.log('[slash-debug] Searching slash commands with pattern:', pattern.pattern);
|
||||
searchSlashCommands(pattern.pattern);
|
||||
} else {
|
||||
searchFiles(pattern.pattern);
|
||||
}
|
||||
setShowSuggestions(true);
|
||||
}, 200);
|
||||
} else {
|
||||
setShowSuggestions(false);
|
||||
setSuggestions([]);
|
||||
}
|
||||
|
||||
// Debounce the search
|
||||
searchTimeoutRef.current = setTimeout(() => {
|
||||
searchFiles(pattern.pattern);
|
||||
setShowSuggestions(true);
|
||||
}, 200);
|
||||
} else {
|
||||
setShowSuggestions(false);
|
||||
setSuggestions([]);
|
||||
// No @ or / in text, clear autocomplete state
|
||||
if (showSuggestions) {
|
||||
setShowSuggestions(false);
|
||||
setSuggestions([]);
|
||||
setActivePattern(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Handle selection change (cursor movement)
|
||||
const handleSelectionChange = (e: React.SyntheticEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
// Only process cursor movement if autocomplete is active - performance optimization
|
||||
if (!showSuggestions && !value.includes('@') && !value.includes('/')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = e.target as HTMLInputElement | HTMLTextAreaElement;
|
||||
const cursorPos = target.selectionStart || 0;
|
||||
setCursorPosition(cursorPos);
|
||||
@ -243,11 +305,12 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
const selectSuggestion = (suggestion: FileItem) => {
|
||||
if (!activePattern) return;
|
||||
|
||||
// Replace the pattern with the selected file path
|
||||
// Replace the pattern with the selected path
|
||||
const before = value.substring(0, activePattern.start);
|
||||
const after = value.substring(cursorPosition);
|
||||
const newValue = before + '@' + suggestion.path + after;
|
||||
|
||||
const prefix = activePattern.type === 'slash' ? '/' : '@';
|
||||
const newValue = before + prefix + suggestion.path + after;
|
||||
|
||||
onChange(newValue);
|
||||
setShowSuggestions(false);
|
||||
setSuggestions([]);
|
||||
@ -267,6 +330,10 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
if (onSelect) {
|
||||
onSelect(suggestion.path);
|
||||
}
|
||||
|
||||
if (activePattern.type === 'slash') {
|
||||
console.log('[slash-debug] Selected slash command:', suggestion.path);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle keyboard navigation
|
||||
@ -318,9 +385,9 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
// Close dropdown when clicking outside
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
if (dropdownRef.current && event.target && event.target instanceof Node && !dropdownRef.current.contains(event.target)) {
|
||||
const element = getInputElement();
|
||||
if (element && !element.contains(event.target as Node)) {
|
||||
if (element && event.target && event.target instanceof Node && !element.contains(event.target)) {
|
||||
setShowSuggestions(false);
|
||||
}
|
||||
}
|
||||
@ -354,7 +421,7 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="relative h-full w-full">
|
||||
{isTextarea ? (
|
||||
<textarea
|
||||
ref={textareaRef || internalTextareaRef}
|
||||
@ -372,7 +439,7 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
{showSuggestions && suggestions.length > 0 && (
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="absolute z-50 max-h-60 overflow-auto rounded-md bg-gray-800 py-1 shadow-lg ring-1 ring-black ring-opacity-5"
|
||||
className="absolute z-50 max-h-60 overflow-auto rounded-md bg-surface-secondary py-1 shadow-lg ring-1 ring-black ring-opacity-5 border border-border-primary"
|
||||
style={{
|
||||
minWidth: Math.min(300, dropdownPosition?.maxWidth || 300) + 'px',
|
||||
maxWidth: dropdownPosition?.maxWidth || '800px',
|
||||
@ -385,25 +452,34 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
|
||||
})
|
||||
}}
|
||||
>
|
||||
{suggestions.map((suggestion, index) => (
|
||||
<div
|
||||
key={suggestion.path}
|
||||
className={`flex items-center px-4 py-2.5 cursor-pointer min-w-0 ${
|
||||
index === selectedIndex
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'text-gray-300 hover:bg-gray-700'
|
||||
}`}
|
||||
onClick={() => selectSuggestion(suggestion)}
|
||||
onMouseEnter={() => setSelectedIndex(index)}
|
||||
>
|
||||
{suggestion.isDirectory ? (
|
||||
<Folder className="w-4 h-4 mr-3 flex-shrink-0" />
|
||||
) : (
|
||||
<FileText className="w-4 h-4 mr-3 flex-shrink-0" />
|
||||
)}
|
||||
<span className="text-sm truncate pr-2" title={suggestion.path}>{suggestion.path}</span>
|
||||
</div>
|
||||
))}
|
||||
{suggestions.map((suggestion, index) => {
|
||||
// Check if this is a slash command (activePattern will be set)
|
||||
const isSlashCommand = activePattern?.type === 'slash';
|
||||
|
||||
return (
|
||||
<div
|
||||
key={suggestion.path}
|
||||
className={`flex items-center px-4 py-2.5 cursor-pointer min-w-0 transition-colors ${
|
||||
index === selectedIndex
|
||||
? 'bg-interactive text-on-interactive'
|
||||
: 'text-text-secondary hover:bg-surface-hover'
|
||||
}`}
|
||||
onClick={() => selectSuggestion(suggestion)}
|
||||
onMouseEnter={() => setSelectedIndex(index)}
|
||||
>
|
||||
{isSlashCommand ? (
|
||||
<Zap className="w-4 h-4 mr-3 flex-shrink-0 text-purple-500" />
|
||||
) : suggestion.isDirectory ? (
|
||||
<Folder className="w-4 h-4 mr-3 flex-shrink-0" />
|
||||
) : (
|
||||
<FileText className="w-4 h-4 mr-3 flex-shrink-0" />
|
||||
)}
|
||||
<span className="text-sm truncate pr-2" title={suggestion.path}>
|
||||
{isSlashCommand ? '/' : ''}{suggestion.path}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
353
frontend/src/components/GitStatusIndicator.tsx
Normal file
@ -0,0 +1,353 @@
|
||||
import React from 'react';
|
||||
import { Check, Edit, CircleArrowDown, AlertTriangle, HelpCircle, GitMerge, Loader2 } from 'lucide-react';
|
||||
import type { GitStatus } from '../types/session';
|
||||
|
||||
interface GitStatusIndicatorProps {
|
||||
gitStatus?: GitStatus;
|
||||
size?: 'small' | 'medium' | 'large';
|
||||
sessionId?: string;
|
||||
onClick?: () => void;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
interface GitStatusConfig {
|
||||
color: string;
|
||||
bgColor: string;
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the git status indicates the branch is fully synced with main
|
||||
*/
|
||||
function isGitStatusFullySynced(gitStatus: GitStatus): boolean {
|
||||
return (!gitStatus.ahead || gitStatus.ahead === 0) &&
|
||||
(!gitStatus.behind || gitStatus.behind === 0) &&
|
||||
(!gitStatus.hasUncommittedChanges) &&
|
||||
(!gitStatus.hasUntrackedFiles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the comprehensive tooltip content for the git status indicator
|
||||
*/
|
||||
function buildTooltipContent(gitStatus: GitStatus, config: GitStatusConfig): string {
|
||||
let tooltipContent = '';
|
||||
|
||||
// Show total commits in branch if available
|
||||
if (gitStatus.totalCommits && gitStatus.totalCommits > 0) {
|
||||
tooltipContent = `${gitStatus.totalCommits} commit${gitStatus.totalCommits !== 1 ? 's' : ''} in branch`;
|
||||
|
||||
// Add ahead/behind info if relevant
|
||||
if (gitStatus.ahead && gitStatus.ahead > 0) {
|
||||
tooltipContent += ` (${gitStatus.ahead} ahead of main)`;
|
||||
} else if (gitStatus.behind && gitStatus.behind > 0) {
|
||||
tooltipContent += ` (${gitStatus.behind} behind main)`;
|
||||
} else if (gitStatus.state === 'diverged') {
|
||||
tooltipContent += ` (${gitStatus.ahead || 0} ahead, ${gitStatus.behind || 0} behind)`;
|
||||
}
|
||||
|
||||
// Add file change statistics for commits
|
||||
if (gitStatus.commitFilesChanged) {
|
||||
tooltipContent += `\n${gitStatus.commitFilesChanged} files changed (+${gitStatus.commitAdditions || 0}/-${gitStatus.commitDeletions || 0})`;
|
||||
}
|
||||
} else if (gitStatus.ahead && gitStatus.ahead > 0) {
|
||||
// Fallback to old behavior if totalCommits not available
|
||||
tooltipContent = `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} ahead of main`;
|
||||
if (gitStatus.commitFilesChanged) {
|
||||
tooltipContent += `\n${gitStatus.commitFilesChanged} files changed (+${gitStatus.commitAdditions || 0}/-${gitStatus.commitDeletions || 0})`;
|
||||
}
|
||||
} else if (gitStatus.behind && gitStatus.behind > 0) {
|
||||
tooltipContent = `${gitStatus.behind} commit${gitStatus.behind !== 1 ? 's' : ''} behind main`;
|
||||
} else if (gitStatus.state === 'diverged') {
|
||||
tooltipContent = `${gitStatus.ahead || 0} ahead, ${gitStatus.behind || 0} behind main`;
|
||||
}
|
||||
|
||||
// Add uncommitted changes info
|
||||
if (gitStatus.hasUncommittedChanges && gitStatus.filesChanged) {
|
||||
if (tooltipContent) tooltipContent += '\n\n';
|
||||
tooltipContent += `Uncommitted changes:\n${gitStatus.filesChanged} file${gitStatus.filesChanged !== 1 ? 's' : ''} modified`;
|
||||
if (gitStatus.additions || gitStatus.deletions) {
|
||||
tooltipContent += ` (+${gitStatus.additions || 0}/-${gitStatus.deletions || 0})`;
|
||||
}
|
||||
}
|
||||
|
||||
// If still no content (e.g., clean state with no commits ahead), be more descriptive
|
||||
if (!tooltipContent) {
|
||||
if (gitStatus.state === 'clean') {
|
||||
tooltipContent = 'Branch is up to date with main\nNo uncommitted changes';
|
||||
} else if (gitStatus.state === 'modified' && gitStatus.filesChanged) {
|
||||
tooltipContent = `${gitStatus.filesChanged} uncommitted file${gitStatus.filesChanged !== 1 ? 's' : ''}`;
|
||||
if (gitStatus.additions || gitStatus.deletions) {
|
||||
tooltipContent += ` (+${gitStatus.additions || 0}/-${gitStatus.deletions || 0})`;
|
||||
}
|
||||
} else {
|
||||
tooltipContent = config.description;
|
||||
}
|
||||
}
|
||||
|
||||
// Add untracked files note
|
||||
if (gitStatus.hasUntrackedFiles) {
|
||||
tooltipContent += '\n+ untracked files';
|
||||
}
|
||||
|
||||
// Add actionable information based on new simplified scheme
|
||||
let actionableInfo = '';
|
||||
|
||||
// Check sync status
|
||||
const isFullySynced = isGitStatusFullySynced(gitStatus);
|
||||
const hasCommitsToMerge = gitStatus.ahead && gitStatus.ahead > 0 && !gitStatus.hasUncommittedChanges && !gitStatus.hasUntrackedFiles && (!gitStatus.behind || gitStatus.behind === 0);
|
||||
const hasConflictRisk = gitStatus.ahead && gitStatus.ahead > 0 && gitStatus.behind && gitStatus.behind > 0;
|
||||
const isMostlyBehind = hasConflictRisk && gitStatus.behind && gitStatus.ahead && gitStatus.behind >= 5 * gitStatus.ahead && gitStatus.ahead <= 2;
|
||||
|
||||
if (hasCommitsToMerge || gitStatus.isReadyToMerge) {
|
||||
actionableInfo = '🔀 Ready to merge - no conflicts expected';
|
||||
} else if (isMostlyBehind) {
|
||||
actionableInfo = '📊 Mostly behind main - minimal unique changes, consider rebasing or removing';
|
||||
} else if (hasConflictRisk) {
|
||||
actionableInfo = '⚠️ Rebase from main before merging to avoid conflicts';
|
||||
} else if (gitStatus.state === 'conflict') {
|
||||
actionableInfo = '🚫 Resolve merge conflicts before continuing';
|
||||
} else if (gitStatus.hasUncommittedChanges || gitStatus.hasUntrackedFiles) {
|
||||
actionableInfo = '📝 Commit changes before merging';
|
||||
} else if (gitStatus.behind && gitStatus.behind > 0 && (!gitStatus.ahead || gitStatus.ahead === 0)) {
|
||||
actionableInfo = '⬇️ Consider updating or removing - no unique changes';
|
||||
} else if (isFullySynced) {
|
||||
actionableInfo = '✅ Safe to remove - no unique changes';
|
||||
}
|
||||
|
||||
if (actionableInfo) {
|
||||
tooltipContent += '\n\n' + actionableInfo;
|
||||
}
|
||||
|
||||
// Add click hint
|
||||
tooltipContent += '\n\nClick to view diff details';
|
||||
|
||||
return tooltipContent;
|
||||
}
|
||||
|
||||
function getGitStatusConfig(gitStatus: GitStatus): GitStatusConfig {
|
||||
const iconProps = { size: 14, strokeWidth: 2 };
|
||||
|
||||
// HIGH PRIORITY: Branches with changes that matter
|
||||
|
||||
// 1. Ready to Merge (HIGH PRIORITY) - Has commits to merge, clean working directory, not behind
|
||||
if (gitStatus.isReadyToMerge ||
|
||||
(gitStatus.ahead && gitStatus.ahead > 0 && !gitStatus.hasUncommittedChanges && !gitStatus.hasUntrackedFiles && (!gitStatus.behind || gitStatus.behind === 0))) {
|
||||
const commitCount = gitStatus.totalCommits || gitStatus.ahead || 0;
|
||||
return {
|
||||
color: 'text-green-600 dark:text-green-400',
|
||||
bgColor: 'bg-green-100 dark:bg-green-900/30',
|
||||
icon: <GitMerge {...iconProps} />,
|
||||
label: 'Ready to Merge',
|
||||
description: `${commitCount} commit${commitCount !== 1 ? 's' : ''} ready to merge`
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Conflict Risk (HIGH PRIORITY) - Has commits but also behind main
|
||||
// Special case: If significantly behind with minimal ahead, treat as "Mostly Behind" instead of conflict risk
|
||||
if (gitStatus.ahead && gitStatus.ahead > 0 && gitStatus.behind && gitStatus.behind > 0) {
|
||||
// If the branch is significantly more behind than ahead (5:1 ratio), and has few commits ahead (<=2),
|
||||
// treat it more like a "behind" branch than a conflict risk
|
||||
const mostlyBehind = gitStatus.behind >= 5 * gitStatus.ahead && gitStatus.ahead <= 2;
|
||||
|
||||
if (mostlyBehind) {
|
||||
// Show as "Mostly Behind" with gray color like other low-priority statuses
|
||||
return {
|
||||
color: 'text-gray-500 dark:text-gray-400',
|
||||
bgColor: 'bg-gray-100 dark:bg-gray-800/30',
|
||||
icon: <CircleArrowDown {...iconProps} />,
|
||||
label: 'Mostly Behind',
|
||||
description: `${gitStatus.behind} behind, ${gitStatus.ahead} ahead - consider rebasing`
|
||||
};
|
||||
}
|
||||
|
||||
// Normal conflict risk for branches with significant divergence
|
||||
return {
|
||||
color: 'text-amber-600 dark:text-amber-400',
|
||||
bgColor: 'bg-amber-100 dark:bg-amber-900/30',
|
||||
icon: <AlertTriangle {...iconProps} />,
|
||||
label: 'Conflict Risk',
|
||||
description: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind - potential conflicts`
|
||||
};
|
||||
}
|
||||
|
||||
// SPECIAL CASES: Keep these distinct
|
||||
|
||||
// Active merge conflicts
|
||||
if (gitStatus.state === 'conflict') {
|
||||
return {
|
||||
color: 'text-red-600 dark:text-red-400',
|
||||
bgColor: 'bg-red-100 dark:bg-red-900/30',
|
||||
icon: <AlertTriangle {...iconProps} />,
|
||||
label: 'Conflicts',
|
||||
description: 'Has merge conflicts - resolve before continuing'
|
||||
};
|
||||
}
|
||||
|
||||
// Uncommitted changes (includes both modified and untracked)
|
||||
if (gitStatus.hasUncommittedChanges || gitStatus.hasUntrackedFiles || gitStatus.state === 'modified' || gitStatus.state === 'untracked') {
|
||||
const ahead = gitStatus.ahead || 0;
|
||||
const filesChanged = gitStatus.filesChanged || 0;
|
||||
const hasFiles = filesChanged > 0 || gitStatus.hasUntrackedFiles;
|
||||
|
||||
let description = '';
|
||||
if (ahead > 0 && hasFiles) {
|
||||
description = `${ahead} commit${ahead !== 1 ? 's' : ''} + uncommitted changes`;
|
||||
} else if (hasFiles) {
|
||||
description = gitStatus.hasUntrackedFiles ? 'Untracked files' : `${filesChanged} uncommitted file${filesChanged !== 1 ? 's' : ''}`;
|
||||
} else {
|
||||
description = 'Uncommitted changes';
|
||||
}
|
||||
|
||||
return {
|
||||
color: 'text-blue-600 dark:text-blue-400',
|
||||
bgColor: 'bg-blue-100 dark:bg-blue-900/30',
|
||||
icon: <Edit {...iconProps} />,
|
||||
label: 'Uncommitted',
|
||||
description: description
|
||||
};
|
||||
}
|
||||
|
||||
// LOW PRIORITY: Branches you care little about
|
||||
|
||||
// Behind only (no commits ahead)
|
||||
if (gitStatus.behind && gitStatus.behind > 0 && (!gitStatus.ahead || gitStatus.ahead === 0)) {
|
||||
return {
|
||||
color: 'text-gray-500 dark:text-gray-400',
|
||||
bgColor: 'bg-gray-100 dark:bg-gray-800/30',
|
||||
icon: <CircleArrowDown {...iconProps} />,
|
||||
label: 'Behind Only',
|
||||
description: `${gitStatus.behind} commit${gitStatus.behind !== 1 ? 's' : ''} behind main`
|
||||
};
|
||||
}
|
||||
|
||||
// Up to date (fully synced)
|
||||
const isFullySynced = isGitStatusFullySynced(gitStatus);
|
||||
if (isFullySynced) {
|
||||
return {
|
||||
color: 'text-gray-500 dark:text-gray-400',
|
||||
bgColor: 'bg-gray-100 dark:bg-gray-800/30',
|
||||
icon: <Check {...iconProps} />,
|
||||
label: 'Up to Date',
|
||||
description: 'No changes - safe to remove'
|
||||
};
|
||||
}
|
||||
|
||||
// Fallback for unknown states
|
||||
return {
|
||||
color: 'text-gray-500 dark:text-gray-400',
|
||||
bgColor: 'bg-gray-100 dark:bg-gray-800/30',
|
||||
icon: <HelpCircle {...iconProps} />,
|
||||
label: 'Unknown',
|
||||
description: 'Unable to determine git status'
|
||||
};
|
||||
}
|
||||
|
||||
const GitStatusIndicator: React.FC<GitStatusIndicatorProps> = React.memo(({ gitStatus, size = 'small', sessionId, onClick, isLoading }) => {
|
||||
// Size configurations
|
||||
const sizeConfig = {
|
||||
small: {
|
||||
dot: 'w-2 h-2',
|
||||
text: 'text-xs',
|
||||
padding: 'px-1.5 py-0.5',
|
||||
gap: 'gap-0.5',
|
||||
loader: 'w-3 h-3'
|
||||
},
|
||||
medium: {
|
||||
dot: 'w-3 h-3',
|
||||
text: 'text-sm',
|
||||
padding: 'px-2 py-1',
|
||||
gap: 'gap-1',
|
||||
loader: 'w-4 h-4'
|
||||
},
|
||||
large: {
|
||||
dot: 'w-4 h-4',
|
||||
text: 'text-base',
|
||||
padding: 'px-3 py-1.5',
|
||||
gap: 'gap-1.5',
|
||||
loader: 'w-5 h-5'
|
||||
}
|
||||
}[size];
|
||||
|
||||
// Show loading state
|
||||
if (isLoading === true) {
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center justify-center w-[5.5ch] ${sizeConfig.padding} ${sizeConfig.text} rounded-md border bg-gray-100 dark:bg-gray-900/30 text-gray-500 dark:text-gray-400 border-gray-300 dark:border-gray-600`}
|
||||
title="Checking git status..."
|
||||
data-testid={sessionId ? `session-${sessionId}-git-status` : 'git-status'}
|
||||
data-git-loading="true"
|
||||
>
|
||||
<Loader2 className={`${sizeConfig.loader} animate-spin`} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// No git status and not loading
|
||||
if (!gitStatus) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const config = getGitStatusConfig(gitStatus);
|
||||
|
||||
// Build comprehensive tooltip content using helper function
|
||||
const tooltipContent = buildTooltipContent(gitStatus, config);
|
||||
|
||||
const handleClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (onClick) {
|
||||
onClick();
|
||||
} else if (sessionId) {
|
||||
// Dispatch event to select session and switch to View Diff tab
|
||||
const selectEvent = new CustomEvent('select-session-and-view-diff', {
|
||||
detail: { sessionId }
|
||||
});
|
||||
window.dispatchEvent(selectEvent);
|
||||
}
|
||||
};
|
||||
|
||||
// Determine the primary count to display
|
||||
let primaryCount = 0;
|
||||
let ariaLabel = config.label;
|
||||
|
||||
if (gitStatus.totalCommits && gitStatus.totalCommits > 0) {
|
||||
primaryCount = gitStatus.totalCommits;
|
||||
ariaLabel = `${primaryCount} commit${primaryCount !== 1 ? 's' : ''} in branch`;
|
||||
} else if (gitStatus.filesChanged && gitStatus.filesChanged > 0) {
|
||||
primaryCount = gitStatus.filesChanged;
|
||||
ariaLabel = `${primaryCount} file${primaryCount !== 1 ? 's' : ''} changed`;
|
||||
} else if (gitStatus.ahead && gitStatus.ahead > 0) {
|
||||
primaryCount = gitStatus.ahead;
|
||||
ariaLabel = `Ahead by ${primaryCount} commit${primaryCount !== 1 ? 's' : ''}`;
|
||||
} else if (gitStatus.behind && gitStatus.behind > 0) {
|
||||
primaryCount = gitStatus.behind;
|
||||
ariaLabel = `Behind by ${primaryCount} commit${primaryCount !== 1 ? 's' : ''}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center ${primaryCount > 0 ? 'justify-center gap-0.5' : 'justify-center'} w-[5.5ch] ${sizeConfig.padding} ${sizeConfig.text} rounded-md border ${config.bgColor} ${config.color} border-gray-300 dark:border-gray-600 ${(onClick || sessionId) ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
|
||||
title={tooltipContent}
|
||||
onClick={handleClick}
|
||||
aria-label={ariaLabel}
|
||||
data-testid={sessionId ? `session-${sessionId}-git-status` : 'git-status'}
|
||||
data-git-state={gitStatus.state}
|
||||
data-git-ahead={gitStatus.ahead}
|
||||
data-git-behind={gitStatus.behind}
|
||||
>
|
||||
<span className="flex-shrink-0">
|
||||
{config.icon}
|
||||
</span>
|
||||
{primaryCount > 0 && (
|
||||
<span className="font-bold">
|
||||
{primaryCount > 9 ? '★' : primaryCount}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
});
|
||||
|
||||
GitStatusIndicator.displayName = 'GitStatusIndicator';
|
||||
|
||||
export { GitStatusIndicator };
|
||||
@ -1,4 +1,5 @@
|
||||
import { X, GitBranch, Terminal, Folder, Zap, MessageSquare, Settings, Bell, History } from 'lucide-react';
|
||||
import { GitBranch, Terminal, Folder, Zap, MessageSquare, Settings, Bell, History } from 'lucide-react';
|
||||
import { Modal, ModalHeader, ModalBody } from './ui/Modal';
|
||||
|
||||
interface HelpProps {
|
||||
isOpen: boolean;
|
||||
@ -6,36 +7,24 @@ interface HelpProps {
|
||||
}
|
||||
|
||||
export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4 overflow-y-auto">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
|
||||
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<h2 className="text-2xl font-bold text-gray-900 dark:text-white">Crystal Help</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-500 dark:hover:text-gray-300"
|
||||
>
|
||||
<X className="h-6 w-6" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
<div className="space-y-8">
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="xl" showCloseButton={false}>
|
||||
<ModalHeader>Crystal Help</ModalHeader>
|
||||
<ModalBody>
|
||||
<div className="space-y-8">
|
||||
{/* Quick Start */}
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
|
||||
<Zap className="h-5 w-5 mr-2" />
|
||||
Quick Start
|
||||
</h3>
|
||||
<div className="space-y-3 text-gray-700 dark:text-gray-300">
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
|
||||
<p className="font-medium text-blue-900 dark:text-blue-200 mb-2">Prerequisites</p>
|
||||
<div className="space-y-3 text-text-secondary">
|
||||
<div className="bg-interactive/10 border border-interactive/30 rounded-lg p-3">
|
||||
<p className="font-medium text-interactive mb-2">Prerequisites</p>
|
||||
<ul className="list-disc list-inside space-y-1 text-sm">
|
||||
<li>Claude Code must be installed with credentials configured</li>
|
||||
<li>We recommend using a MAX plan for best performance</li>
|
||||
<li>Crystal runs Claude Code with <code className="bg-gray-200 dark:bg-gray-700 px-1 rounded">--dangerously-ignore-permissions</code></li>
|
||||
<li>Crystal runs Claude Code with <code className="bg-surface-tertiary px-1 rounded">--dangerously-ignore-permissions</code></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@ -57,7 +46,7 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
</li>
|
||||
<li><strong>Work with results:</strong>
|
||||
<ul className="list-disc list-inside ml-4 mt-1 text-sm">
|
||||
<li>View changes in the View Diff tab</li>
|
||||
<li>View changes in the Diff panel</li>
|
||||
<li>Continue conversations to refine the solution</li>
|
||||
<li>Rebase back to your main branch when done</li>
|
||||
</ul>
|
||||
@ -69,14 +58,14 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
|
||||
{/* Session Management */}
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
|
||||
<Terminal className="h-5 w-5 mr-2" />
|
||||
Session Management
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">Creating Sessions</h4>
|
||||
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
|
||||
<h4 className="font-medium text-text-primary">Creating Sessions</h4>
|
||||
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
|
||||
<li>Enter a prompt describing what you want Claude to do</li>
|
||||
<li>Optionally specify a worktree name template</li>
|
||||
<li>Create multiple sessions at once with the count field</li>
|
||||
@ -84,20 +73,20 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">Session States</h4>
|
||||
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
|
||||
<li><span className="text-yellow-600 dark:text-yellow-500">Initializing</span> - Setting up git worktree</li>
|
||||
<li><span className="text-blue-600 dark:text-blue-500">Running</span> - Claude is processing</li>
|
||||
<li><span className="text-green-600 dark:text-green-500">Waiting</span> - Waiting for your input</li>
|
||||
<li><span className="text-gray-600 dark:text-gray-400">Stopped</span> - Session completed or stopped</li>
|
||||
<li><span className="text-red-600 dark:text-red-500">Error</span> - Something went wrong</li>
|
||||
<h4 className="font-medium text-text-primary">Session States</h4>
|
||||
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
|
||||
<li><span className="text-status-warning">Initializing</span> - Setting up git worktree</li>
|
||||
<li><span className="text-interactive">Running</span> - Claude is processing</li>
|
||||
<li><span className="text-status-success">Waiting</span> - Waiting for your input</li>
|
||||
<li><span className="text-text-tertiary">Stopped</span> - Session completed or stopped</li>
|
||||
<li><span className="text-status-error">Error</span> - Something went wrong</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">Continuing Conversations</h4>
|
||||
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
|
||||
<h4 className="font-medium text-text-primary">Continuing Conversations</h4>
|
||||
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
|
||||
<li>Click on a stopped session to resume it</li>
|
||||
<li>Use <kbd className="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded text-sm">Cmd/Ctrl + Enter</kbd> to send input</li>
|
||||
<li>Use <kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Enter</kbd> to send input</li>
|
||||
<li>Full conversation history is preserved</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -106,17 +95,17 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
|
||||
{/* Git Integration */}
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
|
||||
<GitBranch className="h-5 w-5 mr-2" />
|
||||
Git Worktree Integration
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
<p className="text-gray-700 dark:text-gray-300">
|
||||
<p className="text-text-secondary">
|
||||
Each session operates in its own git worktree, allowing parallel development without conflicts.
|
||||
</p>
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">Git Operations</h4>
|
||||
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
|
||||
<h4 className="font-medium text-text-primary">Git Operations</h4>
|
||||
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
|
||||
<li><strong>Rebase from main</strong> - Pull latest changes from main branch</li>
|
||||
<li><strong>Squash and rebase to main</strong> - Combine commits and rebase onto main</li>
|
||||
<li>View diffs in the View Diff tab</li>
|
||||
@ -128,40 +117,40 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
|
||||
{/* View Tabs */}
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
|
||||
<MessageSquare className="h-5 w-5 mr-2" />
|
||||
View Tabs
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">Output</h4>
|
||||
<p className="text-gray-700 dark:text-gray-300">Formatted terminal output with syntax highlighting</p>
|
||||
<h4 className="font-medium text-text-primary">Output</h4>
|
||||
<p className="text-text-secondary">Formatted terminal output with syntax highlighting</p>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">Messages</h4>
|
||||
<p className="text-gray-700 dark:text-gray-300">Raw JSON messages for debugging</p>
|
||||
<h4 className="font-medium text-text-primary">Messages</h4>
|
||||
<p className="text-text-secondary">Raw JSON messages for debugging</p>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">View Diff</h4>
|
||||
<p className="text-gray-700 dark:text-gray-300">Git diffs showing all file changes</p>
|
||||
<h4 className="font-medium text-text-primary">View Diff</h4>
|
||||
<p className="text-text-secondary">Git diffs showing all file changes</p>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">Terminal</h4>
|
||||
<p className="text-gray-700 dark:text-gray-300">Run project scripts (tests, builds, etc.)</p>
|
||||
<h4 className="font-medium text-text-primary">Terminal</h4>
|
||||
<p className="text-text-secondary">Run project scripts (tests, builds, etc.)</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Project Management */}
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
|
||||
<Folder className="h-5 w-5 mr-2" />
|
||||
Project Management
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">Project Settings</h4>
|
||||
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
|
||||
<h4 className="font-medium text-text-primary">Project Settings</h4>
|
||||
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
|
||||
<li>Custom system prompts per project</li>
|
||||
<li>Run scripts for testing/building</li>
|
||||
<li>Main branch configuration</li>
|
||||
@ -173,11 +162,11 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
|
||||
{/* Prompts Tab */}
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
|
||||
<History className="h-5 w-5 mr-2" />
|
||||
Prompts History
|
||||
</h3>
|
||||
<div className="space-y-2 text-gray-700 dark:text-gray-300">
|
||||
<div className="space-y-2 text-text-secondary">
|
||||
<p>Access all prompts from the Prompts tab in the sidebar:</p>
|
||||
<ul className="list-disc list-inside mt-1 space-y-1">
|
||||
<li>Search through all prompts and session names</li>
|
||||
@ -190,14 +179,14 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
|
||||
{/* Settings */}
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
|
||||
<Settings className="h-5 w-5 mr-2" />
|
||||
Settings
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200">Global Settings</h4>
|
||||
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
|
||||
<h4 className="font-medium text-text-primary">Global Settings</h4>
|
||||
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
|
||||
<li>Verbose logging for debugging</li>
|
||||
<li>Anthropic API key for AI features</li>
|
||||
<li>Global system prompt additions</li>
|
||||
@ -205,11 +194,11 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-800 dark:text-gray-200 flex items-center">
|
||||
<h4 className="font-medium text-text-primary flex items-center">
|
||||
<Bell className="h-4 w-4 mr-1" />
|
||||
Notifications
|
||||
</h4>
|
||||
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
|
||||
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
|
||||
<li>Desktop notifications for status changes</li>
|
||||
<li>Sound alerts when sessions need input</li>
|
||||
<li>Customizable notification triggers</li>
|
||||
@ -220,27 +209,39 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
|
||||
{/* Keyboard Shortcuts */}
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-3">
|
||||
Keyboard Shortcuts
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-gray-700 dark:text-gray-300">Send Input / Continue Conversation</span>
|
||||
<kbd className="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded text-sm">Cmd/Ctrl + Enter</kbd>
|
||||
<span className="text-text-secondary">Send Input / Continue Conversation</span>
|
||||
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Enter</kbd>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-gray-700 dark:text-gray-300">Open Prompt History</span>
|
||||
<kbd className="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded text-sm">Cmd/Ctrl + P</kbd>
|
||||
<span className="text-text-secondary">Quick Create Session (untitled)</span>
|
||||
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Shift + N</kbd>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-text-secondary">Open Prompt History</span>
|
||||
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + P</kbd>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-text-secondary">Navigate Back in Session History</span>
|
||||
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Option/Alt + ←</kbd>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-text-secondary">Navigate Forward in Session History</span>
|
||||
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Option/Alt + →</kbd>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Tips */}
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-3">
|
||||
Tips & Tricks
|
||||
</h3>
|
||||
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 space-y-2">
|
||||
<ul className="list-disc list-inside text-text-secondary space-y-2">
|
||||
<li>Run multiple sessions with different approaches to compare results</li>
|
||||
<li>Use descriptive worktree names to organize your experiments</li>
|
||||
<li>Check the View Diff tab to review what Claude modified</li>
|
||||
@ -251,12 +252,11 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700 text-center text-sm text-gray-600 dark:text-gray-400">
|
||||
Crystal - Manage multiple Claude Code instances with git worktrees
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
<div className="p-4 border-t border-border-primary text-center text-sm text-text-muted">
|
||||
Crystal - Manage multiple Claude Code instances with git worktrees
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -1,143 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
interface JsonMessage {
|
||||
type: string;
|
||||
subtype?: string;
|
||||
content?: string;
|
||||
data?: any;
|
||||
timestamp: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
interface JsonMessageItemProps {
|
||||
message: JsonMessage;
|
||||
index: number;
|
||||
}
|
||||
|
||||
function JsonMessageItem({ message }: JsonMessageItemProps) {
|
||||
const [isCollapsed, setIsCollapsed] = useState(true);
|
||||
|
||||
const getMessageTypeColor = (type: string, subtype?: string) => {
|
||||
if (type === 'system') {
|
||||
return subtype === 'init' ? 'bg-blue-900/20 border-blue-700' : 'bg-gray-800 border-gray-700';
|
||||
}
|
||||
if (type === 'user') return 'bg-green-900/20 border-green-700';
|
||||
if (type === 'assistant') return 'bg-purple-900/20 border-purple-700';
|
||||
return 'bg-gray-800 border-gray-700';
|
||||
};
|
||||
|
||||
const getMessageTypeIcon = (type: string, subtype?: string) => {
|
||||
if (type === 'system') {
|
||||
return subtype === 'init' ? '🚀' : '⚙️';
|
||||
}
|
||||
if (type === 'user') return '👤';
|
||||
if (type === 'assistant') return '🤖';
|
||||
return '📄';
|
||||
};
|
||||
|
||||
const formatTimestamp = (timestamp: string) => {
|
||||
return new Date(timestamp).toLocaleTimeString();
|
||||
};
|
||||
|
||||
const getMessageTitle = (message: JsonMessage) => {
|
||||
if (message.type === 'system' && message.subtype === 'init') {
|
||||
return 'Session Started';
|
||||
}
|
||||
if (message.type === 'system' && message.subtype === 'result') {
|
||||
return `Result (${message.cost_usd ? `$${message.cost_usd}` : 'No cost'})`;
|
||||
}
|
||||
if (message.type === 'user') {
|
||||
return 'User Input';
|
||||
}
|
||||
if (message.type === 'assistant') {
|
||||
return 'Assistant Response';
|
||||
}
|
||||
return `${message.type} ${message.subtype || ''}`.trim();
|
||||
};
|
||||
|
||||
const getMessagePreview = (message: JsonMessage) => {
|
||||
if (message.content) {
|
||||
return message.content.length > 100
|
||||
? message.content.substring(0, 100) + '...'
|
||||
: message.content;
|
||||
}
|
||||
if (message.type === 'system' && message.subtype === 'result') {
|
||||
return `Duration: ${message.duration_ms}ms, Turns: ${message.num_turns}`;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`border rounded-lg mb-2 ${getMessageTypeColor(message.type, message.subtype)}`}>
|
||||
<div
|
||||
className="p-3 cursor-pointer flex items-center justify-between hover:bg-opacity-80"
|
||||
onClick={() => setIsCollapsed(!isCollapsed)}
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<span className="text-lg">{getMessageTypeIcon(message.type, message.subtype)}</span>
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-200">{getMessageTitle(message)}</h4>
|
||||
{isCollapsed && (
|
||||
<p className="text-sm text-gray-400 mt-1">{getMessagePreview(message)}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-xs text-gray-400">{formatTimestamp(message.timestamp)}</span>
|
||||
<span className={`transform transition-transform ${isCollapsed ? 'rotate-0' : 'rotate-180'}`}>
|
||||
▼
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!isCollapsed && (
|
||||
<div className="border-t bg-gray-900/50 p-4">
|
||||
{message.content && (
|
||||
<div className="mb-4">
|
||||
<h5 className="font-medium text-gray-300 mb-2">Content:</h5>
|
||||
<div className="bg-gray-800 rounded p-3 text-sm font-mono whitespace-pre-wrap border border-gray-700 text-gray-200">
|
||||
{message.content}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<details>
|
||||
<summary className="cursor-pointer font-medium text-gray-300 mb-2">Raw JSON Data</summary>
|
||||
<pre className="bg-gray-800 rounded p-3 text-xs overflow-auto max-h-64 border border-gray-700 text-gray-200">
|
||||
{JSON.stringify(message, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface JsonMessageViewProps {
|
||||
messages: JsonMessage[];
|
||||
}
|
||||
|
||||
export function JsonMessageView({ messages }: JsonMessageViewProps) {
|
||||
if (messages.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-32 text-gray-400">
|
||||
No messages yet
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col bg-gray-900 overflow-hidden">
|
||||
<div className="flex-1 overflow-auto p-4">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<h3 className="text-lg font-semibold text-gray-200 mb-4">
|
||||
Claude Code Messages ({messages.length})
|
||||
</h3>
|
||||
{messages.map((message, index) => (
|
||||
<JsonMessageItem key={index} message={message} index={index} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
interface LoadingSpinnerProps {
|
||||
text?: string;
|
||||
@ -6,7 +7,7 @@ interface LoadingSpinnerProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function LoadingSpinner({ text = 'Loading...', size = 'medium', className = '' }: LoadingSpinnerProps) {
|
||||
export function LoadingSpinner({ text = 'Loading...', size = 'medium', className }: LoadingSpinnerProps) {
|
||||
const sizeClasses = {
|
||||
small: 'w-4 h-4',
|
||||
medium: 'w-6 h-6',
|
||||
@ -20,9 +21,9 @@ export function LoadingSpinner({ text = 'Loading...', size = 'medium', className
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`flex items-center justify-center gap-3 ${className}`}>
|
||||
<Loader2 className={`${sizeClasses[size]} animate-spin text-blue-500`} />
|
||||
<span className={`text-gray-600 dark:text-gray-400 ${textSizeClasses[size]}`}>{text}</span>
|
||||
<div className={cn('flex items-center justify-center gap-3', className)}>
|
||||
<Loader2 className={cn(sizeClasses[size], 'animate-spin text-interactive')} />
|
||||
<span className={cn('text-text-tertiary', textSizeClasses[size])}>{text}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,4 +1,6 @@
|
||||
import { Plus } from 'lucide-react';
|
||||
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { Button } from './ui/Button';
|
||||
|
||||
interface MainBranchWarningDialogProps {
|
||||
isOpen: boolean;
|
||||
@ -17,8 +19,6 @@ export function MainBranchWarningDialog({
|
||||
projectId,
|
||||
mainBranch
|
||||
}: MainBranchWarningDialogProps) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleDontShowAgain = () => {
|
||||
const warningKey = `mainBranchWarning_${projectId}`;
|
||||
localStorage.setItem(warningKey, 'true');
|
||||
@ -26,78 +26,70 @@ export function MainBranchWarningDialog({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 w-full max-w-lg relative shadow-xl border border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute top-4 right-4 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors"
|
||||
title="Close"
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="lg" showCloseButton={false}>
|
||||
<ModalHeader title={`Working in the ${mainBranch} branch`} onClose={onClose} />
|
||||
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
||||
Working in the {mainBranch} branch
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<ModalBody className="space-y-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="text-blue-600 dark:text-blue-400 text-2xl mt-1">💡</span>
|
||||
<span className="text-interactive text-2xl mt-1">💡</span>
|
||||
<div className="flex-1">
|
||||
<p className="text-gray-700 dark:text-gray-300 mb-3">
|
||||
You're about to create a session in the <span className="font-mono bg-gray-100 dark:bg-gray-700 px-1 rounded">{mainBranch}</span> branch
|
||||
<p className="text-text-secondary mb-3">
|
||||
You're about to create a session in the <span className="font-mono bg-surface-secondary px-1 rounded">{mainBranch}</span> branch
|
||||
of <span className="font-medium">{projectName}</span>.
|
||||
</p>
|
||||
<p className="text-gray-700 dark:text-gray-300 mb-3">
|
||||
<p className="text-text-secondary mb-3">
|
||||
For better workflow management, it's recommended to create worktrees instead. This allows you to:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 space-y-1 mb-4">
|
||||
<ul className="list-disc list-inside text-text-secondary space-y-1 mb-4">
|
||||
<li>Run multiple sessions in parallel without conflicts</li>
|
||||
<li>Keep your main branch clean</li>
|
||||
<li>Easily manage and compare different approaches</li>
|
||||
<li>Avoid creating more commits than intended in your main branch</li>
|
||||
</ul>
|
||||
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-md p-3 mb-3">
|
||||
<p className="text-sm text-amber-800 dark:text-amber-300">
|
||||
<div className="bg-status-warning/10 border border-status-warning/30 rounded-md p-3 mb-3">
|
||||
<p className="text-sm text-status-warning">
|
||||
<span className="font-medium">⚠️ Note:</span> Working directly in the {mainBranch} branch may result in
|
||||
multiple intermediate commits as Claude makes changes. Using worktrees allows you to squash
|
||||
these into a single clean commit before merging.
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-md p-3">
|
||||
<p className="text-sm text-blue-800 dark:text-blue-300">
|
||||
<div className="bg-interactive/10 border border-interactive/30 rounded-md p-3">
|
||||
<p className="text-sm text-interactive">
|
||||
<span className="font-medium">Tip:</span> Click the <Plus className="w-4 h-4 inline mx-1" /> button
|
||||
next to the project name to create a new worktree session.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
<div className="flex gap-3 mt-6">
|
||||
<button
|
||||
onClick={onContinue}
|
||||
className="flex-1 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 font-medium py-2 px-4 rounded-md transition-colors"
|
||||
<ModalFooter>
|
||||
<div className="w-full space-y-2">
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
onClick={onContinue}
|
||||
variant="secondary"
|
||||
fullWidth
|
||||
>
|
||||
Continue to {mainBranch} branch
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleDontShowAgain}
|
||||
variant="primary"
|
||||
fullWidth
|
||||
>
|
||||
Continue and don't ask again
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
onClick={onClose}
|
||||
variant="ghost"
|
||||
fullWidth
|
||||
>
|
||||
Continue to {mainBranch} branch
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDontShowAgain}
|
||||
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
|
||||
>
|
||||
Continue and don't ask again
|
||||
</button>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="w-full mt-2 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 text-sm py-2"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -1,9 +1,14 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
import { MermaidRenderer } from './MermaidRenderer';
|
||||
|
||||
interface CodeComponentProps extends React.HTMLAttributes<HTMLElement> {
|
||||
node?: unknown;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
interface MarkdownPreviewProps {
|
||||
content: string;
|
||||
className?: string;
|
||||
@ -11,8 +16,6 @@ interface MarkdownPreviewProps {
|
||||
}
|
||||
|
||||
export const MarkdownPreview: React.FC<MarkdownPreviewProps> = ({ content, className = '' }) => {
|
||||
const { theme } = useTheme();
|
||||
const isDarkMode = theme === 'dark';
|
||||
const [mermaidKey, setMermaidKey] = useState(0);
|
||||
|
||||
// Force re-render of mermaid diagrams when content changes
|
||||
@ -21,11 +24,11 @@ export const MarkdownPreview: React.FC<MarkdownPreviewProps> = ({ content, class
|
||||
}, [content]);
|
||||
|
||||
return (
|
||||
<div className={`markdown-preview ${isDarkMode ? 'markdown-dark' : 'markdown-light'} ${className}`}>
|
||||
<div className={`markdown-preview ${className}`}>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
components={{
|
||||
code({ node, className, children, ...props }: any) {
|
||||
code({ node, className, children, ...props }: CodeComponentProps) {
|
||||
const match = /language-(\w+)/.exec(className || '');
|
||||
const language = match ? match[1] : '';
|
||||
const codeString = String(children).replace(/\n$/, '');
|
||||
@ -50,42 +53,42 @@ export const MarkdownPreview: React.FC<MarkdownPreviewProps> = ({ content, class
|
||||
);
|
||||
},
|
||||
// Style other markdown elements
|
||||
h1: ({ children }) => <h1 className="text-3xl font-bold mt-6 mb-4">{children}</h1>,
|
||||
h2: ({ children }) => <h2 className="text-2xl font-bold mt-5 mb-3">{children}</h2>,
|
||||
h3: ({ children }) => <h3 className="text-xl font-bold mt-4 mb-2">{children}</h3>,
|
||||
h4: ({ children }) => <h4 className="text-lg font-bold mt-3 mb-2">{children}</h4>,
|
||||
p: ({ children }) => <p className="mb-4">{children}</p>,
|
||||
ul: ({ children }) => <ul className="list-disc list-inside mb-4 ml-4">{children}</ul>,
|
||||
ol: ({ children }) => <ol className="list-decimal list-inside mb-4 ml-4">{children}</ol>,
|
||||
li: ({ children }) => <li className="mb-1">{children}</li>,
|
||||
h1: ({ children }) => <h1 className="text-3xl font-bold mt-6 mb-4 text-text-primary">{children}</h1>,
|
||||
h2: ({ children }) => <h2 className="text-2xl font-bold mt-5 mb-3 text-text-primary">{children}</h2>,
|
||||
h3: ({ children }) => <h3 className="text-xl font-bold mt-4 mb-2 text-text-primary">{children}</h3>,
|
||||
h4: ({ children }) => <h4 className="text-lg font-bold mt-3 mb-2 text-text-primary">{children}</h4>,
|
||||
p: ({ children }) => <p className="mb-4 text-text-primary">{children}</p>,
|
||||
ul: ({ children }) => <ul className="list-disc mb-4 ml-6 text-text-primary">{children}</ul>,
|
||||
ol: ({ children }) => <ol className="list-decimal mb-4 ml-6 text-text-primary">{children}</ol>,
|
||||
li: ({ children }) => <li className="mb-2 text-text-primary">{children}</li>,
|
||||
blockquote: ({ children }) => (
|
||||
<blockquote className="border-l-4 border-gray-300 dark:border-gray-600 pl-4 italic my-4">
|
||||
<blockquote className="border-l-4 border-border-secondary pl-4 italic my-4 text-text-tertiary">
|
||||
{children}
|
||||
</blockquote>
|
||||
),
|
||||
table: ({ children }) => (
|
||||
<div className="overflow-x-auto mb-4">
|
||||
<table className="min-w-full border-collapse border border-gray-300 dark:border-gray-600">
|
||||
<table className="min-w-full border-collapse border border-border-primary">
|
||||
{children}
|
||||
</table>
|
||||
</div>
|
||||
),
|
||||
th: ({ children }) => (
|
||||
<th className="border border-gray-300 dark:border-gray-600 px-4 py-2 bg-gray-100 dark:bg-gray-800 font-semibold text-left">
|
||||
<th className="border border-border-primary px-4 py-2 bg-surface-secondary font-semibold text-left text-text-primary">
|
||||
{children}
|
||||
</th>
|
||||
),
|
||||
td: ({ children }) => (
|
||||
<td className="border border-gray-300 dark:border-gray-600 px-4 py-2">
|
||||
<td className="border border-border-primary px-4 py-2 text-text-primary">
|
||||
{children}
|
||||
</td>
|
||||
),
|
||||
a: ({ href, children }) => (
|
||||
<a href={href} className="text-blue-600 dark:text-blue-400 hover:underline" target="_blank" rel="noopener noreferrer">
|
||||
<a href={href} className="text-interactive-on-dark" target="_blank" rel="noopener noreferrer">
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
hr: () => <hr className="my-6 border-gray-300 dark:border-gray-600" />,
|
||||
hr: () => <hr className="my-6 border-border-primary" />,
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
|
||||
@ -15,12 +15,15 @@ export const MermaidRenderer: React.FC<MermaidRendererProps> = ({ chart, id }) =
|
||||
const renderChart = async () => {
|
||||
if (!elementRef.current || !chart) return;
|
||||
|
||||
// Create a unique ID for this render (define it outside try block)
|
||||
const graphId = `mermaid-${id}-${Date.now()}`;
|
||||
|
||||
try {
|
||||
// Clear any previous content
|
||||
elementRef.current.innerHTML = '';
|
||||
setHasError(false);
|
||||
|
||||
// Configure mermaid if needed
|
||||
// Configure mermaid
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
theme: document.documentElement.classList.contains('dark') ? 'dark' : 'default',
|
||||
@ -28,21 +31,36 @@ export const MermaidRenderer: React.FC<MermaidRendererProps> = ({ chart, id }) =
|
||||
fontFamily: 'monospace',
|
||||
});
|
||||
|
||||
// Create a unique ID for this render
|
||||
const graphId = `mermaid-${id}-${Date.now()}`;
|
||||
|
||||
// Render the chart
|
||||
const { svg } = await mermaid.render(graphId, chart);
|
||||
|
||||
|
||||
// Insert the SVG
|
||||
if (elementRef.current) {
|
||||
elementRef.current.innerHTML = svg;
|
||||
}
|
||||
} catch (error: any) {
|
||||
} catch (error: unknown) {
|
||||
console.error('Mermaid rendering error:', error);
|
||||
setHasError(true);
|
||||
setErrorMessage(error?.message || 'Failed to render diagram');
|
||||
|
||||
|
||||
// Extract meaningful error message
|
||||
let message = 'Failed to render diagram';
|
||||
if (error instanceof Error) {
|
||||
// Clean up the error message - remove version info and extra details
|
||||
message = error.message
|
||||
.replace(/mermaid version [\d.]+/gi, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
setErrorMessage(message);
|
||||
|
||||
// Clean up any error SVGs that mermaid may have inserted
|
||||
const errorElements = document.querySelectorAll(`#${graphId}, [id^="mermaid-"]`);
|
||||
errorElements.forEach(el => {
|
||||
if (el.parentNode) {
|
||||
el.parentNode.removeChild(el);
|
||||
}
|
||||
});
|
||||
|
||||
// Try to clean up mermaid's internal state
|
||||
try {
|
||||
// @ts-expect-error - Mermaid API types don't include reset method
|
||||
@ -63,9 +81,11 @@ export const MermaidRenderer: React.FC<MermaidRendererProps> = ({ chart, id }) =
|
||||
|
||||
if (hasError) {
|
||||
return (
|
||||
<div className="border border-red-300 dark:border-red-700 rounded p-4 bg-red-50 dark:bg-red-900/20">
|
||||
<p className="text-red-600 dark:text-red-400 font-semibold">Failed to render diagram</p>
|
||||
<pre className="text-xs text-red-500 dark:text-red-300 mt-2">{errorMessage}</pre>
|
||||
<div className="border border-status-error/30 rounded p-2 bg-status-error/5 text-sm">
|
||||
<p className="text-status-error">
|
||||
<span className="font-semibold">⚠ Diagram error:</span>{' '}
|
||||
<span className="text-status-error/90">{errorMessage}</span>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -51,7 +51,7 @@ export class MonacoErrorBoundary extends Component<MonacoErrorBoundaryProps, Mon
|
||||
// Show a brief loading state while auto-recovering
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full p-8">
|
||||
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
|
||||
<div className="flex items-center gap-2 text-text-tertiary">
|
||||
<RefreshCw className="w-5 h-5 animate-spin" />
|
||||
<span>Reloading editor...</span>
|
||||
</div>
|
||||
|
||||
112
frontend/src/components/NimbalystInstallDialog.tsx
Normal file
@ -0,0 +1,112 @@
|
||||
import { useEffect } from 'react';
|
||||
import { X, ExternalLink, Download } from 'lucide-react';
|
||||
import { NimbalystIcon } from './icons/NimbalystIcon';
|
||||
import { AnalyticsService } from '../services/analyticsService';
|
||||
|
||||
interface NimbalystInstallDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function NimbalystInstallDialog({ isOpen, onClose }: NimbalystInstallDialogProps) {
|
||||
// Handle keyboard events
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
onClose();
|
||||
} else if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
handleDownload();
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleDownload = async () => {
|
||||
// Track download button click
|
||||
await AnalyticsService.trackNimbalystDownloadClicked({});
|
||||
|
||||
window.electronAPI.invoke('openExternal', 'https://nimbalyst.com/');
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-gradient-to-br from-white to-gray-50 dark:from-gray-800 dark:to-gray-900 rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden border border-gray-200/50 dark:border-gray-700/50">
|
||||
{/* Header with gradient background */}
|
||||
<div className="relative bg-gradient-to-r from-blue-500 to-blue-600 dark:from-blue-600 dark:to-blue-700 p-6 pb-8">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute top-4 right-4 text-white/80 hover:text-white transition-colors p-1 rounded-lg hover:bg-white/10"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="flex-shrink-0 bg-white dark:bg-gray-800 p-3 rounded-xl shadow-lg">
|
||||
<NimbalystIcon size={40} />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-2xl font-bold text-white mb-1">
|
||||
Nimbalyst
|
||||
</h3>
|
||||
<p className="text-blue-100 dark:text-blue-200 text-sm font-medium">
|
||||
Integrated Markdown Environment
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-6 space-y-4">
|
||||
<div className="flex items-start space-x-3">
|
||||
<div className="flex-shrink-0 mt-1">
|
||||
<div className="w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
|
||||
<Download className="w-4 h-4 text-blue-600 dark:text-blue-400" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h4 className="text-base font-semibold text-gray-900 dark:text-white mb-2">
|
||||
Installation Required
|
||||
</h4>
|
||||
<p className="text-gray-600 dark:text-gray-300 text-sm leading-relaxed">
|
||||
Nimbalyst is not installed on your system. To open worktrees in Nimbalyst, please download and install it first.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800/30 rounded-lg p-4">
|
||||
<p className="text-gray-700 dark:text-gray-300 text-sm leading-relaxed">
|
||||
<span className="font-semibold text-blue-700 dark:text-blue-400">Nimbalyst</span> is an integrated markdown environment for Claude Code from the team that brought you Crystal.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer with actions */}
|
||||
<div className="bg-gray-50 dark:bg-gray-800/50 px-6 py-4 flex justify-end space-x-3 border-t border-gray-200/50 dark:border-gray-700/50">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-5 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 rounded-lg transition-all border border-gray-300 dark:border-gray-600 shadow-sm hover:shadow"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDownload}
|
||||
className="px-5 py-2.5 text-sm font-semibold text-white bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 rounded-lg transition-all flex items-center gap-2 shadow-lg shadow-blue-500/25 hover:shadow-xl hover:shadow-blue-500/40 hover:scale-[1.02]"
|
||||
autoFocus
|
||||
>
|
||||
Download Nimbalyst
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,4 +1,9 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Button } from './ui/Button';
|
||||
import { ToggleField } from './ui/Toggle';
|
||||
import { CollapsibleCard } from './ui/CollapsibleCard';
|
||||
import { SettingsSection } from './ui/SettingsSection';
|
||||
import { Bell, BellOff, Volume2, VolumeX, Zap, Shield } from 'lucide-react';
|
||||
|
||||
interface NotificationSettings {
|
||||
enabled: boolean;
|
||||
@ -43,142 +48,142 @@ export function NotificationSettings({ settings, onUpdateSettings }: Notificatio
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggle = (key: keyof NotificationSettings) => {
|
||||
onUpdateSettings({ [key]: !settings[key] });
|
||||
const getPermissionIcon = () => {
|
||||
switch (permissionStatus) {
|
||||
case 'granted': return <Bell className="w-4 h-4 text-status-success" />;
|
||||
case 'denied': return <BellOff className="w-4 h-4 text-status-error" />;
|
||||
default: return <Shield className="w-4 h-4 text-status-warning" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getPermissionStatus = () => {
|
||||
switch (permissionStatus) {
|
||||
case 'granted': return { text: 'Enabled', color: 'text-status-success' };
|
||||
case 'denied': return { text: 'Denied', color: 'text-status-error' };
|
||||
default: return { text: 'Not requested', color: 'text-status-warning' };
|
||||
}
|
||||
};
|
||||
|
||||
const status = getPermissionStatus();
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">Notification Settings</h3>
|
||||
|
||||
{/* Permission Status */}
|
||||
<div className="mb-6 p-4 border border-gray-300 dark:border-gray-700 rounded-lg">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-700 dark:text-gray-300">Browser Permissions</h4>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Status: {permissionStatus === 'granted' ? '✅ Enabled' :
|
||||
permissionStatus === 'denied' ? '❌ Denied' : '⚠️ Not requested'}
|
||||
{/* Browser Permissions */}
|
||||
<CollapsibleCard
|
||||
title="Browser Permissions"
|
||||
subtitle="Allow Crystal to show desktop notifications"
|
||||
icon={getPermissionIcon()}
|
||||
defaultExpanded={true}
|
||||
>
|
||||
<SettingsSection
|
||||
title="Notification Access"
|
||||
description="Crystal needs browser permission to show notifications when your sessions update"
|
||||
icon={getPermissionIcon()}
|
||||
>
|
||||
<div className="flex items-center justify-between p-4 bg-surface-secondary rounded-lg border border-border-secondary">
|
||||
<div className="flex items-center gap-3">
|
||||
{getPermissionIcon()}
|
||||
<div>
|
||||
<span className="text-sm font-medium text-text-primary">Permission Status</span>
|
||||
<p className={`text-sm ${status.color} font-medium`}>
|
||||
{status.text}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{permissionStatus !== 'granted' && (
|
||||
<Button
|
||||
onClick={requestPermission}
|
||||
size="sm"
|
||||
variant="primary"
|
||||
>
|
||||
Enable Notifications
|
||||
</Button>
|
||||
)}
|
||||
{permissionStatus === 'granted' && (
|
||||
<Button
|
||||
onClick={testNotification}
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
>
|
||||
Test Notification
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{permissionStatus === 'denied' && (
|
||||
<div className="mt-3 p-3 bg-status-error/10 border border-status-error/20 rounded-lg">
|
||||
<p className="text-xs text-status-error">
|
||||
Notifications are blocked. Please enable them in your browser settings and refresh Crystal.
|
||||
</p>
|
||||
</div>
|
||||
{permissionStatus !== 'granted' && (
|
||||
<button
|
||||
onClick={requestPermission}
|
||||
className="px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700"
|
||||
>
|
||||
Enable Notifications
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{permissionStatus === 'granted' && (
|
||||
<button
|
||||
onClick={testNotification}
|
||||
className="mt-2 px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700"
|
||||
>
|
||||
Test Notification
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</SettingsSection>
|
||||
</CollapsibleCard>
|
||||
|
||||
{/* Settings */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<label className="font-medium text-gray-700 dark:text-gray-300">Enable Notifications</label>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">Show browser notifications for session events</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleToggle('enabled')}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
|
||||
settings.enabled ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
settings.enabled ? 'translate-x-6' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
{/* Notification Preferences */}
|
||||
<CollapsibleCard
|
||||
title="Notification Preferences"
|
||||
subtitle="Customize when and how you receive notifications"
|
||||
icon={settings.enabled ? <Bell className="w-5 h-5" /> : <BellOff className="w-5 h-5" />}
|
||||
defaultExpanded={true}
|
||||
>
|
||||
<SettingsSection
|
||||
title="Master Control"
|
||||
description="Turn all notifications on or off"
|
||||
icon={settings.enabled ? <Bell className="w-4 h-4" /> : <BellOff className="w-4 h-4" />}
|
||||
>
|
||||
<ToggleField
|
||||
label="Enable Notifications"
|
||||
description="Show browser notifications for session events"
|
||||
checked={settings.enabled}
|
||||
onChange={(checked) => onUpdateSettings({ enabled: checked })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<label className="font-medium text-gray-700 dark:text-gray-300">Play Sound</label>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">Play a sound when notifications appear</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleToggle('playSound')}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
|
||||
settings.playSound ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
settings.playSound ? 'translate-x-6' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<SettingsSection
|
||||
title="Sound & Audio"
|
||||
description="Control notification sounds"
|
||||
icon={settings.playSound ? <Volume2 className="w-4 h-4" /> : <VolumeX className="w-4 h-4" />}
|
||||
>
|
||||
<ToggleField
|
||||
label="Play notification sounds"
|
||||
description="Play a subtle sound when notifications appear"
|
||||
checked={settings.playSound}
|
||||
onChange={(checked) => onUpdateSettings({ playSound: checked })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<label className="font-medium text-gray-700 dark:text-gray-300">Status Changes</label>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">Notify when session status changes</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleToggle('notifyOnStatusChange')}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
|
||||
settings.notifyOnStatusChange ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
settings.notifyOnStatusChange ? 'translate-x-6' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<SettingsSection
|
||||
title="Event Triggers"
|
||||
description="Choose which session events should trigger notifications"
|
||||
icon={<Zap className="w-4 h-4" />}
|
||||
spacing="sm"
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<ToggleField
|
||||
label="Status changes"
|
||||
description="When sessions start, stop, or change state"
|
||||
checked={settings.notifyOnStatusChange}
|
||||
onChange={(checked) => onUpdateSettings({ notifyOnStatusChange: checked })}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<label className="font-medium text-gray-700 dark:text-gray-300">Input Required</label>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">Notify when sessions are waiting for input</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleToggle('notifyOnWaiting')}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
|
||||
settings.notifyOnWaiting ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
settings.notifyOnWaiting ? 'translate-x-6' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<ToggleField
|
||||
label="Input required"
|
||||
description="When Claude is waiting for your response"
|
||||
checked={settings.notifyOnWaiting}
|
||||
onChange={(checked) => onUpdateSettings({ notifyOnWaiting: checked })}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<label className="font-medium text-gray-700 dark:text-gray-300">Session Complete</label>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">Notify when sessions finish successfully</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleToggle('notifyOnComplete')}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
|
||||
settings.notifyOnComplete ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
settings.notifyOnComplete ? 'translate-x-6' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
<ToggleField
|
||||
label="Task completion"
|
||||
description="When sessions finish successfully"
|
||||
checked={settings.notifyOnComplete}
|
||||
onChange={(checked) => onUpdateSettings({ notifyOnComplete: checked })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
</CollapsibleCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,17 +1,20 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Check, X, Shield, AlertTriangle, Code, Edit } from 'lucide-react';
|
||||
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { Button } from './ui/Button';
|
||||
import { Textarea } from './ui/Textarea';
|
||||
|
||||
interface PermissionRequest {
|
||||
id: string;
|
||||
sessionId: string;
|
||||
toolName: string;
|
||||
input: any;
|
||||
input: Record<string, unknown>;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
interface PermissionDialogProps {
|
||||
request: PermissionRequest | null;
|
||||
onRespond: (requestId: string, behavior: 'allow' | 'deny', updatedInput?: any, message?: string) => void;
|
||||
onRespond: (requestId: string, behavior: 'allow' | 'deny', updatedInput?: Record<string, unknown>, message?: string) => void;
|
||||
session?: { name: string };
|
||||
}
|
||||
|
||||
@ -83,15 +86,24 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
|
||||
const renderInputPreview = () => {
|
||||
const { input, toolName } = request;
|
||||
|
||||
// Helper to safely get string value
|
||||
const getStringValue = (obj: Record<string, unknown>, key: string): string | undefined => {
|
||||
const value = obj[key];
|
||||
return typeof value === 'string' ? value : undefined;
|
||||
};
|
||||
|
||||
if (toolName.includes('Bash')) {
|
||||
const command = getStringValue(input, 'command');
|
||||
const description = getStringValue(input, 'description');
|
||||
|
||||
return (
|
||||
<div className="bg-gray-100 dark:bg-gray-900 p-3 rounded font-mono text-sm border border-gray-200 dark:border-gray-700">
|
||||
<div className="text-gray-600 dark:text-gray-400 text-xs mb-1">Command:</div>
|
||||
<div className="text-gray-900 dark:text-white">{input.command || 'No command specified'}</div>
|
||||
{input.description && (
|
||||
<div className="bg-surface-secondary p-3 rounded font-mono text-sm border border-border-primary">
|
||||
<div className="text-text-tertiary text-xs mb-1">Command:</div>
|
||||
<div className="text-text-primary">{command || 'No command specified'}</div>
|
||||
{description && (
|
||||
<>
|
||||
<div className="text-gray-600 dark:text-gray-400 text-xs mt-2 mb-1">Description:</div>
|
||||
<div className="text-gray-700 dark:text-gray-300">{input.description}</div>
|
||||
<div className="text-text-tertiary text-xs mt-2 mb-1">Description:</div>
|
||||
<div className="text-text-secondary">{description}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@ -99,15 +111,18 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
|
||||
}
|
||||
|
||||
if (toolName.includes('Write') || toolName.includes('Edit')) {
|
||||
const filePath = getStringValue(input, 'file_path') || getStringValue(input, 'path');
|
||||
const content = getStringValue(input, 'content');
|
||||
|
||||
return (
|
||||
<div className="bg-gray-100 dark:bg-gray-900 p-3 rounded font-mono text-sm border border-gray-200 dark:border-gray-700">
|
||||
<div className="text-gray-600 dark:text-gray-400 text-xs mb-1">File Path:</div>
|
||||
<div className="text-gray-900 dark:text-white">{input.file_path || input.path || 'No path specified'}</div>
|
||||
{input.content && (
|
||||
<div className="bg-surface-secondary p-3 rounded font-mono text-sm border border-border-primary">
|
||||
<div className="text-text-tertiary text-xs mb-1">File Path:</div>
|
||||
<div className="text-text-primary">{filePath || 'No path specified'}</div>
|
||||
{content && (
|
||||
<>
|
||||
<div className="text-gray-600 dark:text-gray-400 text-xs mt-2 mb-1">Content Preview:</div>
|
||||
<div className="text-gray-700 dark:text-gray-300 max-h-32 overflow-y-auto whitespace-pre-wrap">
|
||||
{input.content.length > 500 ? input.content.substring(0, 500) + '...' : input.content}
|
||||
<div className="text-text-tertiary text-xs mt-2 mb-1">Content Preview:</div>
|
||||
<div className="text-text-secondary max-h-32 overflow-y-auto whitespace-pre-wrap">
|
||||
{content.length > 500 ? content.substring(0, 500) + '...' : content}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@ -117,45 +132,44 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
|
||||
|
||||
// Default JSON view
|
||||
return (
|
||||
<div className="bg-gray-900 p-3 rounded font-mono text-sm">
|
||||
<pre className="text-gray-900 dark:text-white overflow-x-auto">{JSON.stringify(input, null, 2)}</pre>
|
||||
<div className="bg-surface-secondary p-3 rounded font-mono text-sm border border-border-primary">
|
||||
<pre className="text-text-primary overflow-x-auto">{JSON.stringify(input, null, 2)}</pre>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden border border-gray-200 dark:border-gray-700">
|
||||
<div className="p-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center gap-3">
|
||||
<Shield className={`w-6 h-6 ${isHighRisk(request.toolName) ? 'text-red-400' : 'text-yellow-400'}`} />
|
||||
<div className="flex-1">
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">Permission Required</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
Claude wants to {getToolDescription(request.toolName)} in session: {session?.name || request.sessionId}
|
||||
</p>
|
||||
</div>
|
||||
<Modal isOpen={true} onClose={() => handleDeny()} size="lg" showCloseButton={false}>
|
||||
<ModalHeader onClose={() => handleDeny()}>
|
||||
<div className="flex items-center gap-3">
|
||||
<Shield className={`w-6 h-6 ${isHighRisk(request.toolName) ? 'text-status-error' : 'text-status-warning'}`} />
|
||||
<div className="flex-1">
|
||||
<h2 className="text-xl font-semibold text-text-primary">Permission Required</h2>
|
||||
<p className="text-sm text-text-secondary mt-1">
|
||||
Claude wants to {getToolDescription(request.toolName)} in session: {session?.name || request.sessionId}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</ModalHeader>
|
||||
|
||||
<div className="p-6 overflow-y-auto max-h-[60vh]">
|
||||
<div className="mb-4">
|
||||
<ModalBody className="space-y-6">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Code className="w-4 h-4 text-gray-400" />
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">Tool</h3>
|
||||
<Code className="w-4 h-4 text-text-tertiary" />
|
||||
<h3 className="text-sm font-medium text-text-secondary">Tool</h3>
|
||||
{isHighRisk(request.toolName) && (
|
||||
<span className="text-xs bg-red-500/20 text-red-400 px-2 py-0.5 rounded">High Risk</span>
|
||||
<span className="text-xs bg-status-error/20 text-status-error px-2 py-0.5 rounded">High Risk</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-gray-900 dark:text-white font-mono">{formatToolName(request.toolName)}</p>
|
||||
<p className="text-text-primary font-mono">{formatToolName(request.toolName)}</p>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">Input Parameters</h3>
|
||||
<h3 className="text-sm font-medium text-text-secondary">Input Parameters</h3>
|
||||
<button
|
||||
onClick={() => setEditMode(!editMode)}
|
||||
className="flex items-center gap-1 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
|
||||
className="flex items-center gap-1 text-xs text-interactive hover:text-interactive-hover transition-colors"
|
||||
>
|
||||
<Edit className="w-3 h-3" />
|
||||
{editMode ? 'Preview' : 'Edit'}
|
||||
@ -163,10 +177,10 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
|
||||
</div>
|
||||
|
||||
{editMode ? (
|
||||
<textarea
|
||||
<Textarea
|
||||
value={editedInput}
|
||||
onChange={(e) => setEditedInput(e.target.value)}
|
||||
className="w-full h-48 bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-white p-3 rounded font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 border border-gray-300 dark:border-gray-700"
|
||||
className="font-mono text-sm h-48"
|
||||
spellCheck={false}
|
||||
/>
|
||||
) : (
|
||||
@ -175,35 +189,34 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
|
||||
</div>
|
||||
|
||||
{isHighRisk(request.toolName) && (
|
||||
<div className="bg-red-100 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded p-3">
|
||||
<div className="flex items-center gap-2 text-red-400">
|
||||
<div className="bg-status-error/10 border border-status-error/30 rounded p-3">
|
||||
<div className="flex items-center gap-2 text-status-error">
|
||||
<AlertTriangle className="w-4 h-4" />
|
||||
<span className="text-sm font-medium">High Risk Action</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-600 dark:text-gray-400 mt-1">
|
||||
<p className="text-xs text-text-tertiary mt-1">
|
||||
This action could modify your system or files. Review carefully before approving.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
<div className="p-6 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
|
||||
<button
|
||||
onClick={handleDeny}
|
||||
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white rounded hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors flex items-center gap-2"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
Deny
|
||||
</button>
|
||||
<button
|
||||
onClick={handleAllow}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-500 transition-colors flex items-center gap-2"
|
||||
>
|
||||
<Check className="w-4 h-4" />
|
||||
Allow
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ModalFooter>
|
||||
<Button
|
||||
onClick={handleDeny}
|
||||
variant="secondary"
|
||||
icon={<X className="w-4 h-4" />}
|
||||
>
|
||||
Deny
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAllow}
|
||||
variant="primary"
|
||||
icon={<Check className="w-4 h-4" />}
|
||||
>
|
||||
Allow
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
|
||||
import { RefreshCw, GitBranch, AlertCircle, CheckCircle, GitPullRequest, Loader2, XCircle, Filter } from 'lucide-react';
|
||||
import { API } from '../utils/api';
|
||||
import type { ProjectDashboardData, SessionBranchInfo } from '../types/projectDashboard';
|
||||
@ -10,6 +10,8 @@ import { useSessionStore } from '../stores/sessionStore';
|
||||
import { useNavigationStore } from '../stores/navigationStore';
|
||||
import { MultiOriginStatus } from './dashboard/MultiOriginStatus';
|
||||
import { StatusSummaryCards } from './dashboard/StatusSummaryCards';
|
||||
import { Card } from './ui/Card';
|
||||
import { Button } from './ui/Button';
|
||||
|
||||
interface ProjectDashboardProps {
|
||||
projectId: number;
|
||||
@ -23,8 +25,40 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [lastRefreshTime, setLastRefreshTime] = useState<Date | null>(null);
|
||||
const [filterType, setFilterType] = useState<'all' | 'stale' | 'changes' | 'pr'>('all');
|
||||
const [isProgressive] = useState(true); // Use progressive loading by default
|
||||
const pendingSessionUpdatesRef = useRef<Map<string, SessionBranchInfo>>(new Map());
|
||||
|
||||
const fetchDashboardData = useCallback(async (useCache: boolean = true) => {
|
||||
// Debounced function to apply pending session updates
|
||||
const applyPendingSessionUpdates = useMemo(
|
||||
() => debounce(() => {
|
||||
const updates = Array.from(pendingSessionUpdatesRef.current.values());
|
||||
if (updates.length === 0) return;
|
||||
|
||||
setDashboardData(prevData => {
|
||||
if (!prevData) return null;
|
||||
|
||||
const sessionMap = new Map(
|
||||
prevData.sessionBranches.map(s => [s.sessionId, s])
|
||||
);
|
||||
|
||||
// Apply all pending updates
|
||||
updates.forEach(update => {
|
||||
sessionMap.set(update.sessionId, update);
|
||||
});
|
||||
|
||||
// Clear pending updates
|
||||
pendingSessionUpdatesRef.current.clear();
|
||||
|
||||
return {
|
||||
...prevData,
|
||||
sessionBranches: Array.from(sessionMap.values())
|
||||
};
|
||||
});
|
||||
}, 100), // 100ms debounce for smooth updates
|
||||
[]
|
||||
);
|
||||
|
||||
const fetchDashboardData = useCallback(async (useCache: boolean = true, useProgressive: boolean = true) => {
|
||||
// Check cache first if not forcing refresh
|
||||
if (useCache) {
|
||||
const cachedData = dashboardCache.get(projectId);
|
||||
@ -40,15 +74,30 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await API.dashboard.getProjectStatus(projectId);
|
||||
|
||||
if (response.success && response.data) {
|
||||
setDashboardData(response.data);
|
||||
setLastRefreshTime(new Date());
|
||||
// Cache the data
|
||||
dashboardCache.set(projectId, response.data);
|
||||
if (useProgressive && isProgressive) {
|
||||
// Use progressive loading
|
||||
const response = await API.dashboard.getProjectStatusProgressive(projectId);
|
||||
|
||||
if (response.success && response.data) {
|
||||
setDashboardData(response.data);
|
||||
setLastRefreshTime(new Date());
|
||||
// Cache the data
|
||||
dashboardCache.set(projectId, response.data);
|
||||
} else {
|
||||
setError(response.error || 'Failed to fetch project status');
|
||||
}
|
||||
} else {
|
||||
setError(response.error || 'Failed to fetch project status');
|
||||
// Use traditional loading
|
||||
const response = await API.dashboard.getProjectStatus(projectId);
|
||||
|
||||
if (response.success && response.data) {
|
||||
setDashboardData(response.data);
|
||||
setLastRefreshTime(new Date());
|
||||
// Cache the data
|
||||
dashboardCache.set(projectId, response.data);
|
||||
} else {
|
||||
setError(response.error || 'Failed to fetch project status');
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error occurred');
|
||||
@ -56,17 +105,72 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
setIsLoading(false);
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
}, [projectId, dashboardData]);
|
||||
}, [projectId, dashboardData, isProgressive]);
|
||||
|
||||
// Debounced refresh function
|
||||
const debouncedRefresh = useMemo(
|
||||
() => debounce(() => {
|
||||
dashboardCache.invalidate(projectId);
|
||||
fetchDashboardData(false);
|
||||
fetchDashboardData(false, true);
|
||||
}, 500),
|
||||
[projectId, fetchDashboardData]
|
||||
);
|
||||
|
||||
// Set up progressive loading event listeners
|
||||
useEffect(() => {
|
||||
if (!isProgressive) return;
|
||||
|
||||
const cleanupFns: Array<() => void> = [];
|
||||
|
||||
// Handle dashboard updates
|
||||
const unsubscribeUpdate = API.dashboard.onUpdate((event) => {
|
||||
if (event.projectId === projectId) {
|
||||
setDashboardData(prevData => {
|
||||
if (!prevData && event.data) {
|
||||
// Initial data
|
||||
return event.data as ProjectDashboardData;
|
||||
} else if (prevData && event.data && event.isPartial) {
|
||||
// Merge partial update
|
||||
return { ...prevData, ...event.data };
|
||||
} else if (event.data) {
|
||||
// Full update
|
||||
const data = event.data as ProjectDashboardData;
|
||||
if (data.projectId && data.projectName && data.sessionBranches) {
|
||||
dashboardCache.set(projectId, data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
return prevData;
|
||||
});
|
||||
|
||||
if (!event.isPartial) {
|
||||
setIsLoading(false);
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
cleanupFns.push(unsubscribeUpdate);
|
||||
|
||||
// Handle individual session updates with debouncing
|
||||
const unsubscribeSession = API.dashboard.onSessionUpdate((event) => {
|
||||
if (event.projectId === projectId && event.data && event.sessionId) {
|
||||
// Cast to SessionBranchInfo since we know this is the expected shape from dashboard updates
|
||||
const sessionData = event.data as SessionBranchInfo;
|
||||
// Add to pending updates
|
||||
pendingSessionUpdatesRef.current.set(event.sessionId, sessionData);
|
||||
// Trigger debounced update
|
||||
applyPendingSessionUpdates();
|
||||
}
|
||||
});
|
||||
cleanupFns.push(unsubscribeSession);
|
||||
|
||||
return () => {
|
||||
cleanupFns.forEach(fn => fn());
|
||||
// Cancel any pending updates
|
||||
applyPendingSessionUpdates.cancel();
|
||||
};
|
||||
}, [projectId, isProgressive, applyPendingSessionUpdates]);
|
||||
|
||||
useEffect(() => {
|
||||
// Clear previous data when switching projects to show skeleton
|
||||
setDashboardData(null);
|
||||
@ -91,7 +195,7 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
// }, [dashboardData?.sessionBranches]);
|
||||
|
||||
const renderSessionRow = useCallback((session: SessionBranchInfo) => {
|
||||
const staleClass = session.isStale ? 'bg-yellow-50 dark:bg-yellow-900/20' : '';
|
||||
const staleClass = session.isStale ? 'bg-status-warning/10' : '';
|
||||
|
||||
const handleSessionClick = async () => {
|
||||
console.log('[ProjectDashboard] Session clicked:', session.sessionId, session.sessionName);
|
||||
@ -106,52 +210,52 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
};
|
||||
|
||||
return (
|
||||
<tr key={session.sessionId} className={`hover:bg-gray-50 dark:hover:bg-gray-800 ${staleClass} cursor-pointer`} onClick={handleSessionClick}>
|
||||
<tr key={session.sessionId} className={`hover:bg-surface-hover ${staleClass} cursor-pointer`} onClick={handleSessionClick}>
|
||||
<td className="px-4 py-3 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="w-4 h-4 text-gray-400" />
|
||||
<GitBranch className="w-4 h-4 text-text-tertiary" />
|
||||
<div>
|
||||
<div className="font-medium text-gray-900 dark:text-gray-100">{session.sessionName}</div>
|
||||
<div className="text-gray-500 dark:text-gray-400 text-xs">{session.branchName}</div>
|
||||
<div className="font-medium text-text-primary">{session.sessionName}</div>
|
||||
<div className="text-text-tertiary text-xs">{session.branchName}</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">
|
||||
<code className="text-xs bg-gray-100 dark:bg-gray-800 px-1 py-0.5 rounded">
|
||||
<td className="px-4 py-3 text-sm text-text-secondary">
|
||||
<code className="text-xs bg-surface-secondary px-1 py-0.5 rounded">
|
||||
{session.baseBranch}
|
||||
</code>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm">
|
||||
{session.isStale ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-yellow-600" />
|
||||
<span className="text-yellow-700 dark:text-yellow-400">
|
||||
<AlertCircle className="w-4 h-4 text-status-warning" />
|
||||
<span className="text-status-warning">
|
||||
Stale {session.staleSince && `since ${formatDistanceToNow(session.staleSince)}`}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-green-500" />
|
||||
<span className="text-green-700 dark:text-green-400">Current</span>
|
||||
<CheckCircle className="w-4 h-4 text-status-success" />
|
||||
<span className="text-status-success">Current</span>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">
|
||||
<td className="px-4 py-3 text-sm text-text-secondary">
|
||||
<div className="flex gap-3 text-xs">
|
||||
{session.commitsAhead > 0 && (
|
||||
<span className="text-blue-600 dark:text-blue-400">+{session.commitsAhead}</span>
|
||||
<span className="text-interactive">+{session.commitsAhead}</span>
|
||||
)}
|
||||
{session.commitsBehind > 0 && (
|
||||
<span className="text-orange-600 dark:text-orange-400">-{session.commitsBehind}</span>
|
||||
<span className="text-status-warning">-{session.commitsBehind}</span>
|
||||
)}
|
||||
{session.commitsAhead === 0 && session.commitsBehind === 0 && (
|
||||
<span className="text-gray-400">—</span>
|
||||
<span className="text-text-tertiary">—</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm">
|
||||
{session.hasUncommittedChanges && (
|
||||
<span className="inline-flex items-center gap-1 text-amber-600 dark:text-amber-400">
|
||||
<span className="inline-flex items-center gap-1 text-status-warning">
|
||||
<AlertCircle className="w-3 h-3" />
|
||||
<span className="text-xs">Uncommitted</span>
|
||||
</span>
|
||||
@ -163,23 +267,23 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
href={session.pullRequest.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-blue-600 hover:text-blue-800 dark:text-blue-400"
|
||||
className="inline-flex items-center gap-1 text-interactive hover:text-interactive-hover"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<GitPullRequest className="w-4 h-4" />
|
||||
<span>#{session.pullRequest.number}</span>
|
||||
{session.pullRequest.state === 'open' && (
|
||||
<span className="inline-block w-2 h-2 bg-green-500 rounded-full"></span>
|
||||
<span className="inline-block w-2 h-2 bg-status-success rounded-full"></span>
|
||||
)}
|
||||
{session.pullRequest.state === 'closed' && (
|
||||
<XCircle className="w-3 h-3 text-red-500" />
|
||||
<XCircle className="w-3 h-3 text-status-error" />
|
||||
)}
|
||||
{session.pullRequest.state === 'merged' && (
|
||||
<CheckCircle className="w-3 h-3 text-purple-500" />
|
||||
<CheckCircle className="w-3 h-3 text-interactive" />
|
||||
)}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-gray-400">—</span>
|
||||
<span className="text-text-tertiary">—</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
@ -204,15 +308,15 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="p-6 bg-red-50 dark:bg-red-900/20 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-red-700 dark:text-red-400">
|
||||
<div className="p-6 bg-status-error/10 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-status-error">
|
||||
<AlertCircle className="w-5 h-5" />
|
||||
<span className="font-medium">Error loading dashboard</span>
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-red-600 dark:text-red-300">{error}</p>
|
||||
<p className="mt-1 text-sm text-status-error/80">{error}</p>
|
||||
<button
|
||||
onClick={() => fetchDashboardData(false)}
|
||||
className="mt-3 px-3 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700"
|
||||
className="mt-3 px-3 py-1 text-sm bg-status-error text-white rounded hover:bg-status-error-hover"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
@ -225,37 +329,32 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 flex flex-col h-full">
|
||||
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||
<Card className="flex flex-col h-full">
|
||||
<div className="px-6 py-4 border-b border-border-primary">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
<h2 className="text-lg font-semibold text-text-primary">
|
||||
Project Dashboard
|
||||
</h2>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
<p className="text-sm text-text-secondary">
|
||||
Git status for {dashboardData?.projectName || projectName}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
{lastRefreshTime && (
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">
|
||||
<span className="text-xs text-text-tertiary">
|
||||
Updated {formatDistanceToNow(lastRefreshTime)}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
<Button
|
||||
onClick={debouncedRefresh}
|
||||
disabled={isLoading || isRefreshing}
|
||||
className="inline-flex items-center gap-2 px-3 py-1.5 text-sm bg-gray-100 dark:bg-gray-800
|
||||
text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-200 dark:hover:bg-gray-700
|
||||
disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
icon={(isLoading || isRefreshing) ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
|
||||
>
|
||||
{(isLoading || isRefreshing) ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
)}
|
||||
Refresh
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -263,12 +362,14 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
{dashboardData ? (
|
||||
<div className="p-6 flex-1 flex flex-col overflow-hidden">
|
||||
{/* Multi-Origin Status */}
|
||||
<MultiOriginStatus
|
||||
mainBranch={dashboardData.mainBranch}
|
||||
mainBranchStatus={dashboardData.mainBranchStatus}
|
||||
remotes={dashboardData.remotes}
|
||||
onReviewUpdates={() => console.log('Review updates clicked')}
|
||||
/>
|
||||
{dashboardData.mainBranchStatus && (
|
||||
<MultiOriginStatus
|
||||
mainBranch={dashboardData.mainBranch}
|
||||
mainBranchStatus={dashboardData.mainBranchStatus}
|
||||
remotes={dashboardData.remotes}
|
||||
onReviewUpdates={() => console.log('Review updates clicked')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Status Summary Cards */}
|
||||
<StatusSummaryCards sessions={dashboardData.sessionBranches} />
|
||||
@ -277,15 +378,15 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
{dashboardData.sessionBranches.length > 0 ? (
|
||||
<div className="flex-1 flex flex-col overflow-hidden">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<h3 className="text-sm font-medium text-text-primary">
|
||||
Session Branches ({filteredSessions.length} of {dashboardData.sessionBranches.length})
|
||||
</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<Filter className="w-4 h-4 text-gray-400" />
|
||||
<Filter className="w-4 h-4 text-text-tertiary" />
|
||||
<select
|
||||
value={filterType}
|
||||
onChange={(e) => setFilterType(e.target.value as typeof filterType)}
|
||||
className="text-sm border border-gray-300 dark:border-gray-600 rounded px-2 py-1 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300"
|
||||
className="text-sm border border-border-primary rounded px-2 py-1 bg-surface-primary text-text-primary focus:outline-none focus:ring-2 focus:ring-interactive focus:border-interactive"
|
||||
>
|
||||
<option value="all">All Sessions</option>
|
||||
<option value="stale">Stale Only</option>
|
||||
@ -294,44 +395,44 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 overflow-x-auto overflow-y-auto border border-gray-200 dark:border-gray-700 rounded-lg">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800">
|
||||
<div className="flex-1 overflow-x-auto overflow-y-auto border border-border-primary rounded-lg">
|
||||
<table className="min-w-full divide-y divide-border-primary">
|
||||
<thead className="bg-surface-secondary">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
|
||||
Session
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
|
||||
Base Branch
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
|
||||
Status
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
|
||||
Commits
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
|
||||
Changes
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
|
||||
Pull Request
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<tbody className="bg-bg-primary divide-y divide-border-primary">
|
||||
{filteredSessions.map(renderSessionRow)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
|
||||
<GitBranch className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
|
||||
<div className="text-center py-8 text-text-tertiary">
|
||||
<GitBranch className="w-12 h-12 mx-auto mb-3 text-text-tertiary/50" />
|
||||
<p>No active session branches</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
});
|
||||
@ -1,31 +1,32 @@
|
||||
import React from 'react';
|
||||
import { Card } from './ui/Card';
|
||||
|
||||
export const ProjectDashboardSkeleton: React.FC = () => {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 animate-pulse">
|
||||
<Card className="animate-pulse">
|
||||
{/* Header Skeleton */}
|
||||
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="px-6 py-4 border-b border-border-primary">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="h-6 w-48 bg-gray-200 dark:bg-gray-700 rounded mb-2"></div>
|
||||
<div className="h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-6 w-48 bg-surface-tertiary rounded mb-2"></div>
|
||||
<div className="h-4 w-32 bg-surface-tertiary rounded"></div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-8 w-20 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-4 w-24 bg-surface-tertiary rounded"></div>
|
||||
<div className="h-8 w-20 bg-surface-tertiary rounded"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-6">
|
||||
{/* Main Branch Status Skeleton */}
|
||||
<div className="mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<div className="mb-6 p-4 bg-surface-secondary rounded-lg">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-5 h-5 bg-gray-300 dark:bg-gray-600 rounded"></div>
|
||||
<div className="w-5 h-5 bg-border-primary rounded"></div>
|
||||
<div>
|
||||
<div className="h-5 w-36 bg-gray-200 dark:bg-gray-700 rounded mb-2"></div>
|
||||
<div className="h-4 w-48 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-5 w-36 bg-surface-tertiary rounded mb-2"></div>
|
||||
<div className="h-4 w-48 bg-surface-tertiary rounded"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -33,47 +34,47 @@ export const ProjectDashboardSkeleton: React.FC = () => {
|
||||
|
||||
{/* Table Header Skeleton */}
|
||||
<div className="mb-3">
|
||||
<div className="h-4 w-40 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-4 w-40 bg-surface-tertiary rounded"></div>
|
||||
</div>
|
||||
|
||||
{/* Table Skeleton */}
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800">
|
||||
<table className="min-w-full divide-y divide-border-primary">
|
||||
<thead className="bg-surface-secondary">
|
||||
<tr>
|
||||
{[1, 2, 3, 4, 5, 6].map((i) => (
|
||||
<th key={i} className="px-4 py-3">
|
||||
<div className="h-3 w-16 bg-gray-300 dark:bg-gray-600 rounded"></div>
|
||||
<div className="h-3 w-16 bg-border-primary rounded"></div>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<tbody className="bg-surface-primary divide-y divide-border-primary">
|
||||
{[1, 2, 3].map((row) => (
|
||||
<tr key={row}>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-4 h-4 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="w-4 h-4 bg-surface-tertiary rounded"></div>
|
||||
<div>
|
||||
<div className="h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded mb-1"></div>
|
||||
<div className="h-3 w-24 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-4 w-32 bg-surface-tertiary rounded mb-1"></div>
|
||||
<div className="h-3 w-24 bg-surface-tertiary rounded"></div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="h-4 w-16 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-4 w-16 bg-surface-tertiary rounded"></div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="h-4 w-20 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-4 w-20 bg-surface-tertiary rounded"></div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="h-4 w-12 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-4 w-12 bg-surface-tertiary rounded"></div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-4 w-24 bg-surface-tertiary rounded"></div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="h-4 w-16 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-4 w-16 bg-surface-tertiary rounded"></div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@ -81,6 +82,6 @@ export const ProjectDashboardSkeleton: React.FC = () => {
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
@ -1,9 +1,15 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ChevronDown, Plus, Check, Settings } from 'lucide-react';
|
||||
import { API } from '../utils/api';
|
||||
import type { Project } from '../types/project';
|
||||
import type { Project, CreateProjectRequest } from '../types/project';
|
||||
import ProjectSettings from './ProjectSettings';
|
||||
import { useErrorStore } from '../stores/errorStore';
|
||||
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { Button, IconButton } from './ui/Button';
|
||||
import { EnhancedInput } from './ui/EnhancedInput';
|
||||
import { FieldWithTooltip } from './ui/FieldWithTooltip';
|
||||
import { Card } from './ui/Card';
|
||||
import { Folder, GitBranch, Hammer, Play } from 'lucide-react';
|
||||
|
||||
interface ProjectSelectorProps {
|
||||
onProjectChange?: (project: Project) => void;
|
||||
@ -14,7 +20,8 @@ export default function ProjectSelector({ onProjectChange }: ProjectSelectorProp
|
||||
const [activeProject, setActiveProject] = useState<Project | null>(null);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [showAddDialog, setShowAddDialog] = useState(false);
|
||||
const [newProject, setNewProject] = useState({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
const [newProject, setNewProject] = useState<CreateProjectRequest>({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
const [showValidationErrors, setShowValidationErrors] = useState(false);
|
||||
const [detectedBranch, setDetectedBranch] = useState<string | null>(null);
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
const [settingsProject, setSettingsProject] = useState<Project | null>(null);
|
||||
@ -83,7 +90,7 @@ export default function ProjectSelector({ onProjectChange }: ProjectSelectorProp
|
||||
if (!newProject.name || !newProject.path) return;
|
||||
|
||||
try {
|
||||
const response = await API.projects.create(newProject);
|
||||
const response = await API.projects.create({ ...newProject, active: false });
|
||||
|
||||
if (!response.success) {
|
||||
showError({
|
||||
@ -108,12 +115,14 @@ export default function ProjectSelector({ onProjectChange }: ProjectSelectorProp
|
||||
} else {
|
||||
fetchProjects();
|
||||
}
|
||||
} catch (error: any) {
|
||||
} catch (error: unknown) {
|
||||
console.error('Failed to create project:', error);
|
||||
const errorMessage = error instanceof Error ? error.message : 'An error occurred while creating the project.';
|
||||
const errorDetails = error instanceof Error ? error.stack : String(error);
|
||||
showError({
|
||||
title: 'Failed to Create Project',
|
||||
error: error.message || 'An error occurred while creating the project.',
|
||||
details: error.stack || error.toString()
|
||||
error: errorMessage,
|
||||
details: errorDetails || ''
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -144,210 +153,259 @@ export default function ProjectSelector({ onProjectChange }: ProjectSelectorProp
|
||||
<>
|
||||
<div className="relative">
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
<Button
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="flex-1 flex items-center space-x-2 px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded-md text-sm transition-colors"
|
||||
variant="secondary"
|
||||
size="md"
|
||||
className="flex-1 justify-between"
|
||||
>
|
||||
<span className="text-gray-300">
|
||||
<span>
|
||||
{activeProject ? activeProject.name : 'Select Project'}
|
||||
</span>
|
||||
<ChevronDown className={`w-4 h-4 text-gray-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
<ChevronDown className={`w-4 h-4 ml-2 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
|
||||
</Button>
|
||||
{activeProject && (
|
||||
<button
|
||||
<IconButton
|
||||
onClick={() => handleSettingsClick(activeProject)}
|
||||
className="p-2 bg-gray-800 hover:bg-gray-700 rounded-md transition-colors"
|
||||
title="Project Settings"
|
||||
>
|
||||
<Settings className="w-4 h-4 text-gray-400" />
|
||||
</button>
|
||||
aria-label="Project Settings"
|
||||
size="md"
|
||||
icon={<Settings className="w-4 h-4" />}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isOpen && (
|
||||
<div className="absolute top-full left-0 mt-1 w-64 bg-gray-800 rounded-md shadow-lg border border-gray-700 z-50">
|
||||
<div className="p-2">
|
||||
<Card
|
||||
variant="elevated"
|
||||
className="absolute top-full left-0 mt-1 w-64 z-50"
|
||||
padding="none"
|
||||
>
|
||||
<div className="p-1">
|
||||
{projects.map(project => (
|
||||
<div
|
||||
key={project.id}
|
||||
className="flex items-center hover:bg-gray-700 rounded group"
|
||||
className="flex items-center hover:bg-bg-hover rounded-md group"
|
||||
>
|
||||
<button
|
||||
onClick={() => handleSelectProject(project)}
|
||||
className="flex-1 text-left px-3 py-2 flex items-center justify-between"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-gray-200">{project.name}</div>
|
||||
<div className="text-xs text-gray-500 truncate">{project.path}</div>
|
||||
<div className="text-sm font-medium text-text-primary">{project.name}</div>
|
||||
<div className="text-xs text-text-tertiary truncate">{project.path}</div>
|
||||
</div>
|
||||
{project.active && (
|
||||
<Check className="w-4 h-4 text-green-500 ml-2 flex-shrink-0" />
|
||||
<Check className="w-4 h-4 text-status-success ml-2 flex-shrink-0" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
<IconButton
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleSettingsClick(project);
|
||||
}}
|
||||
className="p-2 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
title="Project Settings"
|
||||
>
|
||||
<Settings className="w-4 h-4 text-gray-400 hover:text-gray-200" />
|
||||
</button>
|
||||
size="sm"
|
||||
className="opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
aria-label="Project Settings"
|
||||
icon={<Settings className="w-4 h-4" />}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div className="border-t border-gray-700 mt-2 pt-2">
|
||||
<button
|
||||
<div className="border-t border-border-primary mt-2 pt-2">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setIsOpen(false);
|
||||
setShowAddDialog(true);
|
||||
}}
|
||||
className="w-full text-left px-3 py-2 rounded hover:bg-gray-700 flex items-center space-x-2 text-sm"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full justify-start"
|
||||
>
|
||||
<Plus className="w-4 h-4 text-gray-400" />
|
||||
<span className="text-gray-300">Add Project</span>
|
||||
</button>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Add Project
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Add Project Dialog */}
|
||||
{showAddDialog && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-gray-800 rounded-lg p-6 w-96 relative">
|
||||
<button
|
||||
onClick={() => {
|
||||
setShowAddDialog(false);
|
||||
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
setDetectedBranch(null);
|
||||
}}
|
||||
className="absolute top-4 right-4 text-gray-400 hover:text-gray-200 transition-colors"
|
||||
title="Close"
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<h3 className="text-lg font-semibold text-gray-200 mb-4 pr-8">Add New Project</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-1">
|
||||
Project Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newProject.name}
|
||||
onChange={(e) => setNewProject({ ...newProject, name: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200 focus:outline-none focus:border-blue-500"
|
||||
placeholder="My Project"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-1">
|
||||
Repository Path
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
<Modal
|
||||
isOpen={showAddDialog}
|
||||
onClose={() => {
|
||||
setShowAddDialog(false);
|
||||
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
setDetectedBranch(null);
|
||||
setShowValidationErrors(false);
|
||||
}}
|
||||
size="lg"
|
||||
>
|
||||
<ModalHeader title="Add New Project" icon={<Plus className="w-5 h-5" />} />
|
||||
<ModalBody>
|
||||
<div className="space-y-8">
|
||||
{/* Project Info Section */}
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2 pb-2 border-b border-border-primary">
|
||||
<Folder className="w-5 h-5 text-interactive" />
|
||||
<h3 className="text-heading-3 font-semibold text-text-primary">Project Information</h3>
|
||||
</div>
|
||||
|
||||
<FieldWithTooltip
|
||||
label="Project Name"
|
||||
tooltip="A descriptive name for your project that will appear in the project selector."
|
||||
required
|
||||
>
|
||||
<EnhancedInput
|
||||
type="text"
|
||||
value={newProject.path}
|
||||
value={newProject.name}
|
||||
onChange={(e) => {
|
||||
setNewProject({ ...newProject, path: e.target.value });
|
||||
detectCurrentBranch(e.target.value);
|
||||
setNewProject({ ...newProject, name: e.target.value });
|
||||
if (showValidationErrors) setShowValidationErrors(false);
|
||||
}}
|
||||
className="flex-1 px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200 focus:outline-none focus:border-blue-500"
|
||||
placeholder="/path/to/repository"
|
||||
placeholder="Enter project name"
|
||||
size="lg"
|
||||
fullWidth
|
||||
required
|
||||
showRequiredIndicator={showValidationErrors}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
const result = await API.dialog.openDirectory({
|
||||
title: 'Select Repository Directory',
|
||||
buttonLabel: 'Select',
|
||||
});
|
||||
if (result.success && result.data) {
|
||||
setNewProject({ ...newProject, path: result.data });
|
||||
detectCurrentBranch(result.data);
|
||||
}
|
||||
}}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-300 bg-gray-700 border border-gray-600 rounded-md hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
Browse
|
||||
</button>
|
||||
</FieldWithTooltip>
|
||||
|
||||
<FieldWithTooltip
|
||||
label="Repository Path"
|
||||
tooltip="Path to your git repository. This is where Crystal will create worktrees for parallel development."
|
||||
required
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<EnhancedInput
|
||||
type="text"
|
||||
value={newProject.path}
|
||||
onChange={(e) => {
|
||||
setNewProject({ ...newProject, path: e.target.value });
|
||||
detectCurrentBranch(e.target.value);
|
||||
if (showValidationErrors) setShowValidationErrors(false);
|
||||
}}
|
||||
placeholder="/path/to/your/repository"
|
||||
size="lg"
|
||||
fullWidth
|
||||
required
|
||||
showRequiredIndicator={showValidationErrors}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
const result = await API.dialog.openDirectory({
|
||||
title: 'Select Repository Directory',
|
||||
buttonLabel: 'Select',
|
||||
});
|
||||
if (result.success && result.data) {
|
||||
setNewProject({ ...newProject, path: result.data });
|
||||
detectCurrentBranch(result.data);
|
||||
}
|
||||
}}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</FieldWithTooltip>
|
||||
</div>
|
||||
|
||||
{/* Git Info Section */}
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2 pb-2 border-b border-border-primary">
|
||||
<GitBranch className="w-5 h-5 text-interactive" />
|
||||
<h3 className="text-heading-3 font-semibold text-text-primary">Git Information</h3>
|
||||
</div>
|
||||
|
||||
<FieldWithTooltip
|
||||
label="Main Branch"
|
||||
tooltip="The main branch of your repository. Crystal will automatically detect this from your git configuration."
|
||||
>
|
||||
<Card variant="bordered" padding="md" className="text-text-secondary bg-surface-secondary">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="w-4 h-4" />
|
||||
<span className="font-mono">
|
||||
{detectedBranch || (newProject.path ? 'Detecting...' : 'Select a repository path first')}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
</FieldWithTooltip>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-1">
|
||||
Current Branch <span className="text-gray-500">(Auto-detected)</span>
|
||||
</label>
|
||||
<div className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200">
|
||||
{detectedBranch || (newProject.path ? 'Detecting...' : 'Select a repository path first')}
|
||||
{/* Optional Scripts Section */}
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2 pb-2 border-b border-border-primary">
|
||||
<Play className="w-5 h-5 text-interactive" />
|
||||
<h3 className="text-heading-3 font-semibold text-text-primary">Optional Scripts</h3>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
The main branch is automatically detected from the repository. This will be used for git operations.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<FieldWithTooltip
|
||||
label="Build Script"
|
||||
tooltip="Command to build your project. This runs automatically before each Claude Code session starts."
|
||||
>
|
||||
<EnhancedInput
|
||||
type="text"
|
||||
value={newProject.buildScript}
|
||||
onChange={(e) => setNewProject({ ...newProject, buildScript: e.target.value })}
|
||||
placeholder="pnpm build"
|
||||
size="lg"
|
||||
fullWidth
|
||||
icon={<Hammer className="w-4 h-4" />}
|
||||
/>
|
||||
</FieldWithTooltip>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-1">
|
||||
Build Script <span className="text-gray-500">(optional)</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newProject.buildScript}
|
||||
onChange={(e) => setNewProject({ ...newProject, buildScript: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200 focus:outline-none focus:border-blue-500"
|
||||
placeholder="e.g., pnpm build or npm run build"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
This script will run automatically before each Claude Code session starts.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-1">
|
||||
Run Script <span className="text-gray-500">(optional)</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newProject.runScript}
|
||||
onChange={(e) => setNewProject({ ...newProject, runScript: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200 focus:outline-none focus:border-blue-500"
|
||||
placeholder="e.g., pnpm dev or npm start"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
This script can be run manually from the Terminal view during sessions.
|
||||
</p>
|
||||
<FieldWithTooltip
|
||||
label="Run Script"
|
||||
tooltip="Command to start your development server. You can run this manually from the Terminal view during sessions."
|
||||
>
|
||||
<EnhancedInput
|
||||
type="text"
|
||||
value={newProject.runScript}
|
||||
onChange={(e) => setNewProject({ ...newProject, runScript: e.target.value })}
|
||||
placeholder="pnpm dev"
|
||||
size="lg"
|
||||
fullWidth
|
||||
icon={<Play className="w-4 h-4" />}
|
||||
/>
|
||||
</FieldWithTooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex justify-end space-x-3">
|
||||
<button
|
||||
onClick={() => {
|
||||
setShowAddDialog(false);
|
||||
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
setDetectedBranch(null);
|
||||
}}
|
||||
className="px-4 py-2 text-gray-300 hover:text-gray-100 transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCreateProject}
|
||||
disabled={!newProject.name || !newProject.path}
|
||||
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Add Project
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setShowAddDialog(false);
|
||||
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
setDetectedBranch(null);
|
||||
setShowValidationErrors(false);
|
||||
}}
|
||||
variant="ghost"
|
||||
size="md"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!newProject.name || !newProject.path) {
|
||||
setShowValidationErrors(true);
|
||||
return;
|
||||
}
|
||||
handleCreateProject();
|
||||
}}
|
||||
disabled={!newProject.name || !newProject.path}
|
||||
variant="primary"
|
||||
size="md"
|
||||
className={(!newProject.name || !newProject.path) ? 'border-status-error border-2' : ''}
|
||||
>
|
||||
Create Project
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
|
||||
{/* Project Settings Dialog */}
|
||||
{settingsProject && (
|
||||
|
||||
@ -1,7 +1,13 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { X, Save, Trash2 } from 'lucide-react';
|
||||
import { Save, Trash2, FolderIcon, GitBranch, Settings, Code2, BrainCircuit } from 'lucide-react';
|
||||
import { API } from '../utils/api';
|
||||
import type { Project } from '../types/project';
|
||||
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { Input, Textarea } from './ui/Input';
|
||||
import { Button } from './ui/Button';
|
||||
import { EnhancedInput } from './ui/EnhancedInput';
|
||||
import { FieldWithTooltip } from './ui/FieldWithTooltip';
|
||||
import { Card } from './ui/Card';
|
||||
|
||||
interface ProjectSettingsProps {
|
||||
project: Project;
|
||||
@ -50,7 +56,7 @@ export default function ProjectSettings({ project, isOpen, onClose, onUpdate, on
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await API.projects.update(project.id.toString(), {
|
||||
const updates: Partial<Project> = {
|
||||
name,
|
||||
path,
|
||||
system_prompt: systemPrompt || null,
|
||||
@ -58,7 +64,9 @@ export default function ProjectSettings({ project, isOpen, onClose, onUpdate, on
|
||||
build_script: buildScript || null,
|
||||
open_ide_command: openIdeCommand || null,
|
||||
worktree_folder: worktreeFolder || null
|
||||
});
|
||||
};
|
||||
|
||||
const response = await API.projects.update(project.id.toString(), updates);
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(response.error || 'Failed to update project');
|
||||
@ -89,273 +97,340 @@ export default function ProjectSettings({ project, isOpen, onClose, onUpdate, on
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col 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">
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-200">Project Settings</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors"
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="xl">
|
||||
<ModalHeader
|
||||
title="Project Settings"
|
||||
icon={<Settings className="w-5 h-5" />}
|
||||
onClose={onClose}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={isSaving || !name || !path}
|
||||
variant="primary"
|
||||
size="sm"
|
||||
icon={<Save className="w-4 h-4" />}
|
||||
loading={isSaving}
|
||||
loadingText="Saving..."
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
Save Changes
|
||||
</Button>
|
||||
</div>
|
||||
</ModalHeader>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
{error && (
|
||||
<div className="mb-4 p-3 bg-red-100 dark:bg-red-900 dark:bg-opacity-50 border border-red-300 dark:border-red-700 rounded-md text-red-700 dark:text-red-200">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<ModalBody>
|
||||
{error && (
|
||||
<div className="mb-6 p-4 bg-status-error/10 border border-status-error/30 rounded-lg text-status-error">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-8">
|
||||
{/* Project Overview */}
|
||||
<div className="space-y-6">
|
||||
{/* Basic Information */}
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4">Basic Information</h3>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Project Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500"
|
||||
placeholder="My Project"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 pb-3 border-b border-border-primary">
|
||||
<FolderIcon className="w-5 h-5 text-interactive" />
|
||||
<div>
|
||||
<h3 className="text-heading-3 font-semibold text-text-primary">Project Overview</h3>
|
||||
<p className="text-sm text-text-tertiary">Basic project information and repository details</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FieldWithTooltip
|
||||
label="Project Name"
|
||||
tooltip="Display name for this project in Crystal's interface."
|
||||
>
|
||||
<EnhancedInput
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="My Project"
|
||||
size="lg"
|
||||
fullWidth
|
||||
/>
|
||||
</FieldWithTooltip>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Repository Path
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={path}
|
||||
onChange={(e) => setPath(e.target.value)}
|
||||
className="flex-1 px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500"
|
||||
placeholder="/path/to/repository"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
const result = await API.dialog.openDirectory({
|
||||
title: 'Select Repository Directory',
|
||||
buttonLabel: 'Select',
|
||||
});
|
||||
if (result.success && result.data) {
|
||||
setPath(result.data);
|
||||
}
|
||||
}}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
Browse
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
|
||||
The local path to the git repository for this project
|
||||
</p>
|
||||
<FieldWithTooltip
|
||||
label="Repository Path"
|
||||
tooltip="Local path to the git repository where Crystal will manage worktrees."
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<EnhancedInput
|
||||
type="text"
|
||||
value={path}
|
||||
onChange={(e) => setPath(e.target.value)}
|
||||
placeholder="/path/to/your/repository"
|
||||
size="lg"
|
||||
fullWidth
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
const result = await API.dialog.openDirectory({
|
||||
title: 'Select Repository Directory',
|
||||
buttonLabel: 'Select',
|
||||
});
|
||||
if (result.success && result.data) {
|
||||
setPath(result.data);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</FieldWithTooltip>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Current Branch (Auto-detected)
|
||||
</label>
|
||||
<div className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200">
|
||||
<FieldWithTooltip
|
||||
label="Current Branch"
|
||||
tooltip="The currently checked out branch in your repository. This is auto-detected."
|
||||
>
|
||||
<Card variant="bordered" padding="md" className="bg-surface-secondary">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="w-4 h-4 text-text-tertiary" />
|
||||
<span className="font-mono text-text-primary">
|
||||
{currentBranch || 'Detecting...'}
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
|
||||
This is the currently checked out branch in the project directory
|
||||
</p>
|
||||
</span>
|
||||
<span className="ml-auto px-2 py-1 text-xs bg-surface-tertiary text-text-tertiary rounded">
|
||||
Auto-detected
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
</FieldWithTooltip>
|
||||
</div>
|
||||
|
||||
{/* Worktree Configuration */}
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2 pb-3 border-b border-border-primary">
|
||||
<GitBranch className="w-5 h-5 text-interactive" />
|
||||
<div>
|
||||
<h3 className="text-heading-3 font-semibold text-text-primary">Worktree Configuration</h3>
|
||||
<p className="text-sm text-text-tertiary">Settings for git worktree creation and management</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Worktree Folder
|
||||
</label>
|
||||
<FieldWithTooltip
|
||||
label="Worktree Folder"
|
||||
tooltip="Directory where git worktrees will be created. Can be relative to the project or an absolute path."
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<EnhancedInput
|
||||
type="text"
|
||||
value={worktreeFolder}
|
||||
onChange={(e) => setWorktreeFolder(e.target.value)}
|
||||
placeholder="worktrees"
|
||||
size="lg"
|
||||
fullWidth
|
||||
/>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={worktreeFolder}
|
||||
onChange={(e) => setWorktreeFolder(e.target.value)}
|
||||
className="flex-1 px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500"
|
||||
placeholder="worktrees (default)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
const result = await API.dialog.openDirectory({
|
||||
title: 'Select Worktree Directory',
|
||||
buttonLabel: 'Select',
|
||||
});
|
||||
if (result.success && result.data) {
|
||||
setWorktreeFolder(result.data);
|
||||
}
|
||||
}}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
Browse
|
||||
</button>
|
||||
<span className="px-2 py-1 text-xs bg-surface-tertiary text-text-tertiary rounded">
|
||||
Default: worktrees/
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
|
||||
The folder where git worktrees will be created. Can be a relative path (e.g., "worktrees") or an absolute path.
|
||||
Leave empty to use the default "worktrees" folder inside the project directory.
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
const result = await API.dialog.openDirectory({
|
||||
title: 'Select Worktree Directory',
|
||||
buttonLabel: 'Select',
|
||||
});
|
||||
if (result.success && result.data) {
|
||||
setWorktreeFolder(result.data);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</FieldWithTooltip>
|
||||
</div>
|
||||
|
||||
{/* Session Behavior */}
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2 pb-3 border-b border-border-primary">
|
||||
<Code2 className="w-5 h-5 text-interactive" />
|
||||
<div>
|
||||
<h3 className="text-heading-3 font-semibold text-text-primary">Session Behavior</h3>
|
||||
<p className="text-sm text-text-tertiary">Commands and scripts that run during Claude sessions</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Project-Specific Settings */}
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4">Project-Specific Settings</h3>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Project System Prompt
|
||||
</label>
|
||||
<textarea
|
||||
value={systemPrompt}
|
||||
onChange={(e) => setSystemPrompt(e.target.value)}
|
||||
rows={6}
|
||||
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 font-mono text-sm"
|
||||
placeholder="Enter project-specific instructions for Claude..."
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
|
||||
This prompt will be appended to the global system prompt for all sessions in this project
|
||||
</p>
|
||||
</div>
|
||||
<FieldWithTooltip
|
||||
label="Open IDE Command"
|
||||
tooltip="Command to open the worktree in your IDE. The command will be executed in the worktree directory."
|
||||
>
|
||||
<Input
|
||||
value={openIdeCommand}
|
||||
onChange={(e) => setOpenIdeCommand(e.target.value)}
|
||||
placeholder='code .'
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-text-tertiary">
|
||||
<span className="text-text-secondary font-semibold">Common Examples:</span>
|
||||
<br />
|
||||
<span className="font-mono text-text-secondary">• code . </span><span className="text-text-tertiary">(VS Code)</span>
|
||||
<br />
|
||||
<span className="font-mono text-text-secondary">• cursor . </span><span className="text-text-tertiary">(Cursor)</span>
|
||||
<br />
|
||||
<span className="font-mono text-text-secondary">• subl . </span><span className="text-text-tertiary">(Sublime Text)</span>
|
||||
<br />
|
||||
<span className="font-mono text-text-secondary">• idea . </span><span className="text-text-tertiary">(IntelliJ IDEA)</span>
|
||||
<br />
|
||||
<span className="font-mono text-text-secondary">• open -a "PyCharm" . </span><span className="text-text-tertiary">(PyCharm on macOS)</span>
|
||||
<br />
|
||||
<br />
|
||||
<span className="text-text-secondary font-semibold">Troubleshooting:</span>
|
||||
<br />
|
||||
<span className="text-text-tertiary">• If the command is not found, use the full path (e.g., </span><span className="font-mono text-text-secondary">/usr/local/bin/code .</span><span className="text-text-tertiary">)</span>
|
||||
<br />
|
||||
<span className="text-text-tertiary">• For VS Code and Cursor, install the shell command from the Command Palette:</span>
|
||||
<br />
|
||||
<span className="text-text-tertiary ml-2">→ VS Code: "Shell Command: Install 'code' command in PATH"</span>
|
||||
<br />
|
||||
<span className="text-text-tertiary ml-2">→ Cursor: "Shell Command: Install 'cursor' command in PATH"</span>
|
||||
<br />
|
||||
<span className="text-text-tertiary">• The command runs with your shell's environment, inheriting your PATH</span>
|
||||
</p>
|
||||
</FieldWithTooltip>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Build Script
|
||||
</label>
|
||||
<textarea
|
||||
value={buildScript}
|
||||
onChange={(e) => setBuildScript(e.target.value)}
|
||||
rows={3}
|
||||
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 font-mono text-sm"
|
||||
placeholder="npm install npm run build"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
|
||||
Commands to run once when creating a new worktree (e.g., install dependencies, build assets).
|
||||
One command per line. These run in the worktree directory before Claude starts.
|
||||
</p>
|
||||
</div>
|
||||
<FieldWithTooltip
|
||||
label="Build Script"
|
||||
tooltip="Commands that run once when creating a new worktree. Use for setup tasks like installing dependencies."
|
||||
>
|
||||
<Card variant="bordered" padding="sm" className="bg-surface-secondary/50">
|
||||
<Textarea
|
||||
value={buildScript}
|
||||
onChange={(e) => setBuildScript(e.target.value)}
|
||||
rows={4}
|
||||
placeholder="npm install"
|
||||
className="font-mono text-sm bg-transparent border-0 p-3 focus:ring-0 resize-none"
|
||||
fullWidth
|
||||
/>
|
||||
</Card>
|
||||
</FieldWithTooltip>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Run Commands
|
||||
</label>
|
||||
<textarea
|
||||
value={runScript}
|
||||
onChange={(e) => setRunScript(e.target.value)}
|
||||
rows={4}
|
||||
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 font-mono text-sm"
|
||||
placeholder="npm run dev npm test --watch"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
|
||||
Commands to run continuously while Claude is working (e.g., dev server, test watcher).
|
||||
One command per line. Commands run sequentially - each must complete successfully before the next starts.
|
||||
All commands are automatically stopped when the session ends. Output appears in the Terminal tab.
|
||||
<br />
|
||||
<span className="text-gray-700 dark:text-gray-600">Tip: To run multiple servers together, use a process manager like concurrently:</span>
|
||||
<br />
|
||||
<span className="font-mono text-gray-700 dark:text-gray-600">• npx concurrently "npm:server" "npm:client"</span>
|
||||
<br />
|
||||
<span className="font-mono text-gray-700 dark:text-gray-600">• npm run dev (if your package.json uses concurrently)</span>
|
||||
</p>
|
||||
</div>
|
||||
<FieldWithTooltip
|
||||
label="Run Commands"
|
||||
tooltip="Commands that run continuously during sessions. Perfect for development servers and test watchers."
|
||||
>
|
||||
<Card variant="bordered" padding="sm" className="bg-surface-secondary/50">
|
||||
<Textarea
|
||||
value={runScript}
|
||||
onChange={(e) => setRunScript(e.target.value)}
|
||||
rows={4}
|
||||
placeholder="npm run dev"
|
||||
className="font-mono text-sm bg-transparent border-0 p-3 focus:ring-0 resize-none"
|
||||
fullWidth
|
||||
/>
|
||||
</Card>
|
||||
</FieldWithTooltip>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Open IDE Command
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={openIdeCommand}
|
||||
onChange={(e) => setOpenIdeCommand(e.target.value)}
|
||||
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 font-mono text-sm"
|
||||
placeholder='open -na "PyCharm.app" --args "`pwd`"'
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
|
||||
Command to open the worktree in your IDE. Use `pwd` to reference the worktree directory.
|
||||
<br />
|
||||
<span className="text-gray-700 dark:text-gray-600">Examples:</span>
|
||||
<br />
|
||||
<span className="font-mono text-gray-700 dark:text-gray-600">• code . (VS Code)</span>
|
||||
<br />
|
||||
<span className="font-mono text-gray-700 dark:text-gray-600">• cursor . (Cursor)</span>
|
||||
<br />
|
||||
<span className="text-gray-700 dark:text-gray-600 italic">Note: You may need to install the shell command separately for VS Code and Cursor</span>
|
||||
<br />
|
||||
<span className="font-mono text-gray-700 dark:text-gray-600">• open -na "PyCharm.app" --args "`pwd`" (PyCharm on macOS)</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* AI Prompt Customization */}
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2 pb-3 border-b border-border-primary">
|
||||
<BrainCircuit className="w-5 h-5 text-interactive" />
|
||||
<div>
|
||||
<h3 className="text-heading-3 font-semibold text-text-primary">AI Prompt Customization</h3>
|
||||
<p className="text-sm text-text-tertiary">Project-specific instructions that enhance Claude's understanding</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Danger Zone */}
|
||||
<div className="border-t border-gray-200 dark:border-gray-700 pt-6">
|
||||
<h3 className="text-lg font-medium text-red-600 dark:text-red-400 mb-4">Danger Zone</h3>
|
||||
<FieldWithTooltip
|
||||
label="Project System Prompt"
|
||||
tooltip="Custom instructions that will be added to every Claude session for this project. Use this to provide context about your codebase, coding standards, or preferred approaches."
|
||||
>
|
||||
<Card variant="bordered" padding="sm" className="bg-surface-secondary/50">
|
||||
<Textarea
|
||||
value={systemPrompt}
|
||||
onChange={(e) => setSystemPrompt(e.target.value)}
|
||||
rows={6}
|
||||
placeholder="This project uses TypeScript and follows strict ESLint rules..."
|
||||
className="font-mono text-sm bg-transparent border-0 p-3 focus:ring-0 resize-none"
|
||||
fullWidth
|
||||
/>
|
||||
</Card>
|
||||
</FieldWithTooltip>
|
||||
</div>
|
||||
|
||||
{/* Danger Zone */}
|
||||
<div className="border-t border-status-error/20 pt-6">
|
||||
<div className="flex items-center gap-2 pb-3 border-b border-status-error/20">
|
||||
<Trash2 className="w-5 h-5 text-status-error" />
|
||||
<div>
|
||||
<h3 className="text-heading-3 font-semibold text-status-error">Danger Zone</h3>
|
||||
<p className="text-sm text-text-tertiary">Irreversible actions for this project</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
{!showDeleteConfirm ? (
|
||||
<button
|
||||
<Button
|
||||
onClick={() => setShowDeleteConfirm(true)}
|
||||
className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md transition-colors flex items-center space-x-2"
|
||||
variant="danger"
|
||||
icon={<Trash2 className="w-4 h-4" />}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
<span>Delete Project</span>
|
||||
</button>
|
||||
Delete Project
|
||||
</Button>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-gray-700 dark:text-gray-300">
|
||||
Are you sure you want to delete this project? This action cannot be undone.
|
||||
</p>
|
||||
<div className="flex space-x-3">
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md transition-colors"
|
||||
>
|
||||
Yes, Delete Project
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowDeleteConfirm(false)}
|
||||
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-md transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<Card variant="bordered" padding="md" className="bg-status-error/5 border-status-error/20">
|
||||
<p className="text-sm text-text-secondary mb-3">
|
||||
Are you sure you want to delete this project? This action cannot be undone and will remove all project data from Crystal.
|
||||
</p>
|
||||
<div className="flex space-x-3">
|
||||
<Button
|
||||
onClick={handleDelete}
|
||||
variant="danger"
|
||||
size="sm"
|
||||
>
|
||||
Yes, Delete Project
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setShowDeleteConfirm(false)}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex justify-end space-x-3 p-6 border-t border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={isSaving || !name || !path}
|
||||
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center space-x-2"
|
||||
>
|
||||
<Save className="w-4 h-4" />
|
||||
<span>{isSaving ? 'Saving...' : 'Save Changes'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ModalFooter>
|
||||
<Button
|
||||
onClick={onClose}
|
||||
variant="ghost"
|
||||
size="md"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={isSaving || !name || !path}
|
||||
variant="primary"
|
||||
size="md"
|
||||
icon={<Save className="w-4 h-4" />}
|
||||
loading={isSaving}
|
||||
loadingText="Saving..."
|
||||
>
|
||||
Save Changes
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -10,7 +10,7 @@ import { EmptyState } from './EmptyState';
|
||||
import { LoadingSpinner } from './LoadingSpinner';
|
||||
import { API } from '../utils/api';
|
||||
import type { Session } from '../types/session';
|
||||
import type { Project } from '../types/project';
|
||||
import type { Project, CreateProjectRequest } from '../types/project';
|
||||
|
||||
interface ProjectWithSessions extends Project {
|
||||
sessions: Session[];
|
||||
@ -26,7 +26,7 @@ export function ProjectTreeView() {
|
||||
const [showProjectSettings, setShowProjectSettings] = useState(false);
|
||||
const [selectedProjectForSettings, setSelectedProjectForSettings] = useState<Project | null>(null);
|
||||
const [showAddProjectDialog, setShowAddProjectDialog] = useState(false);
|
||||
const [newProject, setNewProject] = useState({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
const [newProject, setNewProject] = useState<CreateProjectRequest>({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
const [hasPendingUpdates, setHasPendingUpdates] = useState(false);
|
||||
const activeSessionId = useSessionStore((state) => state.activeSessionId);
|
||||
const [showMainBranchWarning, setShowMainBranchWarning] = useState(false);
|
||||
@ -251,11 +251,11 @@ export function ProjectTreeView() {
|
||||
error: response.error || 'Unknown error occurred'
|
||||
});
|
||||
}
|
||||
} catch (error: any) {
|
||||
} catch (error: unknown) {
|
||||
console.error('Error handling project click:', error);
|
||||
showError({
|
||||
title: 'Failed to open main repository session',
|
||||
error: error.message || 'Unknown error occurred'
|
||||
error: error instanceof Error ? error.message : 'Unknown error occurred'
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -284,7 +284,7 @@ export function ProjectTreeView() {
|
||||
if (!newProject.name || !newProject.path) return;
|
||||
|
||||
try {
|
||||
const response = await API.projects.create(newProject);
|
||||
const response = await API.projects.create({ ...newProject, active: false });
|
||||
|
||||
if (!response.success) {
|
||||
showError({
|
||||
@ -301,12 +301,12 @@ export function ProjectTreeView() {
|
||||
|
||||
// Just reload the projects list
|
||||
loadProjectsWithSessions();
|
||||
} catch (error: any) {
|
||||
} catch (error: unknown) {
|
||||
console.error('Failed to create project:', error);
|
||||
showError({
|
||||
title: 'Failed to Create Project',
|
||||
error: error.message || 'An error occurred while creating the project.',
|
||||
details: error.stack || error.toString()
|
||||
error: error instanceof Error ? error.message : 'An error occurred while creating the project.',
|
||||
details: error instanceof Error && error.stack ? error.stack : String(error)
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -342,21 +342,21 @@ export function ProjectTreeView() {
|
||||
return (
|
||||
<div key={project.id}>
|
||||
<div
|
||||
className="group flex items-center space-x-1 px-2 py-1.5 rounded cursor-pointer transition-colors hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||
className="group flex items-center space-x-1 px-2 py-1.5 rounded cursor-pointer transition-colors hover:bg-surface-hover"
|
||||
>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
toggleProject(project.id);
|
||||
}}
|
||||
className="p-0.5 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
|
||||
className="p-0.5 hover:bg-surface-hover rounded transition-colors"
|
||||
disabled={sessionCount === 0}
|
||||
>
|
||||
{sessionCount > 0 ? (
|
||||
isExpanded ? (
|
||||
<ChevronDown className="w-3 h-3 text-gray-600 dark:text-gray-400" />
|
||||
<ChevronDown className="w-3 h-3 text-text-tertiary" />
|
||||
) : (
|
||||
<ChevronRight className="w-3 h-3 text-gray-600 dark:text-gray-400" />
|
||||
<ChevronRight className="w-3 h-3 text-text-tertiary" />
|
||||
)
|
||||
) : (
|
||||
<div className="w-3 h-3" />
|
||||
@ -368,11 +368,11 @@ export function ProjectTreeView() {
|
||||
onClick={() => handleProjectClick(project)}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<FolderOpen className="w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0" />
|
||||
<FolderOpen className="w-4 h-4 text-interactive flex-shrink-0" />
|
||||
) : (
|
||||
<Folder className="w-4 h-4 text-gray-600 dark:text-gray-400 flex-shrink-0" />
|
||||
<Folder className="w-4 h-4 text-text-tertiary flex-shrink-0" />
|
||||
)}
|
||||
<span className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate text-left">
|
||||
<span className="text-sm font-medium text-text-primary truncate text-left">
|
||||
{project.name}
|
||||
</span>
|
||||
</div>
|
||||
@ -382,14 +382,14 @@ export function ProjectTreeView() {
|
||||
e.stopPropagation();
|
||||
handleCreateSession(project);
|
||||
}}
|
||||
className={`relative p-1 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors group/tooltip ${
|
||||
className={`relative p-1 hover:bg-surface-hover rounded transition-colors group/tooltip ${
|
||||
sessionCount === 0 ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
>
|
||||
<Plus className="w-4 h-4 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200" />
|
||||
<span className="absolute left-1/2 -translate-x-1/2 bottom-full mb-2 px-2 py-1 text-xs text-white bg-gray-800 dark:bg-gray-700 rounded whitespace-nowrap opacity-0 invisible group-hover/tooltip:opacity-100 group-hover/tooltip:visible transition-all duration-200 pointer-events-none z-50">
|
||||
<Plus className="w-4 h-4 text-text-tertiary hover:text-text-primary" />
|
||||
<span className="absolute left-1/2 -translate-x-1/2 bottom-full mb-2 px-2 py-1 text-xs text-white bg-surface-tertiary rounded whitespace-nowrap opacity-0 invisible group-hover/tooltip:opacity-100 group-hover/tooltip:visible transition-all duration-200 pointer-events-none z-50">
|
||||
Create new session
|
||||
<span className="absolute left-1/2 -translate-x-1/2 top-full w-0 h-0 border-4 border-transparent border-t-gray-800 dark:border-t-gray-700"></span>
|
||||
<span className="absolute left-1/2 -translate-x-1/2 top-full w-0 h-0 border-4 border-transparent border-t-surface-tertiary"></span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@ -399,10 +399,10 @@ export function ProjectTreeView() {
|
||||
setSelectedProjectForSettings(project);
|
||||
setShowProjectSettings(true);
|
||||
}}
|
||||
className="p-1 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors opacity-0 group-hover:opacity-100"
|
||||
className="p-1 hover:bg-surface-hover rounded transition-colors opacity-0 group-hover:opacity-100"
|
||||
title="Project settings"
|
||||
>
|
||||
<Settings className="w-3 h-3 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200" />
|
||||
<Settings className="w-3 h-3 text-text-tertiary hover:text-text-primary" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@ -423,7 +423,7 @@ export function ProjectTreeView() {
|
||||
|
||||
<button
|
||||
onClick={() => setShowAddProjectDialog(true)}
|
||||
className="w-full mt-2 px-2 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors flex items-center justify-center space-x-2"
|
||||
className="w-full mt-2 px-2 py-1.5 text-sm text-text-secondary hover:text-text-primary hover:bg-surface-hover rounded transition-colors flex items-center justify-center space-x-2"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
<span>New Project</span>
|
||||
@ -469,26 +469,26 @@ export function ProjectTreeView() {
|
||||
|
||||
{/* Add Project Dialog */}
|
||||
{showAddProjectDialog && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 w-96 shadow-xl border border-gray-200 dark:border-gray-700">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-200 mb-4">Add New Project</h3>
|
||||
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-50">
|
||||
<div className="bg-surface-primary rounded-lg p-6 w-96 shadow-xl border border-border-primary">
|
||||
<h3 className="text-lg font-semibold text-text-primary mb-4">Add New Project</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Project Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newProject.name}
|
||||
onChange={(e) => setNewProject({ ...newProject, name: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 placeholder-gray-500 dark:placeholder-gray-400"
|
||||
className="w-full px-3 py-2 bg-surface-secondary border border-border-primary rounded-md text-text-primary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive placeholder-text-tertiary"
|
||||
placeholder="My Project"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Repository Path
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
@ -499,7 +499,7 @@ export function ProjectTreeView() {
|
||||
setNewProject({ ...newProject, path: e.target.value });
|
||||
detectCurrentBranch(e.target.value);
|
||||
}}
|
||||
className="flex-1 px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 placeholder-gray-500 dark:placeholder-gray-400"
|
||||
className="flex-1 px-3 py-2 bg-surface-secondary border border-border-primary rounded-md text-text-primary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive placeholder-text-tertiary"
|
||||
placeholder="/path/to/repository"
|
||||
/>
|
||||
<button
|
||||
@ -514,7 +514,7 @@ export function ProjectTreeView() {
|
||||
detectCurrentBranch(result.data);
|
||||
}
|
||||
}}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
className="px-4 py-2 text-sm font-medium text-text-secondary bg-surface-tertiary border border-border-primary rounded-md hover:bg-surface-hover focus:outline-none focus:ring-2 focus:ring-interactive"
|
||||
>
|
||||
Browse
|
||||
</button>
|
||||
@ -522,45 +522,45 @@ export function ProjectTreeView() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Current Branch <span className="text-gray-500">(Auto-detected)</span>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Current Branch <span className="text-text-tertiary">(Auto-detected)</span>
|
||||
</label>
|
||||
<div className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200">
|
||||
<div className="w-full px-3 py-2 bg-surface-tertiary border border-border-primary rounded-md text-text-secondary">
|
||||
{detectedBranchForNewProject || (newProject.path ? 'Detecting...' : 'Select a repository path first')}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
<p className="text-xs text-text-tertiary mt-1">
|
||||
The main branch is automatically detected from the repository. This will be used for git operations.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Build Script <span className="text-gray-500 dark:text-gray-500">(optional)</span>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Build Script <span className="text-text-tertiary">(optional)</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newProject.buildScript}
|
||||
onChange={(e) => setNewProject({ ...newProject, buildScript: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 placeholder-gray-500 dark:placeholder-gray-400"
|
||||
className="w-full px-3 py-2 bg-surface-secondary border border-border-primary rounded-md text-text-primary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive placeholder-text-tertiary"
|
||||
placeholder="e.g., pnpm build or npm run build"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
<p className="text-xs text-text-tertiary mt-1">
|
||||
This script will run automatically before each Claude Code session starts.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Run Script <span className="text-gray-500 dark:text-gray-500">(optional)</span>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Run Script <span className="text-text-tertiary">(optional)</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newProject.runScript}
|
||||
onChange={(e) => setNewProject({ ...newProject, runScript: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 placeholder-gray-500 dark:placeholder-gray-400"
|
||||
className="w-full px-3 py-2 bg-surface-secondary border border-border-primary rounded-md text-text-primary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive placeholder-text-tertiary"
|
||||
placeholder="e.g., pnpm dev or npm start"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
<p className="text-xs text-text-tertiary mt-1">
|
||||
This script can be run manually from the Terminal view during sessions.
|
||||
</p>
|
||||
</div>
|
||||
@ -572,14 +572,14 @@ export function ProjectTreeView() {
|
||||
setShowAddProjectDialog(false);
|
||||
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
}}
|
||||
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
|
||||
className="px-4 py-2 text-text-secondary hover:text-text-primary transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCreateProject}
|
||||
disabled={!newProject.name || !newProject.path}
|
||||
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
className="px-4 py-2 bg-interactive hover:bg-interactive-hover text-white rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Add Project
|
||||
</button>
|
||||
|
||||
388
frontend/src/components/ProjectView.tsx
Normal file
@ -0,0 +1,388 @@
|
||||
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { API } from '../utils/api';
|
||||
import { useSessionStore } from '../stores/sessionStore';
|
||||
import { Session } from '../types/session';
|
||||
import { PanelTabBar } from './panels/PanelTabBar';
|
||||
import { PanelContainer } from './panels/PanelContainer';
|
||||
import { usePanelStore } from '../stores/panelStore';
|
||||
import { panelApi } from '../services/panelApi';
|
||||
import { ToolPanel, ToolPanelType } from '../../../shared/types/panels';
|
||||
import { SessionProvider } from '../contexts/SessionContext';
|
||||
|
||||
interface ProjectViewProps {
|
||||
projectId: number;
|
||||
projectName: string;
|
||||
onGitPull: () => void;
|
||||
onGitPush: () => void;
|
||||
isMerging: boolean;
|
||||
}
|
||||
|
||||
export const ProjectView: React.FC<ProjectViewProps> = ({
|
||||
projectId,
|
||||
projectName,
|
||||
onGitPull,
|
||||
onGitPush,
|
||||
isMerging
|
||||
}) => {
|
||||
const [mainRepoSessionId, setMainRepoSessionId] = useState<string | null>(null);
|
||||
const [mainRepoSession, setMainRepoSession] = useState<Session | null>(null);
|
||||
const [isLoadingSession, setIsLoadingSession] = useState(false);
|
||||
|
||||
// Panel store state and actions
|
||||
const {
|
||||
panels,
|
||||
activePanels,
|
||||
setPanels,
|
||||
setActivePanel: setActivePanelInStore,
|
||||
addPanel,
|
||||
removePanel
|
||||
} = usePanelStore();
|
||||
|
||||
// Load panels when main repo session changes and ensure dashboard panel exists
|
||||
useEffect(() => {
|
||||
if (mainRepoSessionId) {
|
||||
console.log('[ProjectView] Loading panels for project session:', mainRepoSessionId);
|
||||
panelApi.loadPanelsForSession(mainRepoSessionId).then(async (loadedPanels) => {
|
||||
console.log('[ProjectView] Loaded panels:', loadedPanels);
|
||||
|
||||
// Check if dashboard panel exists, create if not
|
||||
const dashboardPanel = loadedPanels.find(p => p.type === 'dashboard');
|
||||
const setupTasksPanel = loadedPanels.find(p => p.type === 'setup-tasks');
|
||||
|
||||
let panelsCreated = false;
|
||||
|
||||
if (!dashboardPanel) {
|
||||
console.log('[ProjectView] Creating dashboard panel for project');
|
||||
await panelApi.createPanel({
|
||||
sessionId: mainRepoSessionId,
|
||||
type: 'dashboard',
|
||||
title: 'Dashboard',
|
||||
metadata: { permanent: true }
|
||||
});
|
||||
panelsCreated = true;
|
||||
}
|
||||
|
||||
if (!setupTasksPanel) {
|
||||
console.log('[ProjectView] Creating setup-tasks panel for project');
|
||||
await panelApi.createPanel({
|
||||
sessionId: mainRepoSessionId,
|
||||
type: 'setup-tasks',
|
||||
title: 'Setup',
|
||||
metadata: { permanent: true }
|
||||
});
|
||||
panelsCreated = true;
|
||||
}
|
||||
|
||||
// Reload panels if any were created
|
||||
const finalPanels = panelsCreated
|
||||
? await panelApi.loadPanelsForSession(mainRepoSessionId)
|
||||
: loadedPanels;
|
||||
|
||||
setPanels(mainRepoSessionId, finalPanels);
|
||||
|
||||
// Determine which panel should be active
|
||||
const activePanel = await panelApi.getActivePanel(mainRepoSessionId);
|
||||
const setupPanel = finalPanels.find(p => p.type === 'setup-tasks');
|
||||
const dashPanel = finalPanels.find(p => p.type === 'dashboard');
|
||||
|
||||
if (!activePanel) {
|
||||
// No active panel - prioritize setup-tasks if it exists, otherwise dashboard
|
||||
const panelToActivate = setupPanel || dashPanel;
|
||||
if (panelToActivate) {
|
||||
setActivePanelInStore(mainRepoSessionId, panelToActivate.id);
|
||||
await panelApi.setActivePanel(mainRepoSessionId, panelToActivate.id);
|
||||
}
|
||||
} else {
|
||||
// There's already an active panel, use it
|
||||
setActivePanelInStore(mainRepoSessionId, activePanel.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [mainRepoSessionId, setPanels, setActivePanelInStore]);
|
||||
|
||||
// Get panels for current main repo session
|
||||
const sessionPanels = useMemo(
|
||||
() => panels[mainRepoSessionId || ''] || [],
|
||||
[panels, mainRepoSessionId]
|
||||
);
|
||||
|
||||
const currentActivePanel = useMemo(
|
||||
() => sessionPanels.find(p => p.id === activePanels[mainRepoSessionId || '']),
|
||||
[sessionPanels, activePanels, mainRepoSessionId]
|
||||
);
|
||||
|
||||
// Panel event handlers
|
||||
const handlePanelSelect = useCallback(
|
||||
async (panel: ToolPanel) => {
|
||||
if (!mainRepoSessionId) return;
|
||||
setActivePanelInStore(mainRepoSessionId, panel.id);
|
||||
await panelApi.setActivePanel(mainRepoSessionId, panel.id);
|
||||
},
|
||||
[mainRepoSessionId, setActivePanelInStore]
|
||||
);
|
||||
|
||||
const handlePanelClose = useCallback(
|
||||
async (panel: ToolPanel) => {
|
||||
if (!mainRepoSessionId) return;
|
||||
|
||||
// Don't allow closing dashboard or setup-tasks panels
|
||||
if (panel.type === 'dashboard' || panel.type === 'setup-tasks') {
|
||||
console.log('[ProjectView] Cannot close permanent panel:', panel.type);
|
||||
return;
|
||||
}
|
||||
|
||||
// Find next panel to activate
|
||||
const panelIndex = sessionPanels.findIndex(p => p.id === panel.id);
|
||||
let nextPanel = sessionPanels[panelIndex + 1] || sessionPanels[panelIndex - 1];
|
||||
|
||||
// If no other panel or the next panel is the same, fall back to dashboard
|
||||
if (!nextPanel || nextPanel.id === panel.id) {
|
||||
nextPanel = sessionPanels.find(p => p.type === 'dashboard') || sessionPanels[0];
|
||||
}
|
||||
|
||||
// Remove from store first for immediate UI update
|
||||
removePanel(mainRepoSessionId, panel.id);
|
||||
|
||||
// Set next active panel (should always have dashboard)
|
||||
if (nextPanel) {
|
||||
setActivePanelInStore(mainRepoSessionId, nextPanel.id);
|
||||
await panelApi.setActivePanel(mainRepoSessionId, nextPanel.id);
|
||||
}
|
||||
|
||||
// Delete on backend
|
||||
await panelApi.deletePanel(panel.id);
|
||||
},
|
||||
[mainRepoSessionId, sessionPanels, removePanel, setActivePanelInStore]
|
||||
);
|
||||
|
||||
const handlePanelCreate = useCallback(
|
||||
async (type: ToolPanelType) => {
|
||||
if (!mainRepoSessionId) return;
|
||||
|
||||
const newPanel = await panelApi.createPanel({
|
||||
sessionId: mainRepoSessionId,
|
||||
type
|
||||
});
|
||||
|
||||
// Immediately add the panel and set it as active
|
||||
// The panel:created event will also fire, but addPanel checks for duplicates
|
||||
addPanel(newPanel);
|
||||
setActivePanelInStore(mainRepoSessionId, newPanel.id);
|
||||
},
|
||||
[mainRepoSessionId, addPanel, setActivePanelInStore]
|
||||
);
|
||||
|
||||
// Wrapped git operations
|
||||
const handleGitPull = useCallback(() => {
|
||||
// Find or create a Claude panel
|
||||
const claudePanel = sessionPanels.find(p => p.type === 'claude');
|
||||
if (claudePanel) {
|
||||
handlePanelSelect(claudePanel);
|
||||
} else {
|
||||
handlePanelCreate('claude');
|
||||
}
|
||||
onGitPull();
|
||||
}, [onGitPull, sessionPanels, handlePanelSelect, handlePanelCreate]);
|
||||
|
||||
const handleGitPush = useCallback(() => {
|
||||
// Find or create a Claude panel
|
||||
const claudePanel = sessionPanels.find(p => p.type === 'claude');
|
||||
if (claudePanel) {
|
||||
handlePanelSelect(claudePanel);
|
||||
} else {
|
||||
handlePanelCreate('claude');
|
||||
}
|
||||
onGitPush();
|
||||
}, [onGitPush, sessionPanels, handlePanelSelect, handlePanelCreate]);
|
||||
|
||||
// We don't need terminal handling or the hook for now, as panels handle their own terminals
|
||||
|
||||
// Debug logging
|
||||
useEffect(() => {
|
||||
console.log('[ProjectView] Session state:', {
|
||||
mainRepoSessionId,
|
||||
mainRepoSession: mainRepoSession?.id,
|
||||
activePanelType: currentActivePanel?.type,
|
||||
activeSessionInStore: useSessionStore.getState().activeSessionId
|
||||
});
|
||||
}, [mainRepoSessionId, mainRepoSession, currentActivePanel]);
|
||||
|
||||
// Get or create main repo session when panels are needed
|
||||
useEffect(() => {
|
||||
// Create main repo session when component mounts to support panels
|
||||
const getMainRepoSession = async () => {
|
||||
setIsLoadingSession(true);
|
||||
try {
|
||||
const response = await API.sessions.getOrCreateMainRepoSession(projectId);
|
||||
if (response.success && response.data) {
|
||||
setMainRepoSessionId(response.data.id);
|
||||
setMainRepoSession(response.data);
|
||||
|
||||
// Subscribe to session updates
|
||||
const sessions = useSessionStore.getState().sessions;
|
||||
const mainSession = sessions.find(s => s.id === response.data.id);
|
||||
if (mainSession) {
|
||||
setMainRepoSession(mainSession);
|
||||
}
|
||||
|
||||
// Set as active session
|
||||
useSessionStore.getState().setActiveSession(response.data.id);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to get main repo session:', error);
|
||||
} finally {
|
||||
setIsLoadingSession(false);
|
||||
}
|
||||
};
|
||||
|
||||
getMainRepoSession();
|
||||
}, [projectId]);
|
||||
|
||||
// Subscribe to session updates - optimized to check for actual changes
|
||||
useEffect(() => {
|
||||
if (!mainRepoSessionId) return;
|
||||
|
||||
let previousSession = useSessionStore.getState().sessions.find(s => s.id === mainRepoSessionId);
|
||||
const unsubscribe = useSessionStore.subscribe((state) => {
|
||||
const session = state.sessions.find(s => s.id === mainRepoSessionId);
|
||||
// Only update if session actually changed
|
||||
if (session && session !== previousSession) {
|
||||
previousSession = session;
|
||||
setMainRepoSession(session);
|
||||
}
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, [mainRepoSessionId]);
|
||||
|
||||
// Listen for panel updates from the backend
|
||||
useEffect(() => {
|
||||
if (!mainRepoSessionId) return;
|
||||
|
||||
// Handle panel creation events (for auto-created panels like logs)
|
||||
const handlePanelCreated = (panel: ToolPanel) => {
|
||||
console.log('[ProjectView] Received panel:created event:', panel);
|
||||
|
||||
// Only add if it's for the current session
|
||||
if (panel.sessionId === mainRepoSessionId) {
|
||||
// The store's addPanel now checks for duplicates, so we can safely call it
|
||||
addPanel(panel);
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for panel events
|
||||
const unsubscribeCreated = window.electronAPI?.events?.onPanelCreated?.(handlePanelCreated);
|
||||
|
||||
// Cleanup
|
||||
return () => {
|
||||
unsubscribeCreated?.();
|
||||
};
|
||||
}, [mainRepoSessionId, addPanel]);
|
||||
|
||||
// We don't need Stravu connection status here anymore as it's handled in panels
|
||||
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-bg-primary">
|
||||
{/* Project Header */}
|
||||
<div className="bg-surface-primary border-b border-border-primary px-4 py-3 flex-shrink-0">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1 min-w-0 relative">
|
||||
<h2 className="font-bold text-xl text-text-primary truncate">
|
||||
{projectName}
|
||||
</h2>
|
||||
|
||||
{/* Git Actions for Main Project */}
|
||||
<div className="flex flex-wrap items-center gap-2 mt-2">
|
||||
<div className="flex flex-wrap items-center gap-2 relative z-20">
|
||||
<div className="group relative">
|
||||
<button
|
||||
onClick={handleGitPull}
|
||||
disabled={isMerging}
|
||||
className={`px-3 py-1.5 rounded-full border transition-all flex items-center space-x-2 ${
|
||||
isMerging
|
||||
? 'bg-surface-secondary border-border-secondary text-text-disabled cursor-not-allowed'
|
||||
: 'bg-surface-secondary border-status-info text-status-info hover:bg-status-info/10 hover:border-status-info/70'
|
||||
}`}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 17l-4 4m0 0l-4-4m4 4V3" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium">{isMerging ? 'Pulling...' : 'Pull'}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="group relative">
|
||||
<button
|
||||
onClick={handleGitPush}
|
||||
disabled={isMerging}
|
||||
className={`px-3 py-1.5 rounded-full border transition-all flex items-center space-x-2 ${
|
||||
isMerging
|
||||
? 'bg-surface-secondary border-border-secondary text-text-disabled cursor-not-allowed'
|
||||
: 'bg-surface-secondary border-status-success text-status-success hover:bg-status-success/10 hover:border-status-success/70'
|
||||
}`}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7l4-4m0 0l4 4m-4-4v18" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium">{isMerging ? 'Pushing...' : 'Push'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tool Panel Bar (Dashboard is now part of the panel system) */}
|
||||
{mainRepoSessionId && (
|
||||
<SessionProvider session={mainRepoSession} projectName={projectName}>
|
||||
<PanelTabBar
|
||||
panels={sessionPanels}
|
||||
activePanel={currentActivePanel}
|
||||
onPanelSelect={handlePanelSelect}
|
||||
onPanelClose={handlePanelClose}
|
||||
onPanelCreate={handlePanelCreate}
|
||||
context="project"
|
||||
/>
|
||||
</SessionProvider>
|
||||
)}
|
||||
|
||||
{/* Content Area */}
|
||||
<div className="flex-1 flex relative min-h-0">
|
||||
<div className="flex-1 relative">
|
||||
{isLoadingSession || !mainRepoSessionId ? (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-interactive mx-auto mb-4"></div>
|
||||
<p className="text-text-secondary">Loading panels...</p>
|
||||
</div>
|
||||
</div>
|
||||
) : sessionPanels.length > 0 && currentActivePanel ? (
|
||||
<SessionProvider session={mainRepoSession} projectName={projectName}>
|
||||
{sessionPanels.map(panel => (
|
||||
<div
|
||||
key={panel.id}
|
||||
className="absolute inset-0"
|
||||
style={{ display: panel.id === currentActivePanel.id ? 'block' : 'none' }}
|
||||
>
|
||||
<PanelContainer
|
||||
panel={panel}
|
||||
isActive={panel.id === currentActivePanel.id}
|
||||
isMainRepo={!!mainRepoSession?.isMainRepo}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</SessionProvider>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center">
|
||||
<p className="text-text-secondary mb-4">Loading dashboard...</p>
|
||||
<p className="text-text-tertiary text-sm">Setting up project panels</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -1,11 +1,14 @@
|
||||
import { X, Copy, Check } from 'lucide-react';
|
||||
import { Copy, Check } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { formatDistanceToNow } from '../utils/formatters';
|
||||
import { formatDuration, getTimeDifference, isValidTimestamp, parseTimestamp } from '../utils/timestampUtils';
|
||||
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { IconButton } from './ui/IconButton';
|
||||
|
||||
interface PromptMarker {
|
||||
id: number;
|
||||
session_id: string;
|
||||
session_id?: string;
|
||||
panel_id?: string;
|
||||
prompt_text: string;
|
||||
output_index: number;
|
||||
output_line?: number;
|
||||
@ -53,72 +56,44 @@ export function PromptDetailModal({ prompt, promptIndex, onClose }: PromptDetail
|
||||
}
|
||||
};
|
||||
|
||||
// Close on escape key
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
// No need for manual escape handling - Modal component handles it
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
|
||||
onClick={onClose}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
<div
|
||||
className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full max-h-[80vh] flex flex-col"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
|
||||
<Modal isOpen={true} onClose={onClose} size="lg" showCloseButton={false}>
|
||||
<ModalHeader onClose={onClose}>
|
||||
<div className="flex items-center justify-between flex-1 pr-2">
|
||||
<div className="flex items-center space-x-3">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
<h2 className="text-lg font-semibold text-text-primary">
|
||||
Prompt #{promptIndex + 1}
|
||||
</h2>
|
||||
<div className="flex items-center space-x-2 text-sm text-gray-500 dark:text-gray-400">
|
||||
<div className="flex items-center space-x-2 text-sm text-text-tertiary">
|
||||
<span>{formatDistanceToNow(parseTimestamp(prompt.timestamp))} ago</span>
|
||||
<span className="text-gray-400">•</span>
|
||||
<span className="text-text-tertiary">•</span>
|
||||
<span className="font-medium">{calculateDuration()}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
|
||||
title="Copy prompt"
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4 text-gray-500 dark:text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
|
||||
title="Close"
|
||||
>
|
||||
<X className="h-4 w-4 text-gray-500 dark:text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
<IconButton
|
||||
onClick={handleCopy}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label="Copy prompt"
|
||||
icon={copied ? <Check className="h-4 w-4 text-status-success" /> : <Copy className="h-4 w-4" />}
|
||||
/>
|
||||
</div>
|
||||
</ModalHeader>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<pre className="whitespace-pre-wrap font-mono text-sm text-gray-800 dark:text-gray-200 bg-gray-50 dark:bg-gray-900 p-4 rounded-md">
|
||||
{prompt.prompt_text}
|
||||
</pre>
|
||||
</div>
|
||||
<ModalBody>
|
||||
<pre className="whitespace-pre-wrap font-mono text-sm text-text-primary bg-surface-primary p-4 rounded-md border border-border-secondary">
|
||||
{prompt.prompt_text}
|
||||
</pre>
|
||||
</ModalBody>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700 text-sm text-gray-500 dark:text-gray-400">
|
||||
<div className="flex items-center justify-between">
|
||||
<span>Press ESC to close</span>
|
||||
<span>Double-click any prompt to view details</span>
|
||||
</div>
|
||||
<ModalFooter>
|
||||
<div className="flex items-center justify-between w-full text-sm text-text-tertiary">
|
||||
<span>Press ESC to close</span>
|
||||
<span>Double-click any prompt to view details</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -1,6 +1,10 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSessionStore } from '../stores/sessionStore';
|
||||
import { API } from '../utils/api';
|
||||
import { Button } from './ui/Button';
|
||||
import { Input } from './ui/Input';
|
||||
import { Card } from './ui/Card';
|
||||
import { Search, Copy } from 'lucide-react';
|
||||
|
||||
interface PromptHistoryItem {
|
||||
id: string;
|
||||
@ -96,15 +100,15 @@ export function PromptHistory() {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
case 'stopped':
|
||||
return 'text-green-600 dark:text-green-400 bg-green-100 dark:bg-green-900/20';
|
||||
return 'text-status-success bg-status-success/10';
|
||||
case 'error':
|
||||
return 'text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/20';
|
||||
return 'text-status-error bg-status-error/10';
|
||||
case 'running':
|
||||
return 'text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/20';
|
||||
return 'text-interactive bg-interactive/10';
|
||||
case 'waiting':
|
||||
return 'text-yellow-600 dark:text-yellow-400 bg-yellow-100 dark:bg-yellow-900/20';
|
||||
return 'text-status-warning bg-status-warning/10';
|
||||
default:
|
||||
return 'text-gray-600 dark:text-gray-400 bg-gray-200 dark:bg-gray-700';
|
||||
return 'text-text-tertiary bg-surface-tertiary';
|
||||
}
|
||||
};
|
||||
|
||||
@ -113,31 +117,20 @@ export function PromptHistory() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col bg-white dark:bg-gray-900 overflow-hidden">
|
||||
<div className="h-full flex flex-col bg-bg-primary overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="border-b border-gray-200 dark:border-gray-700 p-6 flex-shrink-0">
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 mb-4">Prompt History</h1>
|
||||
<div className="border-b border-border-primary p-6 flex-shrink-0">
|
||||
<h1 className="text-2xl font-bold text-text-primary mb-4">Prompt History</h1>
|
||||
<div className="relative">
|
||||
<input
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search prompts or session names..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full px-4 py-2 pl-10 bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400"
|
||||
fullWidth
|
||||
className="pl-10"
|
||||
/>
|
||||
<svg
|
||||
className="absolute left-3 top-2.5 h-5 w-5 text-gray-500 dark:text-gray-400"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
|
||||
/>
|
||||
</svg>
|
||||
<Search className="absolute left-3 top-2.5 h-5 w-5 text-text-tertiary pointer-events-none" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -145,15 +138,15 @@ export function PromptHistory() {
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<div className="text-gray-600 dark:text-gray-400">Loading prompt history...</div>
|
||||
<div className="text-text-secondary">Loading prompt history...</div>
|
||||
</div>
|
||||
) : filteredPrompts.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<div className="text-center text-gray-600 dark:text-gray-400">
|
||||
<div className="text-center text-text-secondary">
|
||||
<div className="text-lg mb-2">
|
||||
{searchTerm ? 'No prompts found' : 'No prompt history yet'}
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<div className="text-sm text-text-tertiary">
|
||||
{searchTerm
|
||||
? 'Try adjusting your search terms'
|
||||
: 'Create a session to start building your prompt history'
|
||||
@ -164,19 +157,20 @@ export function PromptHistory() {
|
||||
) : (
|
||||
<div className="p-6 space-y-4">
|
||||
{filteredPrompts.map((promptItem) => (
|
||||
<div
|
||||
<Card
|
||||
key={promptItem.id}
|
||||
className={`border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer ${
|
||||
variant={selectedPromptId === promptItem.id ? 'interactive' : 'bordered'}
|
||||
className={`cursor-pointer transition-all ${
|
||||
selectedPromptId === promptItem.id
|
||||
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
|
||||
: 'border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800'
|
||||
? 'border-interactive bg-interactive/10'
|
||||
: ''
|
||||
}`}
|
||||
onClick={() => handlePromptClick(promptItem)}
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center space-x-3 mb-2">
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 truncate">
|
||||
<h3 className="text-lg font-medium text-text-primary truncate">
|
||||
{promptItem.sessionName}
|
||||
</h3>
|
||||
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(promptItem.status)}`}>
|
||||
@ -184,11 +178,11 @@ export function PromptHistory() {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-700 dark:text-gray-300 mb-3 leading-relaxed">
|
||||
<p className="text-text-secondary mb-3 leading-relaxed">
|
||||
{truncatePrompt(promptItem.prompt, 200)}
|
||||
</p>
|
||||
|
||||
<div className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-400">
|
||||
<div className="flex items-center justify-between text-sm text-text-tertiary">
|
||||
<span>
|
||||
Created {new Date(promptItem.createdAt).toLocaleDateString()} at{' '}
|
||||
{new Date(promptItem.createdAt).toLocaleTimeString()}
|
||||
@ -197,32 +191,40 @@ export function PromptHistory() {
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col space-y-2 ml-4">
|
||||
<button
|
||||
onClick={() => handleReusePrompt(promptItem)}
|
||||
className="px-3 py-1 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors"
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleReusePrompt(promptItem);
|
||||
}}
|
||||
size="sm"
|
||||
>
|
||||
Reuse
|
||||
</button>
|
||||
<button
|
||||
onClick={() => navigator.clipboard.writeText(promptItem.prompt)}
|
||||
className="px-3 py-1 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 text-sm rounded-md hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors"
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigator.clipboard.writeText(promptItem.prompt);
|
||||
}}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
>
|
||||
<Copy className="w-3 h-3 mr-1" />
|
||||
Copy
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{promptItem.prompt.length > 200 && (
|
||||
<details className="mt-3">
|
||||
<summary className="cursor-pointer text-blue-600 dark:text-blue-400 text-sm hover:text-blue-700 dark:hover:text-blue-300">
|
||||
<summary className="cursor-pointer text-interactive-on-dark text-sm transition-colors">
|
||||
Show full prompt
|
||||
</summary>
|
||||
<p className="mt-2 text-gray-700 dark:text-gray-300 whitespace-pre-wrap">
|
||||
<p className="mt-2 text-text-secondary whitespace-pre-wrap">
|
||||
{promptItem.prompt}
|
||||
</p>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@ -1,7 +1,11 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSessionStore } from '../stores/sessionStore';
|
||||
import { API } from '../utils/api';
|
||||
import { X } from 'lucide-react';
|
||||
import { Search } from 'lucide-react';
|
||||
import { Modal, ModalHeader, ModalBody } from './ui/Modal';
|
||||
import { Button } from './ui/Button';
|
||||
import { Input } from './ui/Input';
|
||||
import { Badge } from './ui/Badge';
|
||||
|
||||
interface PromptHistoryItem {
|
||||
id: string;
|
||||
@ -32,18 +36,7 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && isOpen) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}
|
||||
}, [isOpen, onClose]);
|
||||
// Modal component handles escape key automatically
|
||||
|
||||
const fetchPromptHistory = async () => {
|
||||
try {
|
||||
@ -125,19 +118,19 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
|
||||
navigator.clipboard.writeText(prompt);
|
||||
};
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
const getStatusVariant = (status: string): 'success' | 'error' | 'warning' | 'info' | 'default' => {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
case 'stopped':
|
||||
return 'text-green-600 dark:text-green-400 bg-green-100 dark:bg-green-900/20';
|
||||
return 'success';
|
||||
case 'error':
|
||||
return 'text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/20';
|
||||
return 'error';
|
||||
case 'running':
|
||||
return 'text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/20';
|
||||
return 'info';
|
||||
case 'waiting':
|
||||
return 'text-yellow-600 dark:text-yellow-400 bg-yellow-100 dark:bg-yellow-900/20';
|
||||
return 'warning';
|
||||
default:
|
||||
return 'text-gray-600 dark:text-gray-400 bg-gray-200 dark:bg-gray-700';
|
||||
return 'default';
|
||||
}
|
||||
};
|
||||
|
||||
@ -145,62 +138,37 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
|
||||
return prompt.length > maxLength ? prompt.substring(0, maxLength) + '...' : prompt;
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onClick={onClose}>
|
||||
<div
|
||||
className="bg-white dark:bg-gray-900 rounded-lg shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col m-4"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="border-b border-gray-200 dark:border-gray-700 p-6 flex-shrink-0">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Prompt History</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors"
|
||||
>
|
||||
<X className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search prompts or session names..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full px-4 py-2 pl-10 bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400"
|
||||
/>
|
||||
<svg
|
||||
className="absolute left-3 top-2.5 h-5 w-5 text-gray-500 dark:text-gray-400"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
|
||||
/>
|
||||
</svg>
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="xl" showCloseButton={false}>
|
||||
<ModalHeader title="Prompt History" onClose={onClose} />
|
||||
|
||||
<div className="p-6 border-b border-border-primary">
|
||||
<div className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<Search className="w-5 h-5 text-text-muted" />
|
||||
</div>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search prompts or session names..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
<ModalBody className="p-6">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<div className="text-gray-600 dark:text-gray-400">Loading prompt history...</div>
|
||||
<div className="text-text-secondary">Loading prompt history...</div>
|
||||
</div>
|
||||
) : filteredPrompts.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<div className="text-center text-gray-600 dark:text-gray-400">
|
||||
<div className="text-center text-text-secondary">
|
||||
<div className="text-lg mb-2">
|
||||
{searchTerm ? 'No prompts found' : 'No prompt history yet'}
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<div className="text-sm text-text-tertiary">
|
||||
{searchTerm
|
||||
? 'Try adjusting your search terms'
|
||||
: 'Create a session to start building your prompt history'
|
||||
@ -213,29 +181,29 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
|
||||
{filteredPrompts.map((promptItem) => (
|
||||
<div
|
||||
key={promptItem.id}
|
||||
className={`border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer ${
|
||||
className={`border rounded-lg p-4 hover:shadow-md transition-all cursor-pointer ${
|
||||
selectedPromptId === promptItem.id
|
||||
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
|
||||
: 'border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800'
|
||||
? 'border-interactive bg-interactive/10'
|
||||
: 'border-border-primary bg-surface-secondary hover:bg-surface-tertiary'
|
||||
}`}
|
||||
onClick={() => handlePromptClick(promptItem)}
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center space-x-3 mb-2">
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 truncate">
|
||||
<h3 className="text-lg font-medium text-text-primary truncate">
|
||||
{promptItem.sessionName}
|
||||
</h3>
|
||||
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(promptItem.status)}`}>
|
||||
<Badge variant={getStatusVariant(promptItem.status)} size="sm">
|
||||
{promptItem.status}
|
||||
</span>
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-700 dark:text-gray-300 mb-3 leading-relaxed">
|
||||
<p className="text-text-secondary mb-3 leading-relaxed">
|
||||
{truncatePrompt(promptItem.prompt, 200)}
|
||||
</p>
|
||||
|
||||
<div className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-400">
|
||||
<div className="flex items-center justify-between text-sm text-text-tertiary">
|
||||
<span>
|
||||
Created {new Date(promptItem.createdAt).toLocaleDateString()} at{' '}
|
||||
{new Date(promptItem.createdAt).toLocaleTimeString()}
|
||||
@ -244,27 +212,29 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col space-y-2 ml-4">
|
||||
<button
|
||||
<Button
|
||||
onClick={(e) => handleReusePrompt(promptItem, e)}
|
||||
className="px-3 py-1 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors"
|
||||
variant="primary"
|
||||
size="sm"
|
||||
>
|
||||
Reuse
|
||||
</button>
|
||||
<button
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(e) => handleCopyPrompt(promptItem.prompt, e)}
|
||||
className="px-3 py-1 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 text-sm rounded-md hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
>
|
||||
Copy
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{promptItem.prompt.length > 200 && (
|
||||
<details className="mt-3">
|
||||
<summary className="cursor-pointer text-blue-600 dark:text-blue-400 text-sm hover:text-blue-700 dark:hover:text-blue-300">
|
||||
<summary className="cursor-pointer text-interactive text-sm hover:text-interactive-hover">
|
||||
Show full prompt
|
||||
</summary>
|
||||
<p className="mt-2 text-gray-700 dark:text-gray-300 whitespace-pre-wrap">
|
||||
<p className="mt-2 text-text-secondary whitespace-pre-wrap">
|
||||
{promptItem.prompt}
|
||||
</p>
|
||||
</details>
|
||||
@ -273,8 +243,7 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalBody>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -1,258 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { formatDistanceToNow } from '../utils/formatters';
|
||||
import { formatDuration, getTimeDifference, isValidTimestamp, parseTimestamp } from '../utils/timestampUtils';
|
||||
import { API } from '../utils/api';
|
||||
import { useSessionStore } from '../stores/sessionStore';
|
||||
import { PromptDetailModal } from './PromptDetailModal';
|
||||
|
||||
interface PromptMarker {
|
||||
id: number;
|
||||
session_id: string;
|
||||
prompt_text: string;
|
||||
output_index: number;
|
||||
output_line?: number;
|
||||
timestamp: string;
|
||||
completion_timestamp?: string;
|
||||
}
|
||||
|
||||
interface PromptNavigationProps {
|
||||
sessionId: string;
|
||||
onNavigateToPrompt: (marker: PromptMarker) => void;
|
||||
}
|
||||
|
||||
export function PromptNavigation({ sessionId, onNavigateToPrompt }: PromptNavigationProps) {
|
||||
const [prompts, setPrompts] = useState<PromptMarker[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedPromptId, setSelectedPromptId] = useState<number | null>(null);
|
||||
const [modalPrompt, setModalPrompt] = useState<{ prompt: PromptMarker; index: number } | null>(null);
|
||||
const activeSession = useSessionStore((state) => state.sessions.find(s => s.id === sessionId));
|
||||
|
||||
const calculateDuration = (currentPrompt: PromptMarker, currentIndex: number): string => {
|
||||
try {
|
||||
const isLast = currentIndex === prompts.length - 1;
|
||||
|
||||
console.log('calculateDuration for prompt:', {
|
||||
index: currentIndex,
|
||||
isLast,
|
||||
prompt_id: currentPrompt.id,
|
||||
raw_timestamp: currentPrompt.timestamp,
|
||||
completion_timestamp: currentPrompt.completion_timestamp,
|
||||
session_status: activeSession?.status,
|
||||
prompt_text_preview: currentPrompt.prompt_text.substring(0, 30) + '...'
|
||||
});
|
||||
|
||||
// Validate the current prompt's timestamp
|
||||
if (!isValidTimestamp(currentPrompt.timestamp)) {
|
||||
console.warn('Invalid timestamp for prompt:', currentPrompt.timestamp);
|
||||
return 'Unknown duration';
|
||||
}
|
||||
|
||||
// If we have a completion_timestamp, use it to calculate the actual execution duration
|
||||
if (currentPrompt.completion_timestamp && isValidTimestamp(currentPrompt.completion_timestamp)) {
|
||||
const durationMs = getTimeDifference(currentPrompt.timestamp, currentPrompt.completion_timestamp);
|
||||
|
||||
console.log('Using completion timestamp:', {
|
||||
start: currentPrompt.timestamp,
|
||||
end: currentPrompt.completion_timestamp,
|
||||
duration_ms: durationMs
|
||||
});
|
||||
|
||||
// Check for negative duration
|
||||
if (durationMs < 0) {
|
||||
console.warn('Negative duration detected with completion timestamp');
|
||||
return 'Invalid duration';
|
||||
}
|
||||
|
||||
return formatDuration(durationMs);
|
||||
}
|
||||
|
||||
// If no completion timestamp, check if prompt is still running
|
||||
if (isLast && activeSession && (activeSession.status === 'running' || activeSession.status === 'waiting')) {
|
||||
// For ongoing prompts, calculate duration from the UTC timestamp to current UTC time
|
||||
const startTime = parseTimestamp(currentPrompt.timestamp);
|
||||
const now = new Date();
|
||||
const durationMs = now.getTime() - startTime.getTime();
|
||||
|
||||
console.log('Calculating ongoing duration:', {
|
||||
raw_timestamp: currentPrompt.timestamp,
|
||||
parsed_start: startTime.toISOString(),
|
||||
now_utc: now.toISOString(),
|
||||
duration_ms: durationMs
|
||||
});
|
||||
|
||||
// Check for negative duration
|
||||
if (durationMs < 0) {
|
||||
console.error('NEGATIVE DURATION DETECTED:', {
|
||||
raw_timestamp: currentPrompt.timestamp,
|
||||
parsed_as_utc: startTime.toISOString(),
|
||||
current_time_utc: now.toISOString(),
|
||||
difference_ms: durationMs,
|
||||
difference_hours: durationMs / (1000 * 60 * 60)
|
||||
});
|
||||
// Instead of showing negative, show the absolute value with a warning
|
||||
return `${formatDuration(Math.abs(durationMs))} (!)`;
|
||||
}
|
||||
|
||||
return formatDuration(durationMs) + ' (ongoing)';
|
||||
}
|
||||
|
||||
// For prompts without completion_timestamp that are not actively running
|
||||
// Try to estimate using the next prompt's timestamp
|
||||
if (!isLast && currentIndex < prompts.length - 1) {
|
||||
const nextPrompt = prompts[currentIndex + 1];
|
||||
if (nextPrompt && isValidTimestamp(nextPrompt.timestamp)) {
|
||||
const durationMs = getTimeDifference(currentPrompt.timestamp, nextPrompt.timestamp);
|
||||
|
||||
console.log('Estimating duration from next prompt:', {
|
||||
current_timestamp: currentPrompt.timestamp,
|
||||
next_timestamp: nextPrompt.timestamp,
|
||||
duration_ms: durationMs
|
||||
});
|
||||
|
||||
if (durationMs >= 0) {
|
||||
return formatDuration(durationMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for completed prompts without any way to calculate duration
|
||||
return 'Completed';
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error calculating duration:', error);
|
||||
return 'Unknown duration';
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
|
||||
const fetchPrompts = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await API.sessions.getPrompts(sessionId);
|
||||
if (response.success) {
|
||||
// Log the timestamps to debug format issues
|
||||
console.log('Fetched prompts with timestamps:', response.data.map((p: PromptMarker) => ({
|
||||
id: p.id,
|
||||
raw_timestamp: p.timestamp,
|
||||
parsed_timestamp: parseTimestamp(p.timestamp).toISOString(),
|
||||
completion_timestamp: p.completion_timestamp,
|
||||
parsed_completion: p.completion_timestamp ? parseTimestamp(p.completion_timestamp).toISOString() : null,
|
||||
prompt_text: p.prompt_text.substring(0, 50) + '...'
|
||||
})));
|
||||
setPrompts(response.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching prompt markers:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchPrompts();
|
||||
|
||||
// Only refresh prompts when session status changes, not on a timer
|
||||
// This reduces unnecessary API calls from every 5 seconds to only when needed
|
||||
}, [sessionId, activeSession?.status]);
|
||||
|
||||
// Use requestAnimationFrame for smooth UI updates instead of setInterval
|
||||
useEffect(() => {
|
||||
if (!activeSession || (activeSession.status !== 'running' && activeSession.status !== 'waiting')) {
|
||||
return;
|
||||
}
|
||||
|
||||
let animationId: number;
|
||||
let lastUpdate = 0;
|
||||
const UPDATE_INTERVAL = 5000; // Update every 5 seconds instead of every second
|
||||
|
||||
const updateOngoingDuration = (timestamp: number) => {
|
||||
if (timestamp - lastUpdate >= UPDATE_INTERVAL) {
|
||||
setPrompts(prev => [...prev]); // Force re-render for duration updates
|
||||
lastUpdate = timestamp;
|
||||
}
|
||||
animationId = requestAnimationFrame(updateOngoingDuration);
|
||||
};
|
||||
|
||||
animationId = requestAnimationFrame(updateOngoingDuration);
|
||||
return () => cancelAnimationFrame(animationId);
|
||||
}, [activeSession?.status]);
|
||||
|
||||
const handlePromptClick = (marker: PromptMarker) => {
|
||||
setSelectedPromptId(marker.id);
|
||||
onNavigateToPrompt(marker);
|
||||
};
|
||||
|
||||
const handlePromptDoubleClick = (marker: PromptMarker, index: number) => {
|
||||
setModalPrompt({ prompt: marker, index });
|
||||
};
|
||||
|
||||
if (isLoading && prompts.length === 0) {
|
||||
return (
|
||||
<div className="w-64 bg-gray-800 border-l border-gray-700 p-4">
|
||||
<h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-4">Prompt History</h3>
|
||||
<div className="text-gray-500 dark:text-gray-400 text-sm">Loading prompts...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-64 bg-gray-800 border-l border-gray-700 flex flex-col h-full">
|
||||
<div className="p-4 border-b border-gray-700">
|
||||
<h3 className="font-semibold text-gray-700 dark:text-gray-300">Prompt History</h3>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Click to navigate • Double-click for details</p>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{prompts.length === 0 ? (
|
||||
<div className="p-4 text-gray-500 dark:text-gray-400 text-sm">
|
||||
No prompts yet. Start by entering a prompt below.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1 p-2">
|
||||
{prompts.map((marker, index) => (
|
||||
<button
|
||||
key={marker.id}
|
||||
onClick={() => handlePromptClick(marker)}
|
||||
onDoubleClick={() => handlePromptDoubleClick(marker, index)}
|
||||
className={`w-full text-left p-3 rounded-lg transition-colors ${
|
||||
selectedPromptId === marker.id
|
||||
? 'bg-blue-900/30 border-blue-700 border'
|
||||
: 'hover:bg-gray-700 border border-transparent'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start space-x-2">
|
||||
<span className="text-blue-500 dark:text-blue-400 font-mono text-sm mt-0.5">
|
||||
#{index + 1}
|
||||
</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm text-gray-800 dark:text-gray-200 line-clamp-2">
|
||||
{marker.prompt_text}
|
||||
</div>
|
||||
<div className="flex items-center space-x-2 text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
<span>{formatDistanceToNow(parseTimestamp(marker.timestamp))} ago</span>
|
||||
<span className="text-gray-400">•</span>
|
||||
<span className="font-medium text-gray-600 dark:text-gray-400">
|
||||
{calculateDuration(marker, index)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{modalPrompt && (
|
||||
<PromptDetailModal
|
||||
prompt={modalPrompt.prompt}
|
||||
promptIndex={modalPrompt.index}
|
||||
onClose={() => setModalPrompt(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
114
frontend/src/components/ResizablePanel.tsx
Normal file
@ -0,0 +1,114 @@
|
||||
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { GripHorizontal } from 'lucide-react';
|
||||
|
||||
interface ResizablePanelProps {
|
||||
children: React.ReactNode;
|
||||
defaultHeight?: number;
|
||||
minHeight?: number;
|
||||
maxHeight?: number;
|
||||
storageKey: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const ResizablePanel: React.FC<ResizablePanelProps> = ({
|
||||
children,
|
||||
defaultHeight = 300,
|
||||
minHeight = 200,
|
||||
maxHeight = 600,
|
||||
storageKey,
|
||||
className = '',
|
||||
}) => {
|
||||
// Load height from localStorage or use default
|
||||
const [height, setHeight] = useState<number>(() => {
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
return saved ? parseInt(saved, 10) : defaultHeight;
|
||||
});
|
||||
|
||||
const [isResizing, setIsResizing] = useState(false);
|
||||
const startYRef = useRef<number>(0);
|
||||
const startHeightRef = useRef<number>(0);
|
||||
|
||||
// Save height to localStorage when it changes
|
||||
useEffect(() => {
|
||||
localStorage.setItem(storageKey, height.toString());
|
||||
}, [height, storageKey]);
|
||||
|
||||
const handleMouseDown = useCallback((e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
setIsResizing(true);
|
||||
startYRef.current = e.clientY;
|
||||
startHeightRef.current = height;
|
||||
}, [height]);
|
||||
|
||||
const handleMouseMove = useCallback((e: MouseEvent) => {
|
||||
if (!isResizing) return;
|
||||
|
||||
// Calculate the new height based on mouse movement
|
||||
// Since we're dragging from the top, moving up should increase height
|
||||
const deltaY = startYRef.current - e.clientY;
|
||||
const newHeight = startHeightRef.current + deltaY;
|
||||
|
||||
// Clamp height between min and max
|
||||
const clampedHeight = Math.max(minHeight, Math.min(maxHeight, newHeight));
|
||||
setHeight(clampedHeight);
|
||||
}, [isResizing, minHeight, maxHeight]);
|
||||
|
||||
const handleMouseUp = useCallback(() => {
|
||||
setIsResizing(false);
|
||||
}, []);
|
||||
|
||||
// Add global mouse event listeners when resizing
|
||||
useEffect(() => {
|
||||
if (isResizing) {
|
||||
document.addEventListener('mousemove', handleMouseMove);
|
||||
document.addEventListener('mouseup', handleMouseUp);
|
||||
// Prevent text selection while dragging
|
||||
document.body.style.userSelect = 'none';
|
||||
document.body.style.cursor = 'ns-resize';
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousemove', handleMouseMove);
|
||||
document.removeEventListener('mouseup', handleMouseUp);
|
||||
document.body.style.userSelect = '';
|
||||
document.body.style.cursor = '';
|
||||
};
|
||||
}
|
||||
}, [isResizing, handleMouseMove, handleMouseUp]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex flex-col ${className}`}
|
||||
style={{ height: `${height}px` }}
|
||||
>
|
||||
{/* Resize Handle */}
|
||||
<div
|
||||
className={`
|
||||
flex items-center justify-center
|
||||
h-2 cursor-ns-resize
|
||||
border-t border-border-primary
|
||||
bg-surface-secondary
|
||||
hover:bg-surface-hover
|
||||
transition-colors
|
||||
group
|
||||
${isResizing ? 'bg-interactive/10' : ''}
|
||||
`}
|
||||
onMouseDown={handleMouseDown}
|
||||
title="Drag to resize"
|
||||
>
|
||||
<GripHorizontal
|
||||
className={`
|
||||
w-5 h-5 text-text-tertiary
|
||||
group-hover:text-text-secondary
|
||||
transition-colors
|
||||
${isResizing ? 'text-interactive' : ''}
|
||||
`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-visible">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
103
frontend/src/components/RunScriptConfigDialog.tsx
Normal file
@ -0,0 +1,103 @@
|
||||
import { Settings, X, Play, AlertCircle } from 'lucide-react';
|
||||
|
||||
interface RunScriptConfigDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onOpenSettings?: () => void;
|
||||
}
|
||||
|
||||
export function RunScriptConfigDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onOpenSettings
|
||||
}: RunScriptConfigDialogProps) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleOpenSettings = () => {
|
||||
onClose();
|
||||
if (onOpenSettings) {
|
||||
onOpenSettings();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full mx-4 p-6">
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex-shrink-0">
|
||||
<Play className="w-6 h-6 text-blue-500" />
|
||||
</div>
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-white">
|
||||
Configure Run Script
|
||||
</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mb-6 space-y-4">
|
||||
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
|
||||
<div className="flex items-start space-x-2">
|
||||
<AlertCircle className="w-5 h-5 text-yellow-600 dark:text-yellow-500 flex-shrink-0 mt-0.5" />
|
||||
<div className="text-sm text-yellow-800 dark:text-yellow-300">
|
||||
<p className="font-semibold mb-1">No run script configured</p>
|
||||
<p>A run script is required to test changes in your application.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-gray-700 dark:text-gray-300 space-y-3">
|
||||
<p>
|
||||
<strong>What is a run script?</strong><br />
|
||||
A run script contains the commands needed to start your application for testing changes made by Claude Code sessions.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<strong>How to configure:</strong>
|
||||
</p>
|
||||
<ol className="list-decimal list-inside space-y-2 ml-4">
|
||||
<li>Click the settings icon (⚙️) next to your project name in the sidebar (visible on hover)</li>
|
||||
<li>In the "Run Script" field, enter the command(s) to start your application</li>
|
||||
<li>Optionally add a "Build Script" that runs when creating new worktrees</li>
|
||||
</ol>
|
||||
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mt-4">
|
||||
<p className="text-sm text-blue-800 dark:text-blue-300">
|
||||
<strong>💡 Recommendation:</strong> Include commands to kill any existing instances of your application to prevent port conflicts when switching between sessions.
|
||||
</p>
|
||||
<div className="mt-2 font-mono text-xs bg-white dark:bg-gray-900 p-2 rounded border border-blue-200 dark:border-blue-700">
|
||||
<div className="text-gray-600 dark:text-gray-400"># Example for a Node.js app on port 3000:</div>
|
||||
<div>pkill -f "node.*port=3000" || true</div>
|
||||
<div>npm run dev</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
{onOpenSettings && (
|
||||
<button
|
||||
onClick={handleOpenSettings}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md transition-colors flex items-center space-x-2"
|
||||
autoFocus
|
||||
>
|
||||
<Settings className="w-4 h-4" />
|
||||
<span>Open Project Settings</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,17 +1,27 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, memo, useCallback } from 'react';
|
||||
import { useSessionStore } from '../stores/sessionStore';
|
||||
import { useNavigationStore } from '../stores/navigationStore';
|
||||
import { StatusIndicator } from './StatusIndicator';
|
||||
import { GitStatusIndicator } from './GitStatusIndicator';
|
||||
import { ConfirmDialog } from './ConfirmDialog';
|
||||
import { RunScriptConfigDialog } from './RunScriptConfigDialog';
|
||||
import { NimbalystInstallDialog } from './NimbalystInstallDialog';
|
||||
import { API } from '../utils/api';
|
||||
import { Star, Archive } from 'lucide-react';
|
||||
import type { Session } from '../types/session';
|
||||
import { NimbalystIcon } from './icons/NimbalystIcon';
|
||||
import type { Session, GitStatus } from '../types/session';
|
||||
import { useContextMenu } from '../contexts/ContextMenuContext';
|
||||
import { IconButton } from './ui/IconButton';
|
||||
import { cn } from '../utils/cn';
|
||||
import { AnalyticsService } from '../services/analyticsService';
|
||||
|
||||
interface SessionListItemProps {
|
||||
session: Session;
|
||||
isNested?: boolean;
|
||||
}
|
||||
|
||||
export function SessionListItem({ session, isNested = false }: SessionListItemProps) {
|
||||
// Memoized component to prevent unnecessary re-renders
|
||||
export const SessionListItem = memo(function SessionListItem({ session, isNested = false }: SessionListItemProps) {
|
||||
const { activeSessionId, setActiveSession, deletingSessionIds, addDeletingSessionId, removeDeletingSessionId } = useSessionStore();
|
||||
const { navigateToSessions } = useNavigationStore();
|
||||
const isActive = activeSessionId === session.id;
|
||||
@ -21,36 +31,23 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
const [isClosing, setIsClosing] = useState(false);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [editName, setEditName] = useState(session.name);
|
||||
const [showContextMenu, setShowContextMenu] = useState(false);
|
||||
const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 });
|
||||
const [gitStatus, setGitStatus] = useState<GitStatus | undefined>(session.gitStatus);
|
||||
const { menuState, openMenu, closeMenu, isMenuOpen } = useContextMenu();
|
||||
const [showArchiveConfirm, setShowArchiveConfirm] = useState(false);
|
||||
const [showRunScriptConfig, setShowRunScriptConfig] = useState(false);
|
||||
const [showNimbalystInstall, setShowNimbalystInstall] = useState(false);
|
||||
const [gitStatusLoading, setGitStatusLoading] = useState(false);
|
||||
|
||||
// Force re-render when session status changes
|
||||
const [, forceUpdate] = useState({});
|
||||
|
||||
// Performance optimization: Remove unnecessary subscription
|
||||
// The component already receives the session as a prop, which will cause re-render when it changes
|
||||
// No need for an additional store subscription that runs for every session item on every store change
|
||||
|
||||
// Sync git status loading state from store
|
||||
useEffect(() => {
|
||||
// Subscribe to session updates to ensure UI updates when this session's status changes
|
||||
const unsubscribe = useSessionStore.subscribe((state) => {
|
||||
const updatedSession = state.sessions.find(s => s.id === session.id) ||
|
||||
(state.activeMainRepoSession?.id === session.id ? state.activeMainRepoSession : null);
|
||||
|
||||
if (updatedSession && updatedSession.status !== session.status) {
|
||||
forceUpdate({});
|
||||
}
|
||||
});
|
||||
|
||||
// Also listen for custom session status change events
|
||||
const handleStatusChange = (event: CustomEvent) => {
|
||||
if (event.detail.sessionId === session.id) {
|
||||
forceUpdate({});
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('session-status-changed', handleStatusChange as EventListener);
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
window.removeEventListener('session-status-changed', handleStatusChange as EventListener);
|
||||
};
|
||||
}, [session.id, session.status]);
|
||||
const loading = useSessionStore.getState().isGitStatusLoading(session.id);
|
||||
setGitStatusLoading(loading);
|
||||
}, [session.id]);
|
||||
|
||||
useEffect(() => {
|
||||
// Check if this session's project has a run script
|
||||
@ -66,26 +63,25 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
|
||||
checkRunScript();
|
||||
|
||||
// Listen for project updates
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
|
||||
if (window.electronAPI?.events?.onProjectUpdated) {
|
||||
unsubscribe = window.electronAPI.events.onProjectUpdated((project) => {
|
||||
// Check if this session belongs to the updated project
|
||||
if (session.projectId === project.id) {
|
||||
// Re-check if the run script exists for this session
|
||||
checkRunScript();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (unsubscribe) {
|
||||
unsubscribe();
|
||||
// Listen for custom project update events from the global useIPCEvents hook
|
||||
const handleProjectUpdate = (event: CustomEvent) => {
|
||||
const project = event.detail;
|
||||
// Check if this session belongs to the updated project
|
||||
if (session.projectId === project.id) {
|
||||
// Re-check if the run script exists for this session
|
||||
checkRunScript();
|
||||
}
|
||||
};
|
||||
}, [session.id, session.projectId]);
|
||||
|
||||
window.addEventListener('project-updated', handleProjectUpdate as EventListener);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('project-updated', handleProjectUpdate as EventListener);
|
||||
};
|
||||
// Only re-run when the actual session ID changes to prevent memory leaks
|
||||
}, [session.id]);
|
||||
|
||||
// Combine script-related effects
|
||||
useEffect(() => {
|
||||
// Check if this session is currently running
|
||||
API.sessions.getRunningSession()
|
||||
@ -95,37 +91,85 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
}
|
||||
})
|
||||
.catch(console.error);
|
||||
}, [session.id]);
|
||||
|
||||
useEffect(() => {
|
||||
// Listen for script session changes
|
||||
const handleScriptSessionChange = (event: CustomEvent) => {
|
||||
setIsRunning(event.detail === session.id);
|
||||
};
|
||||
|
||||
window.addEventListener('script-session-changed', handleScriptSessionChange as EventListener);
|
||||
return () => {
|
||||
window.removeEventListener('script-session-changed', handleScriptSessionChange as EventListener);
|
||||
};
|
||||
}, [session.id]);
|
||||
|
||||
useEffect(() => {
|
||||
// Listen for script closing state
|
||||
const handleScriptClosing = (event: CustomEvent) => {
|
||||
setIsClosing(event.detail === session.id);
|
||||
};
|
||||
|
||||
window.addEventListener('script-session-changed', handleScriptSessionChange as EventListener);
|
||||
window.addEventListener('script-closing', handleScriptClosing as EventListener);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('script-session-changed', handleScriptSessionChange as EventListener);
|
||||
window.removeEventListener('script-closing', handleScriptClosing as EventListener);
|
||||
};
|
||||
}, [session.id]);
|
||||
|
||||
const handleRunScript = async (e: React.MouseEvent) => {
|
||||
useEffect(() => {
|
||||
// Optimized git status fetching - rely on centralized smart polling instead of individual fetches
|
||||
const fetchGitStatusIfNeeded = async () => {
|
||||
// Only fetch if we don't have git status yet and session is active/viable
|
||||
if (!session.archived && session.status !== 'error' && !gitStatus && !session.gitStatus) {
|
||||
try {
|
||||
setGitStatusLoading(true);
|
||||
// Use queue-based initial load to prevent overwhelming the system
|
||||
const response = await window.electronAPI.invoke('sessions:get-git-status', session.id, false, true);
|
||||
if (response.success && response.gitStatus) {
|
||||
setGitStatus(response.gitStatus);
|
||||
}
|
||||
setGitStatusLoading(false);
|
||||
} catch (error) {
|
||||
console.warn('Error fetching initial git status:', error);
|
||||
setGitStatusLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Use session.gitStatus if available, or fetch only once if needed
|
||||
if (session.gitStatus) {
|
||||
setGitStatus(session.gitStatus);
|
||||
} else {
|
||||
fetchGitStatusIfNeeded();
|
||||
}
|
||||
|
||||
// Listen for custom git status events from the global useIPCEvents hook
|
||||
const handleGitStatusUpdate = (event: CustomEvent) => {
|
||||
const { sessionId, gitStatus } = event.detail;
|
||||
if (sessionId === session.id) {
|
||||
setGitStatus(gitStatus);
|
||||
setGitStatusLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for git status loading events to show immediate feedback
|
||||
const handleGitStatusLoading = (event: CustomEvent) => {
|
||||
const { sessionId } = event.detail;
|
||||
if (sessionId === session.id) {
|
||||
setGitStatusLoading(true);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('git-status-updated', handleGitStatusUpdate as EventListener);
|
||||
window.addEventListener('git-status-loading', handleGitStatusLoading as EventListener);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('git-status-updated', handleGitStatusUpdate as EventListener);
|
||||
window.removeEventListener('git-status-loading', handleGitStatusLoading as EventListener);
|
||||
};
|
||||
// Reduced dependency array to prevent excessive re-runs
|
||||
}, [session.id, session.archived, session.status, session.gitStatus]);
|
||||
|
||||
const handleRunScript = useCallback(async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
|
||||
if (!hasRunScript) {
|
||||
alert('No run script configured for this project.\n\nRun scripts are the commands needed to run your application so you can easily test changes.\n\nTo configure a run script:\n1. Click the settings icon (⚙️) next to your project (only shows on hover)\n\n2. Enter your \'Build Script\' to run at worktree creation (Optional)\n\n3. Enter your run script command(s) to run your application for testing');
|
||||
setShowRunScriptConfig(true);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -144,8 +188,8 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
// Clear closing state after stop completes
|
||||
window.dispatchEvent(new CustomEvent('script-closing', { detail: null }));
|
||||
|
||||
// Clear any previous script output for this session
|
||||
useSessionStore.getState().clearScriptOutput(session.id);
|
||||
// Note: Script output now goes to logs, not terminal
|
||||
// No need to clear terminal output here
|
||||
|
||||
// Then run the script for this session
|
||||
const response = await API.sessions.runScript(session.id);
|
||||
@ -162,22 +206,20 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
window.dispatchEvent(new CustomEvent('script-closing', { detail: null }));
|
||||
alert('Failed to run script');
|
||||
}
|
||||
};
|
||||
}, [hasRunScript, session.id]);
|
||||
|
||||
const handleStopScript = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
|
||||
try {
|
||||
console.log('Stopping script...');
|
||||
// Set closing state for this session
|
||||
setIsClosing(true);
|
||||
const response = await API.sessions.stopScript();
|
||||
const response = await API.sessions.stopScript(session.id);
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(response.error || 'Failed to stop script');
|
||||
}
|
||||
|
||||
console.log('Script stop request successful');
|
||||
// Clear closing state
|
||||
setIsClosing(false);
|
||||
// Update running state for all sessions
|
||||
@ -192,20 +234,17 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (e: React.MouseEvent) => {
|
||||
const handleDelete = useCallback(async (e: React.MouseEvent) => {
|
||||
e.stopPropagation(); // Prevent selecting the session
|
||||
|
||||
// Prevent deletion if already being deleted
|
||||
if (isDeleting) return;
|
||||
|
||||
const confirmMessage = `Archive session "${session.name}"? This will:\n` +
|
||||
`• Move the session to the archived sessions list\n` +
|
||||
`• Preserve all session history and outputs\n` +
|
||||
(session.isMainRepo ? `• Close the active Claude Code connection` : `• Remove the git worktree (${session.worktreePath?.split('/').pop() || 'worktree'})`);
|
||||
|
||||
const confirmed = window.confirm(confirmMessage);
|
||||
if (!confirmed) return;
|
||||
|
||||
// Show the confirmation dialog
|
||||
setShowArchiveConfirm(true);
|
||||
}, [isDeleting]);
|
||||
|
||||
const handleConfirmArchive = useCallback(async () => {
|
||||
addDeletingSessionId(session.id);
|
||||
try {
|
||||
const response = await API.sessions.delete(session.id);
|
||||
@ -224,7 +263,7 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
} finally {
|
||||
removeDeletingSessionId(session.id);
|
||||
}
|
||||
};
|
||||
}, [isDeleting, session.name, session.id, session.isMainRepo, session.worktreePath, isActive, addDeletingSessionId, removeDeletingSessionId, setActiveSession]);
|
||||
|
||||
const handleSaveEdit = async () => {
|
||||
if (editName.trim() === '') {
|
||||
@ -269,72 +308,101 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
const handleContextMenu = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setContextMenuPosition({ x: e.clientX, y: e.clientY });
|
||||
setShowContextMenu(true);
|
||||
openMenu('session', session, { x: e.clientX, y: e.clientY });
|
||||
};
|
||||
|
||||
const closeContextMenu = () => {
|
||||
setShowContextMenu(false);
|
||||
};
|
||||
|
||||
// Close context menu when clicking outside
|
||||
useEffect(() => {
|
||||
if (showContextMenu) {
|
||||
const handleClick = () => closeContextMenu();
|
||||
document.addEventListener('click', handleClick);
|
||||
return () => document.removeEventListener('click', handleClick);
|
||||
}
|
||||
}, [showContextMenu]);
|
||||
|
||||
const handleRename = () => {
|
||||
closeContextMenu();
|
||||
closeMenu();
|
||||
setEditName(session.name);
|
||||
setIsEditing(true);
|
||||
};
|
||||
|
||||
const handleDeleteFromMenu = () => {
|
||||
closeContextMenu();
|
||||
closeMenu();
|
||||
handleDelete({ stopPropagation: () => {} } as React.MouseEvent);
|
||||
};
|
||||
|
||||
const handleToggleFavorite = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
console.log('[SessionListItem] Toggling favorite for session:', session.id, 'Current status:', session.isFavorite);
|
||||
|
||||
|
||||
try {
|
||||
const response = await API.sessions.toggleFavorite(session.id);
|
||||
console.log('[SessionListItem] Toggle favorite response:', response);
|
||||
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(response.error || 'Failed to toggle favorite status');
|
||||
}
|
||||
|
||||
console.log('[SessionListItem] Successfully toggled favorite status to:', response.data?.isFavorite);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error toggling favorite status:', error);
|
||||
alert('Failed to toggle favorite status');
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenInNimbalyst = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
|
||||
try {
|
||||
// Track button click
|
||||
const sessionIdHash = await AnalyticsService.hashSessionId(session.id);
|
||||
await AnalyticsService.trackNimbalystButtonClicked({
|
||||
session_id_hash: sessionIdHash
|
||||
});
|
||||
|
||||
// Check if Nimbalyst is installed
|
||||
const checkResponse = await window.electronAPI.nimbalyst.checkInstalled();
|
||||
|
||||
if (!checkResponse.success) {
|
||||
throw new Error(checkResponse.error || 'Failed to check Nimbalyst installation');
|
||||
}
|
||||
|
||||
if (!checkResponse.data) {
|
||||
// Track install dialog shown
|
||||
await AnalyticsService.trackNimbalystInstallDialogShown({
|
||||
session_id_hash: sessionIdHash
|
||||
});
|
||||
|
||||
// Show install dialog if not installed
|
||||
setShowNimbalystInstall(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Open the worktree in Nimbalyst
|
||||
const openResponse = await window.electronAPI.nimbalyst.openWorktree(session.worktreePath);
|
||||
|
||||
if (!openResponse.success) {
|
||||
throw new Error(openResponse.error || 'Failed to open worktree in Nimbalyst');
|
||||
}
|
||||
|
||||
// Track successful open
|
||||
await AnalyticsService.trackNimbalystOpened({
|
||||
session_id_hash: sessionIdHash
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error opening in Nimbalyst:', error);
|
||||
alert('Failed to open in Nimbalyst');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`w-full text-left ${isNested ? 'px-2 py-1.5' : 'px-3 py-2'} rounded-md flex items-center space-x-2 transition-all group ${
|
||||
className={cn(
|
||||
'w-full text-left rounded-md flex items-center space-x-2 transition-all group',
|
||||
isNested ? 'px-2 py-1.5 text-sm' : 'px-3 py-2',
|
||||
isActive
|
||||
? 'bg-blue-100 dark:bg-blue-600/20 text-gray-900 dark:text-white shadow-sm ring-1 ring-blue-200 dark:ring-blue-600/30'
|
||||
: 'hover:bg-gray-100 dark:hover:bg-gray-700/50 text-gray-700 dark:text-gray-300 hover:shadow-sm'
|
||||
} ${isNested ? 'text-sm' : ''}`}
|
||||
? 'bg-interactive/20 text-text-primary shadow-sm ring-1 ring-interactive/20 dark:ring-interactive/30'
|
||||
: 'hover:bg-surface-hover text-text-secondary hover:shadow-sm'
|
||||
)}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
<button
|
||||
onClick={() => {
|
||||
console.log('[SessionListItem] Clicking session:', session.id, session.name);
|
||||
setActiveSession(session.id);
|
||||
navigateToSessions();
|
||||
}}
|
||||
className="flex items-center justify-start space-x-3 flex-1 min-w-0"
|
||||
>
|
||||
<StatusIndicator session={session} size="small" />
|
||||
{isEditing ? (
|
||||
<input
|
||||
type="text"
|
||||
@ -343,19 +411,30 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
onKeyDown={handleKeyDown}
|
||||
onBlur={handleSaveEdit}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="flex-1 text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white px-2 py-1 rounded border border-gray-300 dark:border-gray-600 focus:border-blue-500 focus:outline-none"
|
||||
className="flex-1 text-sm bg-surface-primary text-text-primary px-2 py-1 rounded border border-border-primary focus:border-interactive focus:outline-none focus:ring-2 focus:ring-interactive/20"
|
||||
autoFocus
|
||||
/>
|
||||
) : (
|
||||
<span className={`flex-1 truncate text-sm text-left ${isActive || session.status === 'completed_unviewed' ? 'font-semibold' : ''} ${session.status === 'completed_unviewed' ? 'text-blue-700 dark:text-blue-300' : ''}`} title={session.name}>
|
||||
{session.name}
|
||||
<span className={cn(
|
||||
'flex-1 truncate text-sm text-left flex items-center gap-2',
|
||||
(isActive || session.status === 'completed_unviewed') && 'font-semibold',
|
||||
session.status === 'completed_unviewed' && 'text-interactive'
|
||||
)} title={session.name}>
|
||||
{(gitStatus || gitStatusLoading) && !session.archived && (
|
||||
<GitStatusIndicator gitStatus={gitStatus} size="small" sessionId={session.id} isLoading={gitStatusLoading} />
|
||||
)}
|
||||
<StatusIndicator session={session} size="small" />
|
||||
<span className="ml-1">{session.name}</span>
|
||||
{!!session.isMainRepo && (
|
||||
<span className="ml-1 text-xs text-blue-600 dark:text-blue-400">(main)</span>
|
||||
<span className="ml-1 text-xs text-interactive">(main)</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{!isEditing && (isRunning || isClosing) && (
|
||||
<span className={isClosing ? "text-amber-600 dark:text-amber-400 text-xs" : "text-green-600 dark:text-green-400 text-xs"}>
|
||||
<span className={cn(
|
||||
'text-xs',
|
||||
isClosing ? 'text-status-warning' : 'text-status-success'
|
||||
)}>
|
||||
{isClosing ? '⏸️ Closing' : '▶️ Running'}
|
||||
</span>
|
||||
)}
|
||||
@ -364,34 +443,49 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
{!isEditing && (
|
||||
<>
|
||||
{!session.archived && (
|
||||
<button
|
||||
<IconButton
|
||||
onClick={handleToggleFavorite}
|
||||
className={`p-1 rounded transition-all ${
|
||||
session.isFavorite
|
||||
? 'text-yellow-500 hover:text-yellow-600 dark:text-yellow-400 dark:hover:text-yellow-300'
|
||||
: 'text-gray-400 hover:text-gray-600 dark:text-gray-600 dark:hover:text-gray-400 opacity-0 group-hover:opacity-100'
|
||||
} hover:bg-gray-100 dark:hover:bg-gray-700/50`}
|
||||
title={session.isFavorite ? 'Remove from favorites' : 'Add to favorites'}
|
||||
>
|
||||
<Star
|
||||
className="w-4 h-4"
|
||||
fill={session.isFavorite ? 'currentColor' : 'none'}
|
||||
strokeWidth={session.isFavorite ? 0 : 2}
|
||||
/>
|
||||
</button>
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(
|
||||
'transition-all',
|
||||
session.isFavorite
|
||||
? 'text-status-warning hover:text-status-warning-hover'
|
||||
: 'text-text-tertiary opacity-0 group-hover:opacity-100'
|
||||
)}
|
||||
aria-label={session.isFavorite ? 'Remove from favorites' : 'Add to favorites'}
|
||||
icon={
|
||||
<Star
|
||||
className="w-4 h-4"
|
||||
fill={session.isFavorite ? 'currentColor' : 'none'}
|
||||
strokeWidth={session.isFavorite ? 0 : 2}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!session.archived && (
|
||||
<IconButton
|
||||
onClick={handleOpenInNimbalyst}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-text-tertiary opacity-0 group-hover:opacity-100 transition-opacity hover:text-blue-500"
|
||||
aria-label="Open in Nimbalyst"
|
||||
icon={<NimbalystIcon size={18} className="text-current" />}
|
||||
/>
|
||||
)}
|
||||
{!session.archived && (
|
||||
<button
|
||||
onClick={isRunning ? handleStopScript : handleRunScript}
|
||||
className={`opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded ${
|
||||
className={cn(
|
||||
'opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded',
|
||||
isClosing
|
||||
? 'cursor-wait text-amber-600 dark:text-amber-400'
|
||||
? 'cursor-wait text-status-warning'
|
||||
: isRunning
|
||||
? 'hover:bg-red-100 dark:hover:bg-red-600/20 text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300'
|
||||
? 'hover:bg-status-error/10 text-status-error hover:text-status-error'
|
||||
: hasRunScript
|
||||
? 'hover:bg-green-100 dark:hover:bg-green-600/20 text-green-600 dark:text-green-400 hover:text-green-700 dark:hover:text-green-300'
|
||||
: 'hover:bg-gray-100 dark:hover:bg-gray-600/20 text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400'
|
||||
}`}
|
||||
? 'hover:bg-status-success/10 text-status-success hover:text-status-success'
|
||||
: 'hover:bg-surface-hover text-text-tertiary hover:text-text-secondary'
|
||||
)}
|
||||
title={isClosing ? 'Closing script...' : isRunning ? 'Stop script' : (hasRunScript ? 'Run script' : 'No run script configured - Click to configure')}
|
||||
disabled={isClosing}
|
||||
>
|
||||
@ -399,20 +493,25 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
</button>
|
||||
)}
|
||||
{!session.archived && (
|
||||
<button
|
||||
<IconButton
|
||||
onClick={handleDelete}
|
||||
disabled={isDeleting}
|
||||
className={`opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded hover:bg-amber-100 dark:hover:bg-amber-600/20 ${
|
||||
isDeleting ? 'cursor-not-allowed' : ''
|
||||
}`}
|
||||
title="Archive session"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<span className="text-gray-600 dark:text-gray-400">⏳</span>
|
||||
) : (
|
||||
<Archive className="w-4 h-4 text-amber-600 dark:text-amber-400 hover:text-amber-700 dark:hover:text-amber-300" />
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(
|
||||
'opacity-0 group-hover:opacity-100 transition-opacity',
|
||||
'hover:bg-status-warning/10',
|
||||
isDeleting && 'cursor-not-allowed'
|
||||
)}
|
||||
</button>
|
||||
aria-label="Archive session"
|
||||
icon={
|
||||
isDeleting ? (
|
||||
<span className="text-text-tertiary">⏳</span>
|
||||
) : (
|
||||
<Archive className="w-4 h-4 text-status-warning hover:text-status-warning" />
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
@ -420,21 +519,21 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
</div>
|
||||
|
||||
{/* Context Menu */}
|
||||
{showContextMenu && (
|
||||
{isMenuOpen('session', session.id) && menuState.position && (
|
||||
<div
|
||||
className="fixed bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg py-1 z-50 min-w-[150px]"
|
||||
style={{ top: contextMenuPosition.y, left: contextMenuPosition.x }}
|
||||
className="context-menu fixed bg-surface-primary border border-border-primary rounded-md shadow-lg py-1 z-50 min-w-[150px]"
|
||||
style={{ top: menuState.position.y, left: menuState.position.x }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
onClick={handleRename}
|
||||
className="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-white"
|
||||
className="w-full text-left px-4 py-2 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary"
|
||||
>
|
||||
Rename
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
closeContextMenu();
|
||||
closeMenu();
|
||||
if (isRunning) {
|
||||
handleStopScript({ stopPropagation: () => {} } as React.MouseEvent);
|
||||
} else {
|
||||
@ -442,23 +541,62 @@ export function SessionListItem({ session, isNested = false }: SessionListItemPr
|
||||
}
|
||||
}}
|
||||
disabled={isClosing}
|
||||
className={`w-full text-left px-4 py-2 text-sm ${
|
||||
isClosing
|
||||
? 'text-gray-400 dark:text-gray-600 cursor-wait'
|
||||
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-white'
|
||||
}`}
|
||||
className={cn(
|
||||
'w-full text-left px-4 py-2 text-sm',
|
||||
isClosing
|
||||
? 'text-text-tertiary cursor-wait'
|
||||
: 'text-text-secondary hover:bg-surface-hover hover:text-text-primary'
|
||||
)}
|
||||
>
|
||||
{isClosing ? 'Closing Script...' : isRunning ? 'Stop Script' : 'Run Script'}
|
||||
</button>
|
||||
<div className="border-t border-gray-200 dark:border-gray-700 my-1" />
|
||||
<div className="border-t border-border-primary my-1" />
|
||||
<button
|
||||
onClick={() => {
|
||||
closeMenu();
|
||||
// Dispatch the discard-and-retry event with session data
|
||||
// The session will be archived only after the new session is created
|
||||
window.dispatchEvent(new CustomEvent('discard-and-retry', {
|
||||
detail: {
|
||||
session,
|
||||
projectId: session.projectId,
|
||||
folderId: session.folderId
|
||||
}
|
||||
}));
|
||||
}}
|
||||
className="w-full text-left px-4 py-2 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary"
|
||||
>
|
||||
Discard and Retry
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDeleteFromMenu}
|
||||
className="w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-red-700 dark:hover:text-red-300"
|
||||
className="w-full text-left px-4 py-2 text-sm text-status-error hover:bg-surface-hover hover:text-status-error"
|
||||
>
|
||||
{session.isMainRepo ? 'Archive' : 'Delete'}
|
||||
Archive
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={showArchiveConfirm}
|
||||
onClose={() => setShowArchiveConfirm(false)}
|
||||
onConfirm={handleConfirmArchive}
|
||||
title={`Archive Session`}
|
||||
message={`Archive session "${session.name}"? This will:\n\n• Move the session to the archived sessions list\n• Preserve all session history and outputs\n${session.isMainRepo ? '• Close the active Claude Code connection' : `• Remove the git worktree locally (${session.worktreePath?.split('/').pop() || 'worktree'})`}`}
|
||||
confirmText="Archive"
|
||||
confirmButtonClass="bg-amber-600 hover:bg-amber-700 text-white"
|
||||
icon={<Archive className="w-6 h-6 text-amber-500 flex-shrink-0" />}
|
||||
/>
|
||||
|
||||
<RunScriptConfigDialog
|
||||
isOpen={showRunScriptConfig}
|
||||
onClose={() => setShowRunScriptConfig(false)}
|
||||
/>
|
||||
|
||||
<NimbalystInstallDialog
|
||||
isOpen={showNimbalystInstall}
|
||||
onClose={() => setShowNimbalystInstall(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
});
|
||||
@ -1,68 +1,467 @@
|
||||
import { useRef, useEffect, useState, memo, useMemo } from 'react';
|
||||
import { useRef, useEffect, useState, memo, useMemo, useCallback } from 'react';
|
||||
import { useSessionStore } from '../stores/sessionStore';
|
||||
import { useNavigationStore } from '../stores/navigationStore';
|
||||
import { JsonMessageView } from './JsonMessageView';
|
||||
import { useSessionHistoryStore } from '../stores/sessionHistoryStore';
|
||||
import { EmptyState } from './EmptyState';
|
||||
import CombinedDiffView from './CombinedDiffView';
|
||||
// import CombinedDiffView from './panels/diff/CombinedDiffView'; // Removed - now in panels
|
||||
import { StravuFileSearch } from './StravuFileSearch';
|
||||
import { Inbox } from 'lucide-react';
|
||||
import '@xterm/xterm/css/xterm.css';
|
||||
import { useSessionView } from '../hooks/useSessionView';
|
||||
import { SessionHeader } from './session/SessionHeader';
|
||||
import { SessionInputWithImages } from './session/SessionInputWithImages';
|
||||
// import { SessionInputWithImages } from './panels/claude/ClaudeInputWithImages'; // Removed - now in panels
|
||||
import { GitErrorDialog } from './session/GitErrorDialog';
|
||||
import { CommitMessageDialog } from './session/CommitMessageDialog';
|
||||
import { PromptNavigation } from './PromptNavigation';
|
||||
import { isDocumentVisible } from '../utils/performanceUtils';
|
||||
import { FileEditor } from './FileEditor';
|
||||
import { ProjectDashboard } from './ProjectDashboard';
|
||||
import { FolderArchiveDialog } from './session/FolderArchiveDialog';
|
||||
// import { FileEditor } from './panels/editor/FileEditor'; // Removed - now in panels
|
||||
import { ProjectView } from './ProjectView';
|
||||
import { API } from '../utils/api';
|
||||
// import { RichOutputWithSidebar } from './panels/claude/RichOutputWithSidebar'; // Removed - now in panels
|
||||
// import { RichOutputSettings } from './panels/claude/RichOutputView'; // Removed - not needed
|
||||
// import { LogsView } from './panels/logPanel/LogsView'; // Removed - now in panels
|
||||
// import { MessagesView } from './panels/claude/MessagesView'; // Removed - now in panels
|
||||
import { usePanelStore } from '../stores/panelStore';
|
||||
import { panelApi } from '../services/panelApi';
|
||||
import { PanelTabBar } from './panels/PanelTabBar';
|
||||
import { PanelContainer } from './panels/PanelContainer';
|
||||
import { SessionProvider } from '../contexts/SessionContext';
|
||||
import { ToolPanel, ToolPanelType } from '../../../shared/types/panels';
|
||||
import { Download, Upload, GitMerge, Code2 } from 'lucide-react';
|
||||
import type { Project } from '../types/project';
|
||||
import { devLog, renderLog } from '../utils/console';
|
||||
|
||||
export const SessionView = memo(() => {
|
||||
const activeSessionId = useSessionStore((state) => state.activeSessionId);
|
||||
const sessions = useSessionStore((state) => state.sessions);
|
||||
const activeMainRepoSession = useSessionStore((state) => state.activeMainRepoSession);
|
||||
const { activeView, activeProjectId } = useNavigationStore();
|
||||
const [animationsEnabled, setAnimationsEnabled] = useState(isDocumentVisible());
|
||||
const [projectData, setProjectData] = useState<Project | null>(null);
|
||||
const [isProjectLoading, setIsProjectLoading] = useState(false);
|
||||
const [isMergingProject, setIsMergingProject] = useState(false);
|
||||
const [sessionProject, setSessionProject] = useState<Project | null>(null);
|
||||
|
||||
// Get active session by subscribing directly to store state
|
||||
// This ensures the component re-renders when git status or other session properties update
|
||||
const activeSession = useSessionStore((state) => {
|
||||
if (!state.activeSessionId) return undefined;
|
||||
// Check main repo session first
|
||||
if (state.activeMainRepoSession && state.activeMainRepoSession.id === state.activeSessionId) {
|
||||
return state.activeMainRepoSession;
|
||||
}
|
||||
// Otherwise look in regular sessions
|
||||
return state.sessions.find(session => session.id === state.activeSessionId);
|
||||
});
|
||||
|
||||
const setActiveSession = useSessionStore(state => state.setActiveSession);
|
||||
|
||||
// Panel store state and actions
|
||||
const {
|
||||
panels,
|
||||
activePanels,
|
||||
setPanels,
|
||||
setActivePanel: setActivePanelInStore,
|
||||
addPanel,
|
||||
removePanel,
|
||||
updatePanelState,
|
||||
} = usePanelStore();
|
||||
|
||||
// History store for navigation
|
||||
const { addToHistory, navigateBack, navigateForward } = useSessionHistoryStore();
|
||||
|
||||
// Load panels when session changes
|
||||
useEffect(() => {
|
||||
const handleVisibilityChange = () => {
|
||||
setAnimationsEnabled(isDocumentVisible());
|
||||
if (activeSession?.id) {
|
||||
devLog.debug('[SessionView] Loading panels for session:', activeSession.id);
|
||||
|
||||
// Always reload panels from database when switching sessions
|
||||
// to ensure we get the latest saved state
|
||||
panelApi.loadPanelsForSession(activeSession.id).then(loadedPanels => {
|
||||
devLog.debug('[SessionView] Loaded panels:', loadedPanels);
|
||||
setPanels(activeSession.id, loadedPanels);
|
||||
});
|
||||
|
||||
panelApi.getActivePanel(activeSession.id).then(activePanel => {
|
||||
console.log('[SessionView] Active panel from backend:', activePanel);
|
||||
if (activePanel) {
|
||||
setActivePanelInStore(activeSession.id, activePanel.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [activeSession?.id, setPanels, setActivePanelInStore]); // Remove panels from deps to avoid skipping reload
|
||||
|
||||
// Listen for panel updates from the backend
|
||||
useEffect(() => {
|
||||
if (!activeSession?.id) return;
|
||||
|
||||
// Handle panel creation events (for logs panel auto-creation)
|
||||
const handlePanelCreated = (panel: ToolPanel) => {
|
||||
console.log('[SessionView] Received panel:created event:', panel);
|
||||
|
||||
// Only add if it's for the current session
|
||||
if (panel.sessionId === activeSession.id) {
|
||||
// Check if panel already exists to prevent duplicates
|
||||
const existingPanels = panels[activeSession.id] || [];
|
||||
const panelExists = existingPanels.some(p => p.id === panel.id);
|
||||
|
||||
if (!panelExists) {
|
||||
console.log('[SessionView] Adding new panel to store:', panel);
|
||||
addPanel(panel);
|
||||
} else {
|
||||
console.log('[SessionView] Panel already exists, not adding duplicate:', panel.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
}, []);
|
||||
const handlePanelUpdated = (updatedPanel: ToolPanel) => {
|
||||
console.log('[SessionView] Received panel:updated event:', updatedPanel);
|
||||
|
||||
// Only update if it's for the current session
|
||||
if (updatedPanel.sessionId === activeSession.id) {
|
||||
console.log('[SessionView] Updating panel in store:', updatedPanel);
|
||||
updatePanelState(updatedPanel);
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for panel events
|
||||
const unsubscribeCreated = window.electronAPI?.events?.onPanelCreated?.(handlePanelCreated);
|
||||
const unsubscribeUpdated = window.electronAPI?.events?.onPanelUpdated?.(handlePanelUpdated);
|
||||
|
||||
// Cleanup
|
||||
return () => {
|
||||
unsubscribeCreated?.();
|
||||
unsubscribeUpdated?.();
|
||||
};
|
||||
}, [activeSession?.id, addPanel, updatePanelState, panels]);
|
||||
|
||||
// Get panels for current session with memoization
|
||||
const sessionPanels = useMemo(
|
||||
() => panels[activeSession?.id || ''] || [],
|
||||
[panels, activeSession?.id]
|
||||
);
|
||||
|
||||
const currentActivePanel = useMemo(
|
||||
() => sessionPanels.find(p => p.id === activePanels[activeSession?.id || '']),
|
||||
[sessionPanels, activePanels, activeSession?.id]
|
||||
);
|
||||
|
||||
const activeSession = activeSessionId
|
||||
? (activeMainRepoSession && activeMainRepoSession.id === activeSessionId
|
||||
? activeMainRepoSession
|
||||
: sessions.find(s => s.id === activeSessionId))
|
||||
: undefined;
|
||||
// Check if session has Claude panels
|
||||
const hasClaudePanels = useMemo(
|
||||
() => sessionPanels.some(panel => panel.type === 'claude'),
|
||||
[sessionPanels]
|
||||
);
|
||||
|
||||
// Track current session/panel in history when they change
|
||||
useEffect(() => {
|
||||
if (activeSession?.id && currentActivePanel?.id) {
|
||||
addToHistory(activeSession.id, currentActivePanel.id);
|
||||
}
|
||||
}, [activeSession?.id, currentActivePanel?.id, addToHistory]);
|
||||
|
||||
// Keyboard shortcuts for navigating history
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// Cmd/Ctrl + Option/Alt + Left/Right arrows for navigation
|
||||
if ((e.metaKey || e.ctrlKey) && e.altKey) {
|
||||
if (e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
const previousEntry = navigateBack();
|
||||
if (previousEntry) {
|
||||
// Navigate to the previous session/panel
|
||||
setActiveSession(previousEntry.sessionId);
|
||||
// Small delay to ensure session is set before panel
|
||||
setTimeout(() => {
|
||||
setActivePanelInStore(previousEntry.sessionId, previousEntry.panelId);
|
||||
panelApi.setActivePanel(previousEntry.sessionId, previousEntry.panelId);
|
||||
}, 50);
|
||||
}
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
e.preventDefault();
|
||||
const nextEntry = navigateForward();
|
||||
if (nextEntry) {
|
||||
// Navigate to the next session/panel
|
||||
setActiveSession(nextEntry.sessionId);
|
||||
// Small delay to ensure session is set before panel
|
||||
setTimeout(() => {
|
||||
setActivePanelInStore(nextEntry.sessionId, nextEntry.panelId);
|
||||
panelApi.setActivePanel(nextEntry.sessionId, nextEntry.panelId);
|
||||
}, 50);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [navigateBack, navigateForward, setActiveSession, setActivePanelInStore]);
|
||||
|
||||
// Debug logging - only in development with verbose enabled
|
||||
renderLog('[SessionView] Session panels:', sessionPanels);
|
||||
renderLog('[SessionView] Active panel ID:', activePanels[activeSession?.id || '']);
|
||||
renderLog('[SessionView] Current active panel:', currentActivePanel);
|
||||
renderLog('[SessionView] Has Claude panels:', hasClaudePanels);
|
||||
|
||||
// FIX: Memoize all callbacks to prevent re-renders
|
||||
const handlePanelSelect = useCallback(
|
||||
async (panel: ToolPanel) => {
|
||||
if (!activeSession) return;
|
||||
|
||||
// Add to history when panel is selected
|
||||
addToHistory(activeSession.id, panel.id);
|
||||
|
||||
setActivePanelInStore(activeSession.id, panel.id);
|
||||
await panelApi.setActivePanel(activeSession.id, panel.id);
|
||||
|
||||
// Clear unviewed content flag when panel is viewed (for AI panels)
|
||||
if (panel.type === 'claude' || panel.type === 'codex') {
|
||||
const customState = panel.state?.customState as { hasUnviewedContent?: boolean; panelStatus?: string } | undefined;
|
||||
if (customState?.hasUnviewedContent || customState?.panelStatus === 'completed_unviewed') {
|
||||
try {
|
||||
await panelApi.clearPanelUnviewedContent(panel.id);
|
||||
} catch (err) {
|
||||
console.error('[SessionView] Failed to clear unviewed content:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
[activeSession, setActivePanelInStore, addToHistory]
|
||||
);
|
||||
|
||||
const handlePanelClose = useCallback(
|
||||
async (panel: ToolPanel) => {
|
||||
if (!activeSession) return;
|
||||
|
||||
// Find next panel to activate
|
||||
const panelIndex = sessionPanels.findIndex(p => p.id === panel.id);
|
||||
const nextPanel = sessionPanels[panelIndex + 1] || sessionPanels[panelIndex - 1];
|
||||
|
||||
// Remove from store first for immediate UI update
|
||||
removePanel(activeSession.id, panel.id);
|
||||
|
||||
// Set next active panel if available
|
||||
if (nextPanel) {
|
||||
setActivePanelInStore(activeSession.id, nextPanel.id);
|
||||
await panelApi.setActivePanel(activeSession.id, nextPanel.id);
|
||||
}
|
||||
|
||||
// Delete on backend
|
||||
await panelApi.deletePanel(panel.id);
|
||||
},
|
||||
[activeSession, sessionPanels, removePanel, setActivePanelInStore]
|
||||
);
|
||||
|
||||
const handlePanelCreate = useCallback(
|
||||
async (type: ToolPanelType) => {
|
||||
if (!activeSession) return;
|
||||
|
||||
// For Codex panels, include the last selected model and thinking level in initial state
|
||||
let initialState: { customState?: unknown } | undefined = undefined;
|
||||
if (type === 'codex') {
|
||||
const savedModel = localStorage.getItem('codex.lastSelectedModel');
|
||||
const savedThinkingLevel = localStorage.getItem('codex.lastSelectedThinkingLevel');
|
||||
|
||||
initialState = {
|
||||
customState: {
|
||||
codexConfig: {
|
||||
model: savedModel || 'auto',
|
||||
modelProvider: 'openai',
|
||||
thinkingLevel: savedThinkingLevel || 'medium',
|
||||
sandboxMode: 'workspace-write',
|
||||
webSearch: false
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const newPanel = await panelApi.createPanel({
|
||||
sessionId: activeSession.id,
|
||||
type,
|
||||
initialState
|
||||
});
|
||||
|
||||
// Immediately add the panel and set it as active
|
||||
// The panel:created event will also fire, but addPanel checks for duplicates
|
||||
addPanel(newPanel);
|
||||
setActivePanelInStore(activeSession.id, newPanel.id);
|
||||
},
|
||||
[activeSession, addPanel, setActivePanelInStore]
|
||||
);
|
||||
|
||||
// Load project data for active session
|
||||
useEffect(() => {
|
||||
const loadSessionProject = async () => {
|
||||
if (activeSession?.projectId) {
|
||||
try {
|
||||
const response = await API.projects.getAll();
|
||||
if (response.success && response.data) {
|
||||
const project = response.data.find((p: Project) => p.id === activeSession.projectId);
|
||||
if (project) {
|
||||
setSessionProject(project);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load session project:', error);
|
||||
}
|
||||
} else {
|
||||
setSessionProject(null);
|
||||
}
|
||||
};
|
||||
loadSessionProject();
|
||||
}, [activeSession?.projectId]);
|
||||
|
||||
// Load project data when activeProjectId changes
|
||||
useEffect(() => {
|
||||
if (activeView === 'project' && activeProjectId) {
|
||||
const loadProjectData = async () => {
|
||||
setIsProjectLoading(true);
|
||||
try {
|
||||
// Get all projects and find the one we need
|
||||
const response = await API.projects.getAll();
|
||||
if (response.success && response.data) {
|
||||
const project = response.data.find((p: Project) => p.id === activeProjectId);
|
||||
if (project) {
|
||||
setProjectData(project);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load project data:', error);
|
||||
} finally {
|
||||
setIsProjectLoading(false);
|
||||
}
|
||||
};
|
||||
loadProjectData();
|
||||
} else {
|
||||
setProjectData(null);
|
||||
}
|
||||
}, [activeView, activeProjectId]);
|
||||
|
||||
const handleProjectGitPull = async () => {
|
||||
if (!activeProjectId || !projectData) return;
|
||||
setIsMergingProject(true);
|
||||
try {
|
||||
// Get or create main repo session for this project
|
||||
const sessionResponse = await API.sessions.getOrCreateMainRepoSession(activeProjectId);
|
||||
if (sessionResponse.success && sessionResponse.data) {
|
||||
const response = await API.sessions.gitPull(sessionResponse.data.id);
|
||||
if (!response.success) {
|
||||
console.error('Git pull failed:', response.error);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to perform git pull:', error);
|
||||
} finally {
|
||||
setIsMergingProject(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleProjectGitPush = async () => {
|
||||
if (!activeProjectId || !projectData) return;
|
||||
setIsMergingProject(true);
|
||||
try {
|
||||
// Get or create main repo session for this project
|
||||
const sessionResponse = await API.sessions.getOrCreateMainRepoSession(activeProjectId);
|
||||
if (sessionResponse.success && sessionResponse.data) {
|
||||
const response = await API.sessions.gitPush(sessionResponse.data.id);
|
||||
if (!response.success) {
|
||||
console.error('Git push failed:', response.error);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to perform git push:', error);
|
||||
} finally {
|
||||
setIsMergingProject(false);
|
||||
}
|
||||
};
|
||||
|
||||
const terminalRef = useRef<HTMLDivElement>(null);
|
||||
const scriptTerminalRef = useRef<HTMLDivElement>(null);
|
||||
// scriptTerminalRef removed - terminals now handled by panels
|
||||
|
||||
const hook = useSessionView(activeSession, terminalRef, scriptTerminalRef);
|
||||
const hook = useSessionView(activeSession, terminalRef);
|
||||
|
||||
// Memoize props to prevent unnecessary re-renders
|
||||
const emptySelectedExecutions = useMemo(() => [], []);
|
||||
const isMainRepo = useMemo(() => activeSession?.isMainRepo || false, [activeSession?.isMainRepo]);
|
||||
// Create branch actions for the panel bar
|
||||
const branchActions = useMemo(() => {
|
||||
if (!activeSession) return [];
|
||||
|
||||
return activeSession.isMainRepo ? [
|
||||
{
|
||||
id: 'pull',
|
||||
label: 'Pull from Remote',
|
||||
icon: Download,
|
||||
onClick: hook.handleGitPull,
|
||||
disabled: hook.isMerging || activeSession.status === 'running' || activeSession.status === 'initializing',
|
||||
variant: 'default' as const,
|
||||
description: hook.gitCommands?.getPullCommand ? `git ${hook.gitCommands.getPullCommand()}` : 'git pull'
|
||||
},
|
||||
{
|
||||
id: 'push',
|
||||
label: 'Push to Remote',
|
||||
icon: Upload,
|
||||
onClick: hook.handleGitPush,
|
||||
disabled: hook.isMerging || activeSession.status === 'running' || activeSession.status === 'initializing',
|
||||
variant: 'success' as const,
|
||||
description: hook.gitCommands?.getPushCommand ? `git ${hook.gitCommands.getPushCommand()}` : 'git push'
|
||||
}
|
||||
] : [
|
||||
{
|
||||
id: 'rebase-from-main',
|
||||
label: `Rebase from ${hook.gitCommands?.mainBranch || 'main'}`,
|
||||
icon: GitMerge,
|
||||
onClick: hook.handleRebaseMainIntoWorktree,
|
||||
disabled: hook.isMerging || activeSession.status === 'running' || activeSession.status === 'initializing' || !hook.hasChangesToRebase,
|
||||
variant: 'default' as const,
|
||||
description: hook.gitCommands?.getRebaseFromMainCommand ? hook.gitCommands.getRebaseFromMainCommand() : `Pulls latest changes from ${hook.gitCommands?.mainBranch || 'main'}`
|
||||
},
|
||||
{
|
||||
id: 'rebase-to-main',
|
||||
label: `Merge to ${hook.gitCommands?.mainBranch || 'main'}`,
|
||||
icon: GitMerge,
|
||||
onClick: hook.handleSquashAndRebaseToMain,
|
||||
disabled: hook.isMerging || activeSession.status === 'running' || activeSession.status === 'initializing' ||
|
||||
(!activeSession.gitStatus?.totalCommits || activeSession.gitStatus?.totalCommits === 0 || activeSession.gitStatus?.ahead === 0),
|
||||
variant: 'success' as const,
|
||||
description: (!activeSession.gitStatus?.totalCommits || activeSession.gitStatus?.totalCommits === 0 || activeSession.gitStatus?.ahead === 0) ?
|
||||
'No commits to merge' :
|
||||
(hook.gitCommands?.getSquashAndRebaseToMainCommand ? hook.gitCommands.getSquashAndRebaseToMainCommand() : `Merges all commits to ${hook.gitCommands?.mainBranch || 'main'} (with safety checks)`)
|
||||
},
|
||||
{
|
||||
id: 'open-ide',
|
||||
label: hook.isOpeningIDE ? 'Opening...' : 'Open in IDE',
|
||||
icon: Code2,
|
||||
onClick: hook.handleOpenIDE,
|
||||
disabled: activeSession.status === 'initializing' || hook.isOpeningIDE || !sessionProject?.open_ide_command,
|
||||
variant: 'default' as const,
|
||||
description: sessionProject?.open_ide_command ? 'Open the worktree in your default IDE' : 'No IDE command configured'
|
||||
}
|
||||
];
|
||||
}, [activeSession, hook.isMerging, hook.gitCommands, hook.hasChangesToRebase, hook.handleGitPull, hook.handleGitPush, hook.handleRebaseMainIntoWorktree, hook.handleSquashAndRebaseToMain, hook.handleOpenIDE, hook.isOpeningIDE, sessionProject?.open_ide_command, activeSession?.gitStatus]);
|
||||
|
||||
// Removed unused variables - now handled by panels
|
||||
|
||||
// Show project view if navigation is set to project
|
||||
if (activeView === 'project' && activeProjectId) {
|
||||
if (isProjectLoading || !projectData) {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-surface-secondary p-6">
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-interactive mx-auto mb-4"></div>
|
||||
<p className="text-text-secondary">Loading project...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Show project dashboard if navigation is set to dashboard
|
||||
if (activeView === 'dashboard' && activeProjectId) {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-gray-50 dark:bg-gray-900 p-6">
|
||||
<ProjectDashboard
|
||||
projectId={activeProjectId}
|
||||
projectName="" // Will be fetched by ProjectDashboard
|
||||
/>
|
||||
</div>
|
||||
<ProjectView
|
||||
projectId={activeProjectId}
|
||||
projectName={projectData.name || 'Project'}
|
||||
onGitPull={handleProjectGitPull}
|
||||
onGitPush={handleProjectGitPush}
|
||||
isMerging={isMergingProject}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!activeSession) {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-gray-50 dark:bg-gray-950">
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-bg-primary">
|
||||
<EmptyState
|
||||
icon={Inbox}
|
||||
title="No Session Selected"
|
||||
@ -74,7 +473,7 @@ export const SessionView = memo(() => {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-gray-50 dark:bg-gray-900">
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-bg-primary">
|
||||
<SessionHeader
|
||||
activeSession={activeSession}
|
||||
isEditingName={hook.isEditingName}
|
||||
@ -83,153 +482,68 @@ export const SessionView = memo(() => {
|
||||
handleNameKeyDown={hook.handleNameKeyDown}
|
||||
handleSaveEditName={hook.handleSaveEditName}
|
||||
handleStartEditName={hook.handleStartEditName}
|
||||
isMerging={hook.isMerging}
|
||||
handleGitPull={hook.handleGitPull}
|
||||
handleGitPush={hook.handleGitPush}
|
||||
handleRebaseMainIntoWorktree={hook.handleRebaseMainIntoWorktree}
|
||||
hasChangesToRebase={hook.hasChangesToRebase}
|
||||
gitCommands={hook.gitCommands}
|
||||
handleSquashAndRebaseToMain={hook.handleSquashAndRebaseToMain}
|
||||
handleOpenIDE={hook.handleOpenIDE}
|
||||
mergeError={hook.mergeError}
|
||||
viewMode={hook.viewMode}
|
||||
setViewMode={hook.setViewMode}
|
||||
unreadActivity={hook.unreadActivity}
|
||||
setUnreadActivity={hook.setUnreadActivity}
|
||||
/>
|
||||
|
||||
{/* Tool Panel Bar - ALWAYS VISIBLE */}
|
||||
<SessionProvider session={activeSession} gitBranchActions={branchActions} isMerging={hook.isMerging}>
|
||||
<PanelTabBar
|
||||
panels={sessionPanels}
|
||||
activePanel={currentActivePanel}
|
||||
onPanelSelect={handlePanelSelect}
|
||||
onPanelClose={handlePanelClose}
|
||||
onPanelCreate={handlePanelCreate}
|
||||
/>
|
||||
</SessionProvider>
|
||||
|
||||
<div className="flex-1 flex relative min-h-0">
|
||||
<div className="flex-1 relative">
|
||||
{hook.isLoadingOutput && (
|
||||
<div className="absolute top-4 left-4 text-gray-600 dark:text-gray-400 z-10">Loading output...</div>
|
||||
)}
|
||||
<div className={`bg-gray-50 dark:bg-black h-full ${hook.viewMode === 'output' ? 'flex flex-col' : 'hidden'} relative`}>
|
||||
<div
|
||||
ref={terminalRef}
|
||||
className="flex-1 min-h-0"
|
||||
/>
|
||||
{(activeSession.status === 'running' || activeSession.status === 'initializing') && (
|
||||
<div className="bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-4 py-2 flex-shrink-0">
|
||||
<div className="flex items-center justify-between text-gray-700 dark:text-gray-300">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex space-x-1">
|
||||
<div className={`w-2 h-2 bg-blue-400 rounded-full ${animationsEnabled ? 'animate-typing-dot' : ''}`}></div>
|
||||
<div className={`w-2 h-2 bg-blue-400 rounded-full ${animationsEnabled ? 'animate-typing-dot' : ''}`} style={{ animationDelay: '0.2s' }}></div>
|
||||
<div className={`w-2 h-2 bg-blue-400 rounded-full ${animationsEnabled ? 'animate-typing-dot' : ''}`} style={{ animationDelay: '0.4s' }}></div>
|
||||
</div>
|
||||
<span className="text-sm font-medium">
|
||||
{activeSession.status === 'initializing' ? 'Starting Claude Code...' : 'Claude is working...'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="text-xs text-gray-600 dark:text-gray-400 font-mono">
|
||||
{activeSession.status === 'initializing' ? '⚡' : hook.formatElapsedTime(hook.elapsedTime)}
|
||||
</div>
|
||||
<button onClick={hook.handleStopSession} className="px-3 py-1 text-xs bg-red-600 hover:bg-red-700 text-white rounded-md">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{hook.loadError && hook.viewMode === 'output' && (
|
||||
<div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-center">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 border border-gray-200 dark:border-gray-700 shadow-lg">
|
||||
<p className="text-gray-700 dark:text-gray-300 mb-2">Failed to load output content</p>
|
||||
<p className="text-gray-600 dark:text-gray-500 text-sm mb-4">{hook.loadError}</p>
|
||||
<button onClick={() => hook.loadOutputContent(activeSession.id)} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
|
||||
Reload Output
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={`h-full ${hook.viewMode === 'messages' ? 'block' : 'hidden'}`}>
|
||||
<JsonMessageView messages={activeSession.jsonMessages || []} />
|
||||
</div>
|
||||
<div className={`h-full ${hook.viewMode === 'changes' ? 'block' : 'hidden'} overflow-hidden`}>
|
||||
<CombinedDiffView
|
||||
sessionId={activeSession.id}
|
||||
selectedExecutions={emptySelectedExecutions}
|
||||
isGitOperationRunning={hook.isMerging}
|
||||
isMainRepo={isMainRepo}
|
||||
isVisible={hook.viewMode === 'changes'}
|
||||
/>
|
||||
</div>
|
||||
<div className={`h-full ${hook.viewMode === 'terminal' ? 'flex flex-col' : 'hidden'} bg-gray-50 dark:bg-black`}>
|
||||
<div className="flex items-center justify-between px-4 py-2 bg-gray-100 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Terminal
|
||||
</div>
|
||||
{!activeSession.archived && (
|
||||
<button
|
||||
onClick={hook.handleClearTerminal}
|
||||
className="p-1.5 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors"
|
||||
title="Clear terminal"
|
||||
>
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
{/* Render panels with smart visibility - keeps critical processes alive */}
|
||||
{sessionPanels.length > 0 && currentActivePanel ? (
|
||||
<SessionProvider session={activeSession} gitBranchActions={branchActions} isMerging={hook.isMerging}>
|
||||
{sessionPanels.map(panel => {
|
||||
const isActive = panel.id === currentActivePanel.id;
|
||||
const shouldKeepAlive = ['terminal', 'claude', 'codex'].includes(panel.type);
|
||||
|
||||
// Only render if active OR if it's a panel type that needs to stay alive
|
||||
if (!isActive && !shouldKeepAlive) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={panel.id}
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
display: isActive ? 'block' : 'none',
|
||||
pointerEvents: isActive ? 'auto' : 'none'
|
||||
}}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
<PanelContainer
|
||||
panel={panel}
|
||||
isActive={isActive}
|
||||
isMainRepo={!!activeSession.isMainRepo}
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{activeSession.archived ? (
|
||||
<div className="flex-1 flex items-center justify-center p-8">
|
||||
<div className="text-center max-w-md">
|
||||
<div className="mb-4">
|
||||
<svg className="w-16 h-16 mx-auto text-gray-400 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">
|
||||
No Terminal History Available
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
This session has been archived. Terminal history is not preserved for archived sessions to save resources.
|
||||
</p>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mt-2">
|
||||
The session outputs and conversation history are still available in the Output and Messages views.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</SessionProvider>
|
||||
) : (
|
||||
<div className="flex-1 flex items-center justify-center text-text-secondary">
|
||||
<div className="text-center p-8">
|
||||
<div className="text-4xl mb-4">⚡</div>
|
||||
<h2 className="text-xl font-semibold mb-2">No Active Panel</h2>
|
||||
<p className="text-sm">Add a tool panel to get started</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={scriptTerminalRef} className="flex-1" />
|
||||
<div className="h-2" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className={`h-full ${hook.viewMode === 'editor' ? 'block' : 'hidden'}`}>
|
||||
<FileEditor sessionId={activeSession.id} />
|
||||
</div>
|
||||
<div className={`h-full ${hook.viewMode === 'dashboard' ? 'flex flex-col p-6' : 'hidden'}`}>
|
||||
{activeSession.projectId && (
|
||||
<ProjectDashboard
|
||||
projectId={activeSession.projectId}
|
||||
projectName={activeSession.name.split(' - ')[0] || 'Project'}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{hook.viewMode === 'output' && (
|
||||
<PromptNavigation
|
||||
sessionId={activeSession.id}
|
||||
onNavigateToPrompt={hook.handleNavigateToPrompt}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{hook.viewMode !== 'terminal' && (
|
||||
{/* Legacy session-level prompt bar removed - now handled by panels */}
|
||||
|
||||
{/* Legacy session-level prompt bar - COMMENTED OUT for Claude panel integration
|
||||
{hook.viewMode !== 'terminal' && !currentActivePanel && (
|
||||
<SessionInputWithImages
|
||||
activeSession={activeSession}
|
||||
viewMode={hook.viewMode}
|
||||
@ -243,10 +557,14 @@ export const SessionView = memo(() => {
|
||||
setShowStravuSearch={hook.setShowStravuSearch}
|
||||
ultrathink={hook.ultrathink}
|
||||
setUltrathink={hook.setUltrathink}
|
||||
handleToggleAutoCommit={hook.handleToggleAutoCommit}
|
||||
gitCommands={hook.gitCommands}
|
||||
handleCompactContext={hook.handleCompactContext}
|
||||
hasConversationHistory={hook.hasConversationHistory}
|
||||
contextCompacted={hook.contextCompacted}
|
||||
handleCancelRequest={hook.handleStopSession}
|
||||
/>
|
||||
)}
|
||||
*/}
|
||||
|
||||
<CommitMessageDialog
|
||||
isOpen={hook.showCommitMessageDialog}
|
||||
@ -258,7 +576,9 @@ export const SessionView = memo(() => {
|
||||
shouldSquash={hook.shouldSquash}
|
||||
setShouldSquash={hook.setShouldSquash}
|
||||
onConfirm={hook.performSquashWithCommitMessage}
|
||||
onMergeAndArchive={hook.performSquashWithCommitMessageAndArchive}
|
||||
isMerging={hook.isMerging}
|
||||
isMergingAndArchiving={hook.isMergingAndArchiving}
|
||||
/>
|
||||
|
||||
<GitErrorDialog
|
||||
@ -274,8 +594,17 @@ export const SessionView = memo(() => {
|
||||
onClose={() => hook.setShowStravuSearch(false)}
|
||||
onFileSelect={hook.handleStravuFileSelect}
|
||||
/>
|
||||
|
||||
<FolderArchiveDialog
|
||||
isOpen={hook.showFolderArchiveDialog}
|
||||
sessionCount={hook.folderSessionCount}
|
||||
onArchiveSessionOnly={hook.handleArchiveSessionOnly}
|
||||
onArchiveEntireFolder={hook.handleArchiveEntireFolder}
|
||||
onCancel={hook.handleCancelFolderArchive}
|
||||
/>
|
||||
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
SessionView.displayName = 'SessionView';
|
||||
SessionView.displayName = 'SessionView';
|
||||
|
||||
@ -4,7 +4,26 @@ import { StravuConnection } from './StravuConnection';
|
||||
import { useNotifications } from '../hooks/useNotifications';
|
||||
import { API } from '../utils/api';
|
||||
import type { AppConfig } from '../types/config';
|
||||
import { Shield, ShieldOff } from 'lucide-react';
|
||||
import { useConfigStore } from '../stores/configStore';
|
||||
import {
|
||||
Shield,
|
||||
ShieldOff,
|
||||
Sun,
|
||||
Moon,
|
||||
Settings as SettingsIcon,
|
||||
Palette,
|
||||
Zap,
|
||||
RefreshCw,
|
||||
FileText,
|
||||
Eye,
|
||||
BarChart3
|
||||
} from 'lucide-react';
|
||||
import { Input, Textarea, Checkbox } from './ui/Input';
|
||||
import { Button } from './ui/Button';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { CollapsibleCard } from './ui/CollapsibleCard';
|
||||
import { SettingsSection } from './ui/SettingsSection';
|
||||
|
||||
interface SettingsProps {
|
||||
isOpen: boolean;
|
||||
@ -19,6 +38,10 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
const [claudeExecutablePath, setClaudeExecutablePath] = useState('');
|
||||
const [defaultPermissionMode, setDefaultPermissionMode] = useState<'approve' | 'ignore'>('ignore');
|
||||
const [autoCheckUpdates, setAutoCheckUpdates] = useState(true);
|
||||
const [devMode, setDevMode] = useState(false);
|
||||
const [additionalPathsText, setAdditionalPathsText] = useState('');
|
||||
const [platform, setPlatform] = useState<string>('darwin');
|
||||
const [enableCrystalFooter, setEnableCrystalFooter] = useState(true);
|
||||
const [notificationSettings, setNotificationSettings] = useState({
|
||||
enabled: true,
|
||||
playSound: true,
|
||||
@ -28,12 +51,18 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
});
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [activeTab, setActiveTab] = useState<'general' | 'notifications' | 'stravu'>('general');
|
||||
const [activeTab, setActiveTab] = useState<'general' | 'notifications' | 'analytics' | 'stravu'>('general');
|
||||
const [analyticsEnabled, setAnalyticsEnabled] = useState(true);
|
||||
const [previousAnalyticsEnabled, setPreviousAnalyticsEnabled] = useState(true);
|
||||
const { updateSettings } = useNotifications();
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
const { fetchConfig: refreshConfigStore } = useConfigStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
fetchConfig();
|
||||
// Get platform for PATH help text
|
||||
window.electronAPI.getPlatform().then(setPlatform);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
@ -49,6 +78,12 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
setClaudeExecutablePath(data.claudeExecutablePath || '');
|
||||
setDefaultPermissionMode(data.defaultPermissionMode || 'ignore');
|
||||
setAutoCheckUpdates(data.autoCheckUpdates !== false); // Default to true
|
||||
setDevMode(data.devMode || false);
|
||||
setEnableCrystalFooter(data.enableCrystalFooter !== false); // Default to true
|
||||
|
||||
// Load additional paths
|
||||
const paths = data.additionalPaths || [];
|
||||
setAdditionalPathsText(paths.join('\n'));
|
||||
|
||||
// Load notification settings
|
||||
if (data.notifications) {
|
||||
@ -56,6 +91,13 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
// Update the useNotifications hook with loaded settings
|
||||
updateSettings(data.notifications);
|
||||
}
|
||||
|
||||
// Load analytics settings
|
||||
if (data.analytics) {
|
||||
const enabled = data.analytics.enabled !== false; // Default to true
|
||||
setAnalyticsEnabled(enabled);
|
||||
setPreviousAnalyticsEnabled(enabled);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Failed to load configuration');
|
||||
}
|
||||
@ -67,14 +109,43 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await API.config.update({
|
||||
verbose,
|
||||
anthropicApiKey,
|
||||
systemPromptAppend: globalSystemPrompt,
|
||||
// Parse the additional paths text into an array
|
||||
const parsedPaths = additionalPathsText
|
||||
.split('\n')
|
||||
.map(p => p.trim())
|
||||
.filter(p => p.length > 0);
|
||||
|
||||
// Track analytics opt-in/opt-out events if the preference changed
|
||||
if (previousAnalyticsEnabled !== analyticsEnabled) {
|
||||
if (analyticsEnabled) {
|
||||
// User opted back in
|
||||
await window.electronAPI.analytics.trackUIEvent({
|
||||
event: 'analytics_opted_in',
|
||||
properties: {}
|
||||
});
|
||||
} else {
|
||||
// User opted out - send final event before disabling
|
||||
await window.electronAPI.analytics.trackUIEvent({
|
||||
event: 'analytics_opted_out',
|
||||
properties: {}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const response = await API.config.update({
|
||||
verbose,
|
||||
anthropicApiKey,
|
||||
systemPromptAppend: globalSystemPrompt,
|
||||
claudeExecutablePath,
|
||||
defaultPermissionMode,
|
||||
autoCheckUpdates,
|
||||
notifications: notificationSettings
|
||||
devMode,
|
||||
enableCrystalFooter,
|
||||
additionalPaths: parsedPaths,
|
||||
notifications: notificationSettings,
|
||||
analytics: {
|
||||
enabled: analyticsEnabled
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
@ -86,6 +157,10 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
|
||||
// Refresh config from server
|
||||
await fetchConfig();
|
||||
|
||||
// Also refresh the global config store
|
||||
await refreshConfigStore();
|
||||
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update configuration');
|
||||
@ -94,54 +169,53 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col 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">
|
||||
<h2 className="text-xl font-bold text-gray-900 dark:text-white">Settings</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300"
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="xl" showCloseButton={false}>
|
||||
<ModalHeader
|
||||
title="Crystal Settings"
|
||||
icon={<SettingsIcon className="w-5 h-5" />}
|
||||
onClose={onClose}
|
||||
/>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
{/* Tabs */}
|
||||
<div className="flex border-b border-gray-200 dark:border-gray-700 mb-6">
|
||||
<ModalBody>
|
||||
{/* Tabs */}
|
||||
<div className="flex border-b border-border-primary mb-8">
|
||||
<button
|
||||
onClick={() => setActiveTab('general')}
|
||||
className={`px-4 py-2 text-sm font-medium ${
|
||||
className={`px-4 py-3 text-sm font-medium transition-colors ${
|
||||
activeTab === 'general'
|
||||
? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300'
|
||||
? 'text-interactive border-b-2 border-interactive bg-interactive/5'
|
||||
: 'text-text-tertiary hover:text-text-primary hover:bg-surface-hover'
|
||||
}`}
|
||||
>
|
||||
General
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('notifications')}
|
||||
className={`px-4 py-2 text-sm font-medium ${
|
||||
className={`px-4 py-3 text-sm font-medium transition-colors ${
|
||||
activeTab === 'notifications'
|
||||
? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300'
|
||||
? 'text-interactive border-b-2 border-interactive bg-interactive/5'
|
||||
: 'text-text-tertiary hover:text-text-primary hover:bg-surface-hover'
|
||||
}`}
|
||||
>
|
||||
Notifications
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('analytics')}
|
||||
className={`px-4 py-3 text-sm font-medium transition-colors ${
|
||||
activeTab === 'analytics'
|
||||
? 'text-interactive border-b-2 border-interactive bg-interactive/5'
|
||||
: 'text-text-tertiary hover:text-text-primary hover:bg-surface-hover'
|
||||
}`}
|
||||
>
|
||||
Analytics
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('stravu')}
|
||||
className={`px-4 py-2 text-sm font-medium ${
|
||||
className={`px-4 py-3 text-sm font-medium transition-colors ${
|
||||
activeTab === 'stravu'
|
||||
? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300'
|
||||
? 'text-interactive border-b-2 border-interactive bg-interactive/5'
|
||||
: 'text-text-tertiary hover:text-text-primary hover:bg-surface-hover'
|
||||
}`}
|
||||
>
|
||||
Stravu Integration
|
||||
@ -149,207 +223,301 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
</div>
|
||||
|
||||
{activeTab === 'general' && (
|
||||
<form id="settings-form" onSubmit={handleSubmit} className="space-y-4">
|
||||
|
||||
<div>
|
||||
<label className="flex items-center space-x-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={verbose}
|
||||
onChange={(e) => setVerbose(e.target.checked)}
|
||||
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">Enable verbose logging</span>
|
||||
</label>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Shows detailed logs for debugging session creation and Claude Code execution
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Theme toggle disabled - dark mode only */}
|
||||
{/* <div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
Theme
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleTheme}
|
||||
className="flex items-center space-x-3 px-4 py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors"
|
||||
<form id="settings-form" onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Appearance */}
|
||||
<CollapsibleCard
|
||||
title="Appearance & Theme"
|
||||
subtitle="Customize how Crystal looks and feels"
|
||||
icon={<Palette className="w-5 h-5" />}
|
||||
defaultExpanded={true}
|
||||
>
|
||||
{theme === 'light' ? (
|
||||
<>
|
||||
<Sun className="w-5 h-5 text-yellow-400" />
|
||||
<span className="text-gray-700 dark:text-gray-100">Light Mode</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Moon className="w-5 h-5 text-blue-400" />
|
||||
<span className="text-gray-700 dark:text-gray-100">Dark Mode</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Toggle between light and dark theme
|
||||
</p>
|
||||
</div> */}
|
||||
|
||||
<div>
|
||||
<label htmlFor="anthropicApiKey" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Anthropic API Key (Optional)
|
||||
</label>
|
||||
<input
|
||||
id="anthropicApiKey"
|
||||
type="password"
|
||||
value={anthropicApiKey}
|
||||
onChange={(e) => setAnthropicApiKey(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-700"
|
||||
placeholder="sk-ant-..."
|
||||
/>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Used for auto-generating session names with AI (NOT for Claude Code itself). If not provided, fallback names will be used.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="globalSystemPrompt" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Global System Prompt (Optional)
|
||||
</label>
|
||||
<textarea
|
||||
id="globalSystemPrompt"
|
||||
value={globalSystemPrompt}
|
||||
onChange={(e) => setGlobalSystemPrompt(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-700"
|
||||
placeholder="Additional instructions to append to every prompt..."
|
||||
rows={3}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
This text will be automatically appended to every initial prompt sent to Claude Code across ALL projects. For project-specific prompts, use the project settings.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Default Permission Mode
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="defaultPermissionMode"
|
||||
value="ignore"
|
||||
checked={defaultPermissionMode === 'ignore'}
|
||||
onChange={(e) => setDefaultPermissionMode(e.target.value as 'ignore' | 'approve')}
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<ShieldOff className="w-4 h-4 text-gray-500 dark:text-gray-400" />
|
||||
<span className="text-sm text-gray-700 dark:text-gray-200">Skip Permissions (Default)</span>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">(faster, less secure)</span>
|
||||
</div>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="defaultPermissionMode"
|
||||
value="approve"
|
||||
checked={defaultPermissionMode === 'approve'}
|
||||
onChange={(e) => setDefaultPermissionMode(e.target.value as 'ignore' | 'approve')}
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4 text-green-500" />
|
||||
<span className="text-sm text-gray-700 dark:text-gray-200">Approve Actions</span>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">(safer, interactive)</span>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-xs text-gray-600 dark:text-gray-500 mt-2">
|
||||
When enabled, Claude will ask for permission before performing potentially dangerous actions. This sets the default for new sessions.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="claudeExecutablePath" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Claude Executable Path (Optional)
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id="claudeExecutablePath"
|
||||
type="text"
|
||||
value={claudeExecutablePath}
|
||||
onChange={(e) => setClaudeExecutablePath(e.target.value)}
|
||||
className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 bg-white"
|
||||
placeholder="/usr/local/bin/claude"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
const result = await API.dialog.openFile({
|
||||
title: 'Select Claude Executable',
|
||||
buttonLabel: 'Select',
|
||||
properties: ['openFile'],
|
||||
filters: [
|
||||
{ name: 'Executables', extensions: ['*'] }
|
||||
]
|
||||
});
|
||||
if (result.success && result.data) {
|
||||
setClaudeExecutablePath(result.data);
|
||||
}
|
||||
}}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
<SettingsSection
|
||||
title="Theme Mode"
|
||||
description="Choose between light and dark theme"
|
||||
icon={theme === 'light' ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
|
||||
>
|
||||
Browse
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Full path to the claude executable. Leave empty to use the claude command from PATH. This is useful if Claude is installed in a non-standard location.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleTheme}
|
||||
className="flex items-center gap-3 px-4 py-3 bg-surface-secondary hover:bg-surface-hover rounded-lg transition-colors border border-border-secondary w-full"
|
||||
>
|
||||
{theme === 'light' ? (
|
||||
<>
|
||||
<Sun className="w-5 h-5 text-status-warning" />
|
||||
<span className="text-text-primary font-medium">Light Mode</span>
|
||||
<span className="ml-auto text-xs text-text-tertiary">Currently active</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Moon className="w-5 h-5 text-interactive" />
|
||||
<span className="text-text-primary font-medium">Dark Mode</span>
|
||||
<span className="ml-auto text-xs text-text-tertiary">Currently active</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</SettingsSection>
|
||||
</CollapsibleCard>
|
||||
|
||||
<div>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1">
|
||||
<label className="flex items-center space-x-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={autoCheckUpdates}
|
||||
onChange={(e) => setAutoCheckUpdates(e.target.checked)}
|
||||
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">Check for updates automatically</span>
|
||||
</label>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Automatically check for new Crystal releases on GitHub every 24 hours. You'll be notified when updates are available.
|
||||
{/* AI Integration */}
|
||||
<CollapsibleCard
|
||||
title="AI Integration"
|
||||
subtitle="Configure Claude integration and smart features"
|
||||
icon={<Zap className="w-5 h-5" />}
|
||||
defaultExpanded={true}
|
||||
>
|
||||
<SettingsSection
|
||||
title="Smart Session Names"
|
||||
description="Let Claude automatically generate meaningful names for your sessions"
|
||||
icon={<FileText className="w-4 h-4" />}
|
||||
>
|
||||
<Input
|
||||
label="Anthropic API Key"
|
||||
type="password"
|
||||
value={anthropicApiKey}
|
||||
onChange={(e) => setAnthropicApiKey(e.target.value)}
|
||||
placeholder="sk-ant-..."
|
||||
fullWidth
|
||||
helperText="Optional: Used only for generating session names. Your main Claude Code API key is separate."
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title="Default Security Mode"
|
||||
description="How Claude should handle potentially risky operations"
|
||||
icon={defaultPermissionMode === 'approve' ? <Shield className="w-4 h-4" /> : <ShieldOff className="w-4 h-4" />}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<label className="flex items-start gap-3 cursor-pointer p-3 rounded-lg hover:bg-surface-hover transition-colors border border-border-secondary">
|
||||
<input
|
||||
type="radio"
|
||||
name="defaultPermissionMode"
|
||||
value="ignore"
|
||||
checked={defaultPermissionMode === 'ignore'}
|
||||
onChange={(e) => setDefaultPermissionMode(e.target.value as 'ignore' | 'approve')}
|
||||
className="text-interactive mt-1"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<ShieldOff className="w-4 h-4 text-text-tertiary" />
|
||||
<span className="text-sm font-medium text-text-primary">Fast & Flexible</span>
|
||||
<span className="ml-auto px-2 py-0.5 text-xs bg-status-warning/20 text-status-warning rounded-full">Default</span>
|
||||
</div>
|
||||
<p className="text-xs text-text-tertiary leading-relaxed">
|
||||
Claude executes commands quickly without asking permission. Great for development workflows.
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
<label className="flex items-start gap-3 cursor-pointer p-3 rounded-lg hover:bg-surface-hover transition-colors border border-border-secondary">
|
||||
<input
|
||||
type="radio"
|
||||
name="defaultPermissionMode"
|
||||
value="approve"
|
||||
checked={defaultPermissionMode === 'approve'}
|
||||
onChange={(e) => setDefaultPermissionMode(e.target.value as 'ignore' | 'approve')}
|
||||
className="text-interactive mt-1"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Shield className="w-4 h-4 text-status-success" />
|
||||
<span className="text-sm font-medium text-text-primary">Secure & Controlled</span>
|
||||
</div>
|
||||
<p className="text-xs text-text-tertiary leading-relaxed">
|
||||
Claude asks for your approval before running potentially risky commands. Safer for production code.
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title="Global Instructions"
|
||||
description="Add custom instructions that apply to all your projects"
|
||||
icon={<FileText className="w-4 h-4" />}
|
||||
>
|
||||
<Textarea
|
||||
label="Global System Prompt"
|
||||
value={globalSystemPrompt}
|
||||
onChange={(e) => setGlobalSystemPrompt(e.target.value)}
|
||||
placeholder="Always use TypeScript... Follow our team's coding standards..."
|
||||
rows={3}
|
||||
fullWidth
|
||||
helperText="These instructions will be added to every Claude session across all projects."
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title="Crystal Attribution"
|
||||
description="Add Crystal branding to commit messages"
|
||||
icon={<FileText className="w-4 h-4" />}
|
||||
>
|
||||
<Checkbox
|
||||
label="Include Crystal footer in commits"
|
||||
checked={enableCrystalFooter}
|
||||
onChange={(e) => setEnableCrystalFooter(e.target.checked)}
|
||||
/>
|
||||
<p className="text-xs text-text-tertiary mt-1">
|
||||
When enabled, commits made through Crystal will include a footer crediting Crystal. This helps others know you're using Crystal for AI-powered development.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const response = await API.checkForUpdates();
|
||||
if (response.success && response.data) {
|
||||
if (response.data.hasUpdate) {
|
||||
// Update will be shown via the version update event
|
||||
} else {
|
||||
alert('You are running the latest version of Crystal!');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to check for updates:', error);
|
||||
alert('Failed to check for updates. Please try again later.');
|
||||
}
|
||||
}}
|
||||
className="ml-4 px-3 py-1 text-sm font-medium text-blue-600 dark:text-blue-500 hover:text-blue-700 dark:hover:text-blue-400 focus:outline-none"
|
||||
</SettingsSection>
|
||||
</CollapsibleCard>
|
||||
|
||||
{/* System Updates */}
|
||||
<CollapsibleCard
|
||||
title="Updates & Maintenance"
|
||||
subtitle="Keep Crystal up to date with the latest features"
|
||||
icon={<RefreshCw className="w-5 h-5" />}
|
||||
defaultExpanded={false}
|
||||
>
|
||||
<SettingsSection
|
||||
title="Automatic Updates"
|
||||
description="Stay current with new features and bug fixes"
|
||||
icon={<RefreshCw className="w-4 h-4" />}
|
||||
>
|
||||
Check Now
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between p-3 bg-surface-secondary rounded-lg border border-border-secondary">
|
||||
<div className="flex items-center gap-3">
|
||||
<Checkbox
|
||||
label="Check for updates automatically"
|
||||
checked={autoCheckUpdates}
|
||||
onChange={(e) => setAutoCheckUpdates(e.target.checked)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const response = await API.checkForUpdates();
|
||||
if (response.success && response.data) {
|
||||
if (response.data.hasUpdate) {
|
||||
// Update will be shown via the version update event
|
||||
} else {
|
||||
alert('You are running the latest version of Crystal!');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to check for updates:', error);
|
||||
alert('Failed to check for updates. Please try again later.');
|
||||
}
|
||||
}}
|
||||
>
|
||||
Check Now
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-text-tertiary mt-2">
|
||||
We check GitHub for new releases every 24 hours. Updates require manual installation.
|
||||
</p>
|
||||
</SettingsSection>
|
||||
</CollapsibleCard>
|
||||
|
||||
{/* Advanced Options */}
|
||||
<CollapsibleCard
|
||||
title="Advanced Options"
|
||||
subtitle="Technical settings for power users"
|
||||
icon={<Eye className="w-5 h-5" />}
|
||||
defaultExpanded={false}
|
||||
variant="subtle"
|
||||
>
|
||||
<SettingsSection
|
||||
title="Debugging"
|
||||
description="Enable detailed logging for troubleshooting"
|
||||
icon={<FileText className="w-4 h-4" />}
|
||||
>
|
||||
<Checkbox
|
||||
label="Enable verbose logging"
|
||||
checked={verbose}
|
||||
onChange={(e) => setVerbose(e.target.checked)}
|
||||
/>
|
||||
<p className="text-xs text-text-tertiary mt-1">
|
||||
Shows detailed logs for session creation and Claude Code execution. Useful for debugging issues.
|
||||
</p>
|
||||
|
||||
<div className="mt-4">
|
||||
<Checkbox
|
||||
label="Enable dev mode"
|
||||
checked={devMode}
|
||||
onChange={(e) => setDevMode(e.target.checked)}
|
||||
/>
|
||||
<p className="text-xs text-text-tertiary mt-1">
|
||||
Adds a "Messages" tab to each session showing raw JSON responses from Claude Code. Useful for debugging and development.
|
||||
</p>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
{error && (
|
||||
<div className="text-red-600 text-sm">{error}</div>
|
||||
)}
|
||||
<SettingsSection
|
||||
title="Additional PATH Directories"
|
||||
description="Add custom directories to the PATH environment variable"
|
||||
icon={<FileText className="w-4 h-4" />}
|
||||
>
|
||||
<Textarea
|
||||
label=""
|
||||
value={additionalPathsText}
|
||||
onChange={(e) => setAdditionalPathsText(e.target.value)}
|
||||
placeholder={
|
||||
platform === 'win32'
|
||||
? "C:\\tools\\bin\nC:\\Program Files\\MyApp\n%USERPROFILE%\\bin"
|
||||
: platform === 'darwin'
|
||||
? "/opt/homebrew/bin\n/usr/local/bin\n~/bin\n~/.cargo/bin"
|
||||
: "/usr/local/bin\n/opt/bin\n~/bin\n~/.local/bin"
|
||||
}
|
||||
rows={4}
|
||||
fullWidth
|
||||
helperText={
|
||||
`Enter one directory path per line. These will be added to PATH for all tools.\n${
|
||||
platform === 'win32'
|
||||
? "Windows: Use backslashes (C:\\path) or forward slashes (C:/path). Environment variables like %USERPROFILE% are supported."
|
||||
: "Unix/macOS: Use forward slashes (/path). The tilde (~) expands to your home directory."
|
||||
}\nNote: Changes require restarting Crystal to take full effect.`
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title="Custom Claude Installation"
|
||||
description="Override the default Claude executable path"
|
||||
icon={<FileText className="w-4 h-4" />}
|
||||
>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id="claudeExecutablePath"
|
||||
type="text"
|
||||
value={claudeExecutablePath}
|
||||
onChange={(e) => setClaudeExecutablePath(e.target.value)}
|
||||
className="flex-1 px-3 py-2 border border-border-primary rounded-md focus:outline-none focus:ring-2 focus:ring-interactive text-text-primary bg-surface-secondary"
|
||||
placeholder="/usr/local/bin/claude"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
const result = await API.dialog.openFile({
|
||||
title: 'Select Claude Executable',
|
||||
buttonLabel: 'Select',
|
||||
properties: ['openFile'],
|
||||
filters: [
|
||||
{ name: 'Executables', extensions: ['*'] }
|
||||
]
|
||||
});
|
||||
if (result.success && result.data) {
|
||||
setClaudeExecutablePath(result.data);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-text-tertiary mt-1">
|
||||
Leave empty to use the 'claude' command from your system PATH.
|
||||
</p>
|
||||
</SettingsSection>
|
||||
</CollapsibleCard>
|
||||
|
||||
{error && (
|
||||
<div className="text-status-error text-sm bg-status-error/10 border border-status-error/30 rounded-lg p-4">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
|
||||
@ -361,65 +529,185 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
{activeTab === 'analytics' && (
|
||||
<form id="analytics-form" onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Analytics Overview */}
|
||||
<CollapsibleCard
|
||||
title="About Analytics"
|
||||
subtitle="Help improve Crystal by sharing anonymous usage data"
|
||||
icon={<BarChart3 className="w-5 h-5" />}
|
||||
defaultExpanded={true}
|
||||
variant="subtle"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-text-secondary leading-relaxed">
|
||||
Crystal collects anonymous usage analytics to understand how the application is used and to help prioritize improvements. All data is completely anonymous and privacy-focused.
|
||||
</p>
|
||||
|
||||
<div className="bg-surface-tertiary rounded-lg p-4 border border-border-secondary">
|
||||
<h4 className="font-medium text-text-primary mb-3 text-sm">✅ What we track:</h4>
|
||||
<ul className="space-y-1 text-xs text-text-secondary">
|
||||
<li>• Feature usage patterns (which features are used)</li>
|
||||
<li>• Session counts and statuses</li>
|
||||
<li>• Git operation types (rebase, squash, etc.)</li>
|
||||
<li>• UI interactions (view switches, button clicks)</li>
|
||||
<li>• Error types (generic categories only)</li>
|
||||
<li>• Performance metrics (categorized durations)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="bg-status-error/10 rounded-lg p-4 border border-status-error/30">
|
||||
<h4 className="font-medium text-text-primary mb-3 text-sm">❌ What we NEVER track:</h4>
|
||||
<ul className="space-y-1 text-xs text-text-secondary">
|
||||
<li>• Your prompts or AI responses</li>
|
||||
<li>• File paths, names, or directory structures</li>
|
||||
<li>• Project names or descriptions</li>
|
||||
<li>• Git commit messages or code diffs</li>
|
||||
<li>• Terminal output or commands</li>
|
||||
<li>• Personal identifiers (emails, usernames, API keys)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-text-tertiary italic">
|
||||
You can opt-out at any time. When disabled, no analytics data will be collected or sent.
|
||||
</p>
|
||||
</div>
|
||||
</CollapsibleCard>
|
||||
|
||||
{/* Analytics Settings */}
|
||||
<CollapsibleCard
|
||||
title="Analytics Settings"
|
||||
subtitle="Configure anonymous usage tracking"
|
||||
icon={<BarChart3 className="w-5 h-5" />}
|
||||
defaultExpanded={true}
|
||||
>
|
||||
<SettingsSection
|
||||
title="Enable Analytics"
|
||||
description="Allow Crystal to collect anonymous usage data to improve the product"
|
||||
icon={<BarChart3 className="w-4 h-4" />}
|
||||
>
|
||||
<Checkbox
|
||||
label="Enable anonymous analytics tracking"
|
||||
checked={analyticsEnabled}
|
||||
onChange={(e) => setAnalyticsEnabled(e.target.checked)}
|
||||
/>
|
||||
{!analyticsEnabled && (
|
||||
<p className="text-xs text-status-warning mt-2">
|
||||
Analytics is disabled. No data will be collected or sent.
|
||||
</p>
|
||||
)}
|
||||
{analyticsEnabled && (
|
||||
<p className="text-xs text-status-success mt-2">
|
||||
Analytics is enabled. Thank you for helping improve Crystal!
|
||||
</p>
|
||||
)}
|
||||
</SettingsSection>
|
||||
</CollapsibleCard>
|
||||
|
||||
{error && (
|
||||
<div className="text-status-error text-sm bg-status-error/10 border border-status-error/30 rounded-lg p-4">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
|
||||
{activeTab === 'stravu' && (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<img
|
||||
src="./stravu-logo.png"
|
||||
alt="Stravu Logo"
|
||||
className="w-16 h-16 object-contain flex-shrink-0"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
|
||||
Stravu - The way AI-first teams collaborate
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
|
||||
Connect Crystal to your Stravu workspace to seamlessly integrate your team's knowledge and documentation into your AI-powered development workflow.
|
||||
{/* Stravu Introduction */}
|
||||
<CollapsibleCard
|
||||
title="About Stravu Integration"
|
||||
subtitle="Connect your team's knowledge to your AI workflow"
|
||||
icon={
|
||||
<img
|
||||
src="./stravu-logo.png"
|
||||
alt="Stravu Logo"
|
||||
className="w-5 h-5 object-contain"
|
||||
/>
|
||||
}
|
||||
defaultExpanded={true}
|
||||
variant="subtle"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-text-secondary leading-relaxed">
|
||||
Stravu is the knowledge platform for AI-first teams. Connect Crystal to your Stravu workspace to give Claude access to your team's documentation, best practices, and institutional knowledge.
|
||||
</p>
|
||||
<a
|
||||
href="https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 text-sm font-medium inline-flex items-center gap-1"
|
||||
>
|
||||
Learn more about Stravu
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t border-gray-700 pt-6">
|
||||
<StravuConnection />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
|
||||
<div className="p-3 bg-surface-tertiary rounded-lg">
|
||||
<h4 className="font-medium text-text-primary mb-1">🚀 Smart Context</h4>
|
||||
<p className="text-text-tertiary">Claude automatically pulls relevant docs and standards</p>
|
||||
</div>
|
||||
<div className="p-3 bg-surface-tertiary rounded-lg">
|
||||
<h4 className="font-medium text-text-primary mb-1">👥 Team Alignment</h4>
|
||||
<p className="text-text-tertiary">Ensure AI follows your team's patterns and conventions</p>
|
||||
</div>
|
||||
<div className="p-3 bg-surface-tertiary rounded-lg">
|
||||
<h4 className="font-medium text-text-primary mb-1">📚 Knowledge Base</h4>
|
||||
<p className="text-text-tertiary">Surface relevant documentation during development</p>
|
||||
</div>
|
||||
<div className="p-3 bg-surface-tertiary rounded-lg">
|
||||
<h4 className="font-medium text-text-primary mb-1">🔄 Always Current</h4>
|
||||
<p className="text-text-tertiary">Real-time sync with your latest team knowledge</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
{(activeTab === 'general' || activeTab === 'notifications') && (
|
||||
<div className="flex justify-end space-x-3 p-6 border-t border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
|
||||
disabled={isSubmitting}
|
||||
<div className="flex items-center justify-between pt-2 border-t border-border-secondary">
|
||||
<a
|
||||
href="https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-interactive hover:text-interactive-hover text-sm inline-flex items-center gap-2 font-medium transition-colors"
|
||||
>
|
||||
Learn more about Stravu
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
</a>
|
||||
<span className="text-xs text-text-tertiary">
|
||||
Made by the Crystal team
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleCard>
|
||||
|
||||
{/* Connection Management */}
|
||||
<CollapsibleCard
|
||||
title="Connection Management"
|
||||
subtitle="Connect and manage your Stravu workspace integration"
|
||||
icon={<Zap className="w-5 h-5" />}
|
||||
defaultExpanded={true}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type={activeTab === 'general' ? 'submit' : 'button'}
|
||||
form={activeTab === 'general' ? 'settings-form' : undefined}
|
||||
onClick={activeTab === 'notifications' ? (e) => handleSubmit(e as any) : undefined}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 transition-colors"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Saving...' : 'Save'}
|
||||
</button>
|
||||
<StravuConnection />
|
||||
</CollapsibleCard>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
{/* Footer */}
|
||||
{(activeTab === 'general' || activeTab === 'notifications' || activeTab === 'analytics') && (
|
||||
<ModalFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={onClose}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type={activeTab === 'general' ? 'submit' : 'button'}
|
||||
form={activeTab === 'general' ? 'settings-form' : undefined}
|
||||
onClick={activeTab === 'notifications' ? (e) => handleSubmit(e as React.FormEvent) : undefined}
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
variant="primary"
|
||||
>
|
||||
Save Changes
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -1,8 +1,11 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Settings } from './Settings';
|
||||
import { DraggableProjectTreeView } from './DraggableProjectTreeView';
|
||||
import { Info, Clock } from 'lucide-react';
|
||||
import { ArchiveProgress } from './ArchiveProgress';
|
||||
import { Info, Clock, Check, Edit, CircleArrowDown, AlertTriangle, GitMerge, ArrowUpDown } from 'lucide-react';
|
||||
import crystalLogo from '../assets/crystal-logo.svg';
|
||||
import { IconButton } from './ui/Button';
|
||||
import { Modal, ModalHeader, ModalBody } from './ui/Modal';
|
||||
|
||||
interface SidebarProps {
|
||||
onHelpClick: () => void;
|
||||
@ -17,33 +20,70 @@ export function Sidebar({ onHelpClick, onAboutClick, onPromptHistoryClick, width
|
||||
const [showStatusGuide, setShowStatusGuide] = useState(false);
|
||||
const [version, setVersion] = useState<string>('');
|
||||
const [gitCommit, setGitCommit] = useState<string>('');
|
||||
const [worktreeName, setWorktreeName] = useState<string>('');
|
||||
const [sessionSortAscending, setSessionSortAscending] = useState<boolean>(false); // Default to descending (newest first)
|
||||
|
||||
useEffect(() => {
|
||||
// Fetch version info on component mount
|
||||
// Fetch version info and UI state on component mount
|
||||
const fetchVersion = async () => {
|
||||
try {
|
||||
console.log('[Sidebar Debug] Fetching version info...');
|
||||
const result = await window.electronAPI.getVersionInfo();
|
||||
console.log('[Sidebar Debug] Version info result:', result);
|
||||
if (result.success && result.data) {
|
||||
console.log('[Sidebar Debug] Version data:', result.data);
|
||||
if (result.data.current) {
|
||||
setVersion(result.data.current);
|
||||
console.log('[Sidebar Debug] Set version:', result.data.current);
|
||||
}
|
||||
if (result.data.gitCommit) {
|
||||
setGitCommit(result.data.gitCommit);
|
||||
console.log('[Sidebar Debug] Set gitCommit:', result.data.gitCommit);
|
||||
}
|
||||
if (result.data.worktreeName) {
|
||||
setWorktreeName(result.data.worktreeName);
|
||||
console.log('[Sidebar Debug] Set worktreeName:', result.data.worktreeName);
|
||||
} else {
|
||||
console.log('[Sidebar Debug] No worktreeName in response');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch version:', error);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const loadUIState = async () => {
|
||||
try {
|
||||
const result = await window.electronAPI.uiState.getExpanded();
|
||||
if (result.success && result.data) {
|
||||
setSessionSortAscending(result.data.sessionSortAscending ?? false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load UI state:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchVersion();
|
||||
loadUIState();
|
||||
}, []);
|
||||
|
||||
const toggleSessionSortOrder = async () => {
|
||||
const newValue = !sessionSortAscending;
|
||||
setSessionSortAscending(newValue);
|
||||
|
||||
// Save to database via electronAPI
|
||||
try {
|
||||
await window.electronAPI.uiState.saveSessionSortAscending(newValue);
|
||||
} catch (error) {
|
||||
console.error('Failed to save session sort order:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
data-testid="sidebar"
|
||||
className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white h-full flex flex-col pt-4 relative flex-shrink-0 border-r border-gray-200 dark:border-gray-700"
|
||||
className="bg-surface-primary text-text-primary h-full flex flex-col pt-4 relative flex-shrink-0 border-r border-border-primary"
|
||||
style={{ width: `${width}px` }}
|
||||
>
|
||||
{/* Resize handle */}
|
||||
@ -52,178 +92,263 @@ export function Sidebar({ onHelpClick, onAboutClick, onPromptHistoryClick, width
|
||||
onMouseDown={onResize}
|
||||
>
|
||||
{/* Visual indicator */}
|
||||
<div className="absolute inset-0 bg-gray-300 dark:bg-gray-700 group-hover:bg-blue-500 transition-colors" />
|
||||
<div className="absolute inset-0 bg-border-secondary group-hover:bg-interactive transition-colors" />
|
||||
{/* Larger grab area */}
|
||||
<div className="absolute -left-2 -right-2 top-0 bottom-0" />
|
||||
{/* Drag indicator dots */}
|
||||
<div className="absolute top-1/2 -translate-y-1/2 right-0 transform translate-x-1/2 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="w-1 h-1 bg-blue-400 rounded-full" />
|
||||
<div className="w-1 h-1 bg-blue-400 rounded-full" />
|
||||
<div className="w-1 h-1 bg-blue-400 rounded-full" />
|
||||
<div className="w-1 h-1 bg-interactive rounded-full" />
|
||||
<div className="w-1 h-1 bg-interactive rounded-full" />
|
||||
<div className="w-1 h-1 bg-interactive rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between overflow-hidden">
|
||||
<div className="p-4 border-b border-border-primary flex items-center justify-between overflow-hidden">
|
||||
<div className="flex items-center space-x-2 min-w-0">
|
||||
<img src={crystalLogo} alt="Crystal" className="h-6 w-6 flex-shrink-0" />
|
||||
<h1 className="text-xl font-bold truncate">Crystal</h1>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2 flex-shrink-0">
|
||||
<button
|
||||
<IconButton
|
||||
onClick={onHelpClick}
|
||||
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
|
||||
title="Help"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
aria-label="Help"
|
||||
size="md"
|
||||
icon={
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
<IconButton
|
||||
onClick={() => setIsSettingsOpen(true)}
|
||||
aria-label="Settings"
|
||||
data-testid="settings-button"
|
||||
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
|
||||
title="Settings"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
size="md"
|
||||
icon={
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0">
|
||||
<div className="px-4 py-2 text-sm uppercase flex items-center justify-between overflow-hidden">
|
||||
<span className="truncate text-gray-700 dark:text-gray-400">Projects & Sessions</span>
|
||||
<span className="truncate text-text-tertiary">Projects & Sessions</span>
|
||||
<div className="flex items-center space-x-1">
|
||||
<button
|
||||
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
|
||||
title="View Prompt History (Cmd/Ctrl + P)"
|
||||
<IconButton
|
||||
aria-label={sessionSortAscending ? "Sort sessions: Oldest first (click to reverse)" : "Sort sessions: Newest first (click to reverse)"}
|
||||
size="sm"
|
||||
onClick={toggleSessionSortOrder}
|
||||
icon={<ArrowUpDown className="w-4 h-4" />}
|
||||
/>
|
||||
<IconButton
|
||||
aria-label="View Prompt History (Cmd/Ctrl + P)"
|
||||
size="sm"
|
||||
onClick={onPromptHistoryClick}
|
||||
>
|
||||
<Clock className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
|
||||
title="View status legend"
|
||||
icon={<Clock className="w-4 h-4" />}
|
||||
/>
|
||||
<IconButton
|
||||
aria-label="View status legend"
|
||||
size="sm"
|
||||
onClick={() => setShowStatusGuide(true)}
|
||||
>
|
||||
<Info className="w-4 h-4" />
|
||||
</button>
|
||||
icon={<Info className="w-4 h-4" />}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DraggableProjectTreeView />
|
||||
<DraggableProjectTreeView sessionSortAscending={sessionSortAscending} />
|
||||
</div>
|
||||
|
||||
{/* Version display at bottom */}
|
||||
{version && (
|
||||
<div className="px-4 py-2 border-t border-gray-200 dark:border-gray-700">
|
||||
<div
|
||||
className="text-xs text-gray-500 dark:text-gray-500 text-center cursor-pointer hover:text-gray-700 dark:hover:text-gray-400 transition-colors"
|
||||
onClick={onAboutClick}
|
||||
title="Click to view version details"
|
||||
>
|
||||
v{version}{gitCommit && ` • ${gitCommit}`}
|
||||
{/* Bottom section - always visible */}
|
||||
<div className="flex-shrink-0">
|
||||
{/* Archive progress indicator above version */}
|
||||
<ArchiveProgress />
|
||||
|
||||
{/* Version display at bottom */}
|
||||
{version && (
|
||||
<div className="px-4 py-2 border-t border-border-primary">
|
||||
<div
|
||||
className="text-xs text-text-tertiary text-center cursor-pointer hover:text-text-secondary transition-colors truncate"
|
||||
onClick={onAboutClick}
|
||||
title="Click to view version details"
|
||||
>
|
||||
v{version}{worktreeName && ` • ${worktreeName}`}{gitCommit && ` • ${gitCommit}`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Settings isOpen={isSettingsOpen} onClose={() => setIsSettingsOpen(false)} />
|
||||
|
||||
{/* Status Guide Modal */}
|
||||
{showStatusGuide && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onClick={() => setShowStatusGuide(false)}>
|
||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-xl p-6 max-w-md w-full mx-4" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">Status Indicators Guide</h3>
|
||||
<button
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
|
||||
onClick={() => setShowStatusGuide(false)}
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<Modal
|
||||
isOpen={showStatusGuide}
|
||||
onClose={() => setShowStatusGuide(false)}
|
||||
size="lg"
|
||||
>
|
||||
<ModalHeader>Status Indicators Guide</ModalHeader>
|
||||
<ModalBody>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Project Indicators */}
|
||||
<div className="pb-3 border-b border-gray-200 dark:border-gray-700">
|
||||
<h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">Project Indicators</h4>
|
||||
<div className="pb-3 border-b border-border-primary">
|
||||
<h4 className="text-sm font-medium text-text-primary mb-2">Project Indicators</h4>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative">
|
||||
<svg className="w-4 h-4 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2">
|
||||
<svg className="w-4 h-4 text-interactive" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2">
|
||||
<path d="M6 3v12M6 3a9 9 0 0 0 9 9m-9-9a9 9 0 0 1 9 9m0-9h12" />
|
||||
</svg>
|
||||
<div className="absolute -bottom-0.5 -right-0.5 w-2 h-2 bg-green-500 rounded-full"></div>
|
||||
<div className="absolute -bottom-0.5 -right-0.5 w-2 h-2 bg-status-success rounded-full"></div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-700 dark:text-gray-200 font-medium">Git Project</span>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">Project connected to a git repository</p>
|
||||
<span className="text-text-secondary font-medium">Git Project</span>
|
||||
<p className="text-text-tertiary text-sm">Project connected to a git repository</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Session Status Indicators */}
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">Session Status</h4>
|
||||
<div className="pb-3 border-b border-border-primary">
|
||||
<h4 className="text-sm font-medium text-text-primary mb-2">Session Status</h4>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-green-500 rounded-full animate-pulse flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-gray-700 dark:text-gray-200 font-medium">Initializing</span>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">Setting up git worktree and environment</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-status-success rounded-full animate-pulse flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-text-secondary font-medium">Initializing</span>
|
||||
<p className="text-text-tertiary text-sm">Setting up git worktree and environment</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-status-success rounded-full animate-pulse flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-text-secondary font-medium">Running</span>
|
||||
<p className="text-text-tertiary text-sm">Claude is actively processing your request</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-status-warning rounded-full animate-pulse flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-text-secondary font-medium">Waiting</span>
|
||||
<p className="text-text-tertiary text-sm">Claude needs your input to continue</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-status-neutral rounded-full flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-text-secondary font-medium">Completed</span>
|
||||
<p className="text-text-tertiary text-sm">Task finished successfully</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-status-info rounded-full animate-pulse flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-text-secondary font-medium">New Activity</span>
|
||||
<p className="text-text-tertiary text-sm">Session has new unviewed results</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-status-error rounded-full flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-text-secondary font-medium">Error</span>
|
||||
<p className="text-text-tertiary text-sm">Something went wrong with the session</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-green-500 rounded-full animate-pulse flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-gray-700 dark:text-gray-200 font-medium">Running</span>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">Claude is actively processing your request</p>
|
||||
{/* Git Status Indicators */}
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-text-primary mb-2">Git Status Indicators</h4>
|
||||
<p className="text-text-tertiary text-sm mb-3">Click any indicator to view detailed changes in the Diff panel</p>
|
||||
|
||||
{/* HIGH PRIORITY */}
|
||||
<div className="mb-3">
|
||||
<p className="text-xs font-medium text-text-tertiary mb-2">HIGH PRIORITY</p>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-3 p-2 rounded">
|
||||
<span className="inline-flex items-center justify-center gap-0.5 w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-status-success/10 text-status-success border-border-primary">
|
||||
<GitMerge className="w-3.5 h-3.5" strokeWidth={2} />
|
||||
<span className="font-bold">3</span>
|
||||
</span>
|
||||
<span className="text-xs text-text-secondary"><strong>Ready to Merge</strong> - Changes ready to merge cleanly</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 p-2 rounded">
|
||||
<span className="inline-flex items-center justify-center gap-0.5 w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-status-warning/10 text-status-warning border-border-primary">
|
||||
<AlertTriangle className="w-3.5 h-3.5" strokeWidth={2} />
|
||||
<span className="font-bold">2</span>
|
||||
</span>
|
||||
<span className="text-xs text-text-secondary"><strong>Conflict Risk</strong> - Behind main, potential conflicts</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-amber-500 rounded-full animate-pulse flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-gray-700 dark:text-gray-200 font-medium">Waiting</span>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">Claude needs your input to continue</p>
|
||||
|
||||
{/* SPECIAL CASES */}
|
||||
<div className="mb-3">
|
||||
<p className="text-xs font-medium text-text-tertiary mb-2">SPECIAL CASES</p>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-3 p-2 rounded">
|
||||
<span className="inline-flex items-center justify-center w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-status-error/10 text-status-error border-border-primary">
|
||||
<AlertTriangle className="w-3.5 h-3.5" strokeWidth={2} />
|
||||
</span>
|
||||
<span className="text-xs text-text-secondary"><strong>Conflicts</strong> - Active merge conflicts need resolution</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 p-2 rounded">
|
||||
<span className="inline-flex items-center justify-center gap-0.5 w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-status-info/10 text-status-info border-border-primary">
|
||||
<Edit className="w-3.5 h-3.5" strokeWidth={2} />
|
||||
<span className="font-bold">2</span>
|
||||
</span>
|
||||
<span className="text-xs text-text-secondary"><strong>Uncommitted</strong> - Work in progress</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-gray-400 rounded-full flex-shrink-0"></div>
|
||||
|
||||
{/* LOW PRIORITY */}
|
||||
<div>
|
||||
<span className="text-gray-700 dark:text-gray-200 font-medium">Completed</span>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">Task finished successfully</p>
|
||||
<p className="text-xs font-medium text-text-tertiary mb-2">LOW PRIORITY</p>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-3 p-2 rounded">
|
||||
<span className="inline-flex items-center justify-center gap-0.5 w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-bg-tertiary text-text-tertiary border-border-primary">
|
||||
<CircleArrowDown className="w-3.5 h-3.5" strokeWidth={2} />
|
||||
<span className="font-bold">2</span>
|
||||
</span>
|
||||
<span className="text-xs text-text-secondary"><strong>Behind Only</strong> - No unique changes</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 p-2 rounded">
|
||||
<span className="inline-flex items-center justify-center w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-bg-tertiary text-text-tertiary border-border-primary">
|
||||
<Check className="w-3.5 h-3.5" strokeWidth={2} />
|
||||
</span>
|
||||
<span className="text-xs text-text-secondary"><strong>Up to Date</strong> - Safe to remove</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-blue-500 rounded-full animate-pulse flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-gray-700 dark:text-gray-200 font-medium">New Activity</span>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">Session has new unviewed results</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 bg-red-500 rounded-full flex-shrink-0"></div>
|
||||
<div>
|
||||
<span className="text-gray-700 dark:text-gray-200 font-medium">Error</span>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">Something went wrong with the session</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 p-3 bg-status-info/10 border border-status-info/20 rounded-lg">
|
||||
<p className="font-medium text-status-info text-xs mb-2">Tips</p>
|
||||
<ul className="list-disc list-inside space-y-1 text-xs text-text-secondary">
|
||||
<li>Focus on <strong>High Priority</strong> branches first</li>
|
||||
<li>Numbers show commit count or file changes</li>
|
||||
<li>Star (★) indicates counts above 9</li>
|
||||
<li>Gray indicators are low priority - often safe to remove</li>
|
||||
<li>Click any indicator to view detailed diff</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ModalBody>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,7 +1,10 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Session } from '../types/session';
|
||||
import { AlertCircle, CheckCircle, Loader2, PauseCircle, Bell } from 'lucide-react';
|
||||
import { isDocumentVisible } from '../utils/performanceUtils';
|
||||
import { Badge } from './ui/Badge';
|
||||
import { StatusDot } from './ui/StatusDot';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
interface StatusIndicatorProps {
|
||||
session: Session;
|
||||
@ -17,7 +20,9 @@ export const StatusIndicator = React.memo(({
|
||||
showProgress = false
|
||||
}: StatusIndicatorProps) => {
|
||||
const [animationsEnabled, setAnimationsEnabled] = useState(isDocumentVisible());
|
||||
const elementRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Use the session status from the prop - parent component manages the session state
|
||||
const currentStatus = session.status;
|
||||
|
||||
useEffect(() => {
|
||||
const handleVisibilityChange = () => {
|
||||
@ -27,205 +32,159 @@ export const StatusIndicator = React.memo(({
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
}, []);
|
||||
const getStatusConfig = (status: Session['status']) => {
|
||||
const getStatusConfig = (status: Session['status'], statusMessage?: string) => {
|
||||
switch (status) {
|
||||
case 'initializing':
|
||||
return {
|
||||
status: 'initializing',
|
||||
color: 'bg-green-500',
|
||||
textColor: 'text-green-400',
|
||||
bgColor: 'bg-green-900/20',
|
||||
borderColor: 'border-green-800',
|
||||
variant: 'success' as const,
|
||||
badgeVariant: 'success' as const,
|
||||
dotStatus: 'running' as const,
|
||||
icon: Loader2,
|
||||
text: 'Initializing',
|
||||
tooltip: 'Setting up git worktree and environment',
|
||||
animated: true,
|
||||
text: statusMessage || 'Initializing',
|
||||
tooltip: statusMessage || 'Setting up git worktree and environment',
|
||||
spin: true,
|
||||
animated: true
|
||||
};
|
||||
case 'running':
|
||||
return {
|
||||
status: 'running',
|
||||
color: 'bg-green-500',
|
||||
textColor: 'text-green-400',
|
||||
bgColor: 'bg-green-900/20',
|
||||
borderColor: 'border-green-800',
|
||||
variant: 'success' as const,
|
||||
badgeVariant: 'success' as const,
|
||||
dotStatus: 'running' as const,
|
||||
icon: Loader2,
|
||||
text: 'Running',
|
||||
tooltip: 'Claude is actively processing your request',
|
||||
animated: true,
|
||||
spin: true,
|
||||
animated: true
|
||||
};
|
||||
case 'waiting':
|
||||
return {
|
||||
status: 'waiting',
|
||||
color: 'bg-amber-500',
|
||||
textColor: 'text-amber-400',
|
||||
bgColor: 'bg-amber-900/20',
|
||||
borderColor: 'border-amber-800',
|
||||
variant: 'warning' as const,
|
||||
badgeVariant: 'warning' as const,
|
||||
dotStatus: 'waiting' as const,
|
||||
icon: PauseCircle,
|
||||
text: 'Waiting for input',
|
||||
tooltip: 'Claude needs your input to continue',
|
||||
animated: true,
|
||||
pulse: true,
|
||||
animated: true
|
||||
};
|
||||
case 'stopped':
|
||||
return {
|
||||
status: 'stopped',
|
||||
color: 'bg-gray-400',
|
||||
textColor: 'text-gray-400',
|
||||
bgColor: 'bg-gray-800',
|
||||
borderColor: 'border-gray-700',
|
||||
variant: 'default' as const,
|
||||
badgeVariant: 'default' as const,
|
||||
dotStatus: 'default' as const,
|
||||
icon: CheckCircle,
|
||||
text: 'Completed',
|
||||
tooltip: 'Task finished successfully',
|
||||
animated: false,
|
||||
animated: false
|
||||
};
|
||||
case 'completed_unviewed':
|
||||
return {
|
||||
status: 'completed_unviewed',
|
||||
color: 'bg-blue-500',
|
||||
textColor: 'text-blue-400',
|
||||
bgColor: 'bg-blue-900/20',
|
||||
borderColor: 'border-blue-800',
|
||||
variant: 'info' as const,
|
||||
badgeVariant: 'info' as const,
|
||||
dotStatus: 'info' as const,
|
||||
icon: Bell,
|
||||
text: 'New activity',
|
||||
tooltip: 'Session has new unviewed results',
|
||||
animated: true,
|
||||
pulse: true,
|
||||
animated: true
|
||||
};
|
||||
case 'error':
|
||||
return {
|
||||
status: 'error',
|
||||
color: 'bg-red-500',
|
||||
textColor: 'text-red-400',
|
||||
bgColor: 'bg-red-900/20',
|
||||
borderColor: 'border-red-800',
|
||||
variant: 'error' as const,
|
||||
badgeVariant: 'error' as const,
|
||||
dotStatus: 'error' as const,
|
||||
icon: AlertCircle,
|
||||
text: 'Error',
|
||||
tooltip: 'Something went wrong with the session',
|
||||
animated: false,
|
||||
animated: false
|
||||
};
|
||||
default:
|
||||
return {
|
||||
status: 'unknown',
|
||||
color: 'bg-gray-400',
|
||||
textColor: 'text-gray-400',
|
||||
bgColor: 'bg-gray-800',
|
||||
borderColor: 'border-gray-700',
|
||||
variant: 'default' as const,
|
||||
badgeVariant: 'default' as const,
|
||||
dotStatus: 'default' as const,
|
||||
icon: AlertCircle,
|
||||
text: 'Unknown',
|
||||
tooltip: 'Unknown status',
|
||||
animated: false,
|
||||
animated: false
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const getSizeClasses = (size: string) => {
|
||||
const getBadgeSize = (size: string) => {
|
||||
switch (size) {
|
||||
case 'small':
|
||||
return {
|
||||
dot: 'w-2 h-2',
|
||||
container: 'w-3 h-3',
|
||||
text: 'text-xs',
|
||||
spacing: 'space-x-1',
|
||||
};
|
||||
return 'sm' as const;
|
||||
case 'large':
|
||||
return {
|
||||
dot: 'w-4 h-4',
|
||||
container: 'w-5 h-5',
|
||||
text: 'text-sm',
|
||||
spacing: 'space-x-3',
|
||||
};
|
||||
default: // medium
|
||||
return {
|
||||
dot: 'w-3 h-3',
|
||||
container: 'w-4 h-4',
|
||||
text: 'text-sm',
|
||||
spacing: 'space-x-2',
|
||||
};
|
||||
return 'lg' as const;
|
||||
default:
|
||||
return 'md' as const;
|
||||
}
|
||||
};
|
||||
|
||||
const config = getStatusConfig(session.status);
|
||||
const sizeClasses = getSizeClasses(size);
|
||||
const getDotSize = (size: string) => {
|
||||
switch (size) {
|
||||
case 'small':
|
||||
return 'sm' as const;
|
||||
case 'large':
|
||||
return 'lg' as const;
|
||||
default:
|
||||
return 'md' as const;
|
||||
}
|
||||
};
|
||||
|
||||
const config = getStatusConfig(currentStatus, session.statusMessage);
|
||||
const badgeSize = getBadgeSize(size);
|
||||
const dotSize = getDotSize(size);
|
||||
|
||||
|
||||
// Disable animations when not visible or for non-active states
|
||||
const shouldAnimate = animationsEnabled && config.animated &&
|
||||
['running', 'initializing', 'waiting', 'completed_unviewed'].includes(session.status);
|
||||
const shouldAnimate = animationsEnabled && config.animated;
|
||||
|
||||
const estimateProgress = (): number => {
|
||||
if (session.status === 'stopped') return 100;
|
||||
if (session.status === 'error') return 0;
|
||||
if (session.status === 'waiting') return 75;
|
||||
if (session.status === 'running') return 50;
|
||||
if (session.status === 'initializing') return 25;
|
||||
if (currentStatus === 'stopped') return 100;
|
||||
if (currentStatus === 'error') return 0;
|
||||
if (currentStatus === 'waiting') return 75;
|
||||
if (currentStatus === 'running') return 50;
|
||||
if (currentStatus === 'initializing') return 25;
|
||||
return 0;
|
||||
};
|
||||
|
||||
|
||||
// When showText is true, render as a chip
|
||||
// When showText is true, render as a badge
|
||||
if (showText) {
|
||||
return (
|
||||
<div className={`flex items-center ${sizeClasses.spacing}`}>
|
||||
{/* Status Chip */}
|
||||
<div
|
||||
className={`
|
||||
inline-flex items-center gap-2
|
||||
px-3 py-1.5
|
||||
rounded-full
|
||||
${config.bgColor}
|
||||
border
|
||||
${config.borderColor}
|
||||
${shouldAnimate ? 'relative overflow-hidden' : ''}
|
||||
transition-all duration-200
|
||||
`}
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={config.badgeVariant}
|
||||
size={badgeSize}
|
||||
animated={shouldAnimate}
|
||||
pulse={config.pulse}
|
||||
icon={React.createElement(config.icon, {
|
||||
className: cn(
|
||||
'w-4 h-4',
|
||||
config.spin && shouldAnimate && 'animate-spin'
|
||||
)
|
||||
})}
|
||||
className={config.tooltip ? `cursor-help` : undefined}
|
||||
title={config.tooltip}
|
||||
>
|
||||
{/* Animated background effect for active states */}
|
||||
{shouldAnimate && (
|
||||
<div className="absolute inset-0 -z-10">
|
||||
<div
|
||||
className={`
|
||||
absolute inset-0
|
||||
${config.color}
|
||||
opacity-20
|
||||
${animationsEnabled ? 'animate-pulse' : ''}
|
||||
`}
|
||||
/>
|
||||
{(config.status === 'running' || config.status === 'initializing') && (
|
||||
<div
|
||||
className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full animate-[shimmer_2s_infinite]"
|
||||
style={{
|
||||
animation: 'shimmer 2s infinite',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Status icon and text */}
|
||||
{React.createElement(config.icon, {
|
||||
className: `w-4 h-4 ${config.textColor} ${config.spin && animationsEnabled ? 'animate-spin' : ''}`
|
||||
})}
|
||||
<span className={`${sizeClasses.text} font-medium ${config.textColor}`}>
|
||||
{config.text}
|
||||
</span>
|
||||
|
||||
{/* Pulsing dot for waiting/new activity status */}
|
||||
{config.pulse && shouldAnimate && (
|
||||
<div className="relative flex h-2 w-2">
|
||||
<span className={`${animationsEnabled ? 'animate-ping' : ''} absolute inline-flex h-full w-full rounded-full ${config.color} opacity-75`}></span>
|
||||
<span className={`relative inline-flex rounded-full h-2 w-2 ${config.color}`}></span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{config.text}
|
||||
</Badge>
|
||||
|
||||
{/* Progress Bar */}
|
||||
{showProgress && (
|
||||
<div className="flex-1 ml-2">
|
||||
<div className="w-full bg-gray-700 rounded-full h-1.5">
|
||||
<div className="w-full bg-surface-tertiary rounded-full h-1.5">
|
||||
<div
|
||||
className={`${config.color} h-1.5 rounded-full transition-all duration-1000 ease-out`}
|
||||
className={cn(
|
||||
'h-1.5 rounded-full transition-all duration-1000 ease-out',
|
||||
config.dotStatus === 'running' && 'bg-status-success',
|
||||
config.dotStatus === 'waiting' && 'bg-status-warning',
|
||||
config.dotStatus === 'error' && 'bg-status-error',
|
||||
config.dotStatus === 'info' && 'bg-status-info',
|
||||
config.dotStatus === 'default' && 'bg-text-tertiary'
|
||||
)}
|
||||
style={{ width: `${estimateProgress()}%` }}
|
||||
/>
|
||||
</div>
|
||||
@ -235,33 +194,16 @@ export const StatusIndicator = React.memo(({
|
||||
);
|
||||
}
|
||||
|
||||
// Original dot indicator for when showText is false
|
||||
// Simple dot indicator for when showText is false
|
||||
return (
|
||||
<div className={`flex items-center ${sizeClasses.spacing}`} title={config.tooltip}>
|
||||
{/* Status Indicator Dot */}
|
||||
<div className={`relative ${sizeClasses.container} flex items-center justify-center`} ref={elementRef}>
|
||||
<div
|
||||
className={`
|
||||
${sizeClasses.dot}
|
||||
${config.color}
|
||||
rounded-full
|
||||
${shouldAnimate && config.animated && animationsEnabled ? 'animate-pulse' : ''}
|
||||
${shouldAnimate && config.pulse && animationsEnabled ? 'animate-ping' : ''}
|
||||
`}
|
||||
/>
|
||||
{config.pulse && shouldAnimate && (
|
||||
<div
|
||||
className={`
|
||||
absolute inset-0
|
||||
${sizeClasses.dot}
|
||||
${config.color}
|
||||
rounded-full
|
||||
opacity-75
|
||||
`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<StatusDot
|
||||
status={config.dotStatus}
|
||||
size={dotSize}
|
||||
animated={shouldAnimate && !config.pulse}
|
||||
pulse={config.pulse && shouldAnimate}
|
||||
className={config.tooltip ? 'cursor-help' : undefined}
|
||||
title={config.tooltip}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@ -131,15 +131,15 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
|
||||
const getStatusIndicator = () => {
|
||||
switch (connectionState.status) {
|
||||
case 'connected':
|
||||
return <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse" />;
|
||||
return <div className="w-3 h-3 bg-status-success rounded-full animate-pulse" />;
|
||||
case 'connecting':
|
||||
return <div className="w-3 h-3 bg-yellow-500 rounded-full animate-pulse" />;
|
||||
return <div className="w-3 h-3 bg-status-warning rounded-full animate-pulse" />;
|
||||
case 'expired':
|
||||
return <div className="w-3 h-3 bg-orange-500 rounded-full" />;
|
||||
return <div className="w-3 h-3 bg-status-warning rounded-full" />;
|
||||
case 'error':
|
||||
return <div className="w-3 h-3 bg-red-500 rounded-full" />;
|
||||
return <div className="w-3 h-3 bg-status-error rounded-full" />;
|
||||
default:
|
||||
return <div className="w-3 h-3 bg-gray-400 dark:bg-gray-500 rounded-full" />;
|
||||
return <div className="w-3 h-3 bg-text-tertiary rounded-full" />;
|
||||
}
|
||||
};
|
||||
|
||||
@ -164,10 +164,10 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
|
||||
<div className="flex items-center space-x-3">
|
||||
{getStatusIndicator()}
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<div className="text-sm font-medium text-text-primary">
|
||||
Stravu Integration
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-400">
|
||||
<div className="text-xs text-text-tertiary">
|
||||
{getStatusText()}
|
||||
</div>
|
||||
</div>
|
||||
@ -178,7 +178,7 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
|
||||
<button
|
||||
onClick={handleConnect}
|
||||
disabled={false}
|
||||
className="px-3 py-1.5 text-sm font-medium text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/20 border border-blue-300 dark:border-blue-800 rounded-md hover:bg-blue-200 dark:hover:bg-blue-900/30 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
className="px-3 py-1.5 text-sm font-medium text-interactive bg-interactive/10 border border-interactive/30 rounded-md hover:bg-interactive/20 focus:outline-none focus:ring-2 focus:ring-interactive disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{connectionState.status === 'expired' ? 'Reconnect' : 'Connect'}
|
||||
</button>
|
||||
@ -186,7 +186,7 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
|
||||
<>
|
||||
<button
|
||||
onClick={checkConnectionStatus}
|
||||
className="p-1.5 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||
className="p-1.5 text-text-tertiary hover:text-text-primary rounded-md hover:bg-surface-hover"
|
||||
title="Refresh connection status"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
@ -195,7 +195,7 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDisconnect}
|
||||
className="px-3 py-1.5 text-sm font-medium text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/20 border border-red-300 dark:border-red-800 rounded-md hover:bg-red-200 dark:hover:bg-red-900/30 focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||
className="px-3 py-1.5 text-sm font-medium text-status-error bg-status-error/10 border border-status-error/30 rounded-md hover:bg-status-error/20 focus:outline-none focus:ring-2 focus:ring-status-error"
|
||||
>
|
||||
Disconnect
|
||||
</button>
|
||||
@ -205,13 +205,13 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
|
||||
</div>
|
||||
|
||||
{connectionState.error && (
|
||||
<div className="mt-2 text-xs text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/20 border border-red-300 dark:border-red-800 rounded-md p-2">
|
||||
<div className="mt-2 text-xs text-status-error bg-status-error/10 border border-status-error/30 rounded-md p-2">
|
||||
{connectionState.error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{connectionState.status === 'connecting' && (
|
||||
<div className="mt-2 text-xs text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/20 border border-blue-300 dark:border-blue-800 rounded-md p-2">
|
||||
<div className="mt-2 text-xs text-interactive bg-interactive/10 border border-interactive/30 rounded-md p-2">
|
||||
Please complete authentication in your browser. This may take a few moments...
|
||||
</div>
|
||||
)}
|
||||
|
||||
@ -178,14 +178,14 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-gray-800 rounded-lg w-full max-w-4xl mx-4 max-h-[80vh] overflow-hidden flex flex-col">
|
||||
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-50">
|
||||
<div className="bg-surface-secondary rounded-lg w-full max-w-4xl mx-4 max-h-[80vh] overflow-hidden flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-6 border-b border-gray-700">
|
||||
<div className="flex items-center justify-between p-6 border-b border-border-primary">
|
||||
<h2 className="text-lg font-semibold text-white">Search Stravu Notebooks</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
|
||||
className="text-text-tertiary hover:text-text-secondary transition-colors"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
@ -200,24 +200,24 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
|
||||
{isConnecting ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-center">
|
||||
<svg className="w-8 h-8 animate-spin text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="w-8 h-8 animate-spin text-interactive" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-600 dark:text-gray-400">Connecting to Stravu...</p>
|
||||
<p className="text-text-secondary">Connecting to Stravu...</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-center">
|
||||
<svg className="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="w-12 h-12 text-text-tertiary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-600 dark:text-gray-400">Not connected to Stravu</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Please authenticate with Stravu to access your notebooks.</p>
|
||||
<p className="text-text-secondary">Not connected to Stravu</p>
|
||||
<p className="text-sm text-text-tertiary">Please authenticate with Stravu to access your notebooks.</p>
|
||||
<button
|
||||
onClick={connectToStravu}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
|
||||
className="px-4 py-2 bg-interactive text-white rounded-md hover:bg-interactive-hover transition-colors"
|
||||
>
|
||||
Connect to Stravu
|
||||
</button>
|
||||
@ -234,12 +234,12 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Search for notebooks (AI-powered semantic search)..."
|
||||
className="flex-1 px-3 py-2 border border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-100 bg-gray-700 placeholder-gray-400"
|
||||
className="flex-1 px-3 py-2 border border-border-primary rounded-md focus:outline-none focus:ring-2 focus:ring-interactive text-text-primary bg-surface-primary placeholder-text-tertiary"
|
||||
/>
|
||||
<button
|
||||
onClick={handleSearch}
|
||||
disabled={isSearching || !searchQuery.trim()}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2"
|
||||
className="px-4 py-2 bg-interactive text-white rounded-md hover:bg-interactive-hover disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2"
|
||||
>
|
||||
{isSearching ? (
|
||||
<>
|
||||
@ -261,15 +261,15 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md p-3">
|
||||
<p className="text-red-800 dark:text-red-200 text-sm">{error}</p>
|
||||
<div className="bg-status-error/10 border border-status-error/30 rounded-md p-3">
|
||||
<p className="text-status-error text-sm">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search Results */}
|
||||
{searchResults.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
<h3 className="text-sm font-medium text-text-secondary">
|
||||
Search Results ({searchResults.length})
|
||||
</h3>
|
||||
<div className="grid gap-2">
|
||||
@ -277,44 +277,44 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
|
||||
<div
|
||||
key={notebook.id}
|
||||
onClick={() => handleNotebookClick(notebook)}
|
||||
className={`p-3 border border-gray-700 rounded-md hover:bg-gray-700 cursor-pointer transition-colors ${
|
||||
selectedNotebook?.id === notebook.id && isLoadingContent ? 'bg-blue-900/20 border-blue-700' : ''
|
||||
className={`p-3 border border-border-primary rounded-md hover:bg-surface-hover cursor-pointer transition-colors ${
|
||||
selectedNotebook?.id === notebook.id && isLoadingContent ? 'bg-interactive/20 border-interactive' : ''
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center space-x-2">
|
||||
<svg className="w-4 h-4 text-gray-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="w-4 h-4 text-text-tertiary flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
|
||||
</svg>
|
||||
<h4 className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">{notebook.title}</h4>
|
||||
<h4 className="text-sm font-medium text-text-primary truncate">{notebook.title}</h4>
|
||||
{selectedNotebook?.id === notebook.id && isLoadingContent && (
|
||||
<svg className="w-4 h-4 animate-spin text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="w-4 h-4 animate-spin text-interactive" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||
</svg>
|
||||
)}
|
||||
{notebook.similarity && (
|
||||
<span className="text-xs bg-blue-900/30 text-blue-200 px-2 py-1 rounded">
|
||||
<span className="text-xs bg-interactive/30 text-interactive px-2 py-1 rounded">
|
||||
{Math.round(notebook.similarity * 100)}% match
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{notebook.excerpt && (
|
||||
<p className="text-xs text-gray-600 dark:text-gray-400 mt-1">{notebook.excerpt}</p>
|
||||
<p className="text-xs text-text-secondary mt-1">{notebook.excerpt}</p>
|
||||
)}
|
||||
<div className="flex items-center space-x-4 mt-2 text-xs text-gray-500">
|
||||
<div className="flex items-center space-x-4 mt-2 text-xs text-text-tertiary">
|
||||
<span>{formatWordCount(notebook.wordCount)}</span>
|
||||
<span>{formatDate(notebook.lastModified)}</span>
|
||||
{notebook.tags.length > 0 && (
|
||||
<div className="flex items-center space-x-1">
|
||||
<span>Tags:</span>
|
||||
{notebook.tags.slice(0, 3).map((tag) => (
|
||||
<span key={tag} className="bg-gray-700 text-gray-400 px-1 rounded text-xs">
|
||||
<span key={tag} className="bg-surface-tertiary text-text-secondary px-1 rounded text-xs">
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
{notebook.tags.length > 3 && (
|
||||
<span className="text-gray-400">+{notebook.tags.length - 3}</span>
|
||||
<span className="text-text-tertiary">+{notebook.tags.length - 3}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@ -329,22 +329,22 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
|
||||
|
||||
{searchQuery && !isSearching && searchResults.length === 0 && !error && (
|
||||
<div className="text-center py-8">
|
||||
<svg className="w-12 h-12 text-gray-400 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="w-12 h-12 text-text-tertiary mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
|
||||
</svg>
|
||||
<p className="text-gray-600 dark:text-gray-400">No notebooks found for "{searchQuery}"</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">Try a different search term or concept</p>
|
||||
<p className="text-text-secondary">No notebooks found for "{searchQuery}"</p>
|
||||
<p className="text-sm text-text-tertiary mt-1">Try a different search term or concept</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!searchQuery && (
|
||||
<div className="text-center py-8">
|
||||
<svg className="w-12 h-12 text-gray-400 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="w-12 h-12 text-text-tertiary mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
|
||||
</svg>
|
||||
<p className="text-gray-600 dark:text-gray-400">Search for Stravu notebooks</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">Use AI-powered semantic search to find notebooks by concept</p>
|
||||
<p className="text-xs text-gray-400 mt-2">💡 Try searching for "machine learning examples" or "API documentation"</p>
|
||||
<p className="text-text-secondary">Search for Stravu notebooks</p>
|
||||
<p className="text-sm text-text-tertiary mt-1">Use AI-powered semantic search to find notebooks by concept</p>
|
||||
<p className="text-xs text-text-tertiary mt-2">💡 Try searching for "machine learning examples" or "API documentation"</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@ -352,10 +352,10 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex justify-end space-x-3 p-6 border-t border-gray-700">
|
||||
<div className="flex justify-end space-x-3 p-6 border-t border-border-primary">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
|
||||
className="px-4 py-2 text-text-secondary hover:text-text-primary transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
|
||||
@ -123,15 +123,15 @@ export function StravuStatusIndicator() {
|
||||
const getStatusColor = () => {
|
||||
switch (connectionState.status) {
|
||||
case 'connected':
|
||||
return 'text-green-600 dark:text-green-400';
|
||||
return 'text-status-success';
|
||||
case 'connecting':
|
||||
return 'text-blue-600 dark:text-blue-400';
|
||||
return 'text-interactive';
|
||||
case 'expired':
|
||||
return 'text-yellow-600 dark:text-yellow-400';
|
||||
return 'text-status-warning';
|
||||
case 'error':
|
||||
return 'text-red-600 dark:text-red-400';
|
||||
return 'text-status-error';
|
||||
default:
|
||||
return 'text-gray-400 dark:text-gray-500';
|
||||
return 'text-text-tertiary';
|
||||
}
|
||||
};
|
||||
|
||||
@ -182,7 +182,7 @@ export function StravuStatusIndicator() {
|
||||
onClick={handleConnect}
|
||||
onMouseEnter={() => setShowTooltip(true)}
|
||||
onMouseLeave={() => setShowTooltip(false)}
|
||||
className={`p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${getStatusColor()}`}
|
||||
className={`p-2 rounded-lg hover:bg-surface-hover transition-colors ${getStatusColor()}`}
|
||||
disabled={connectionState.status === 'connecting'}
|
||||
>
|
||||
{renderIcon()}
|
||||
@ -190,30 +190,30 @@ export function StravuStatusIndicator() {
|
||||
|
||||
{/* Tooltip */}
|
||||
{showTooltip && (
|
||||
<div className="absolute right-0 top-full mt-2 w-64 bg-gray-900 text-white text-sm rounded-lg p-3 z-50">
|
||||
<div className="absolute right-0 top-full mt-2 w-64 bg-surface-tertiary text-text-primary text-sm rounded-lg p-3 z-50">
|
||||
<div className="font-medium mb-1">Stravu Integration</div>
|
||||
<div className="text-gray-300">{getStatusText()}</div>
|
||||
<div className="text-text-secondary">{getStatusText()}</div>
|
||||
|
||||
{connectionState.status === 'connected' && connectionState.memberInfo && (
|
||||
<div className="mt-2 pt-2 border-t border-gray-700">
|
||||
<div className="text-xs text-gray-400">
|
||||
<div className="mt-2 pt-2 border-t border-border-secondary">
|
||||
<div className="text-xs text-text-tertiary">
|
||||
Member: {connectionState.memberInfo.memberId}
|
||||
</div>
|
||||
<div className="text-xs text-gray-400">
|
||||
<div className="text-xs text-text-tertiary">
|
||||
Scopes: {connectionState.memberInfo.scopes.join(', ')}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(connectionState.status === 'disconnected' || connectionState.status === 'error') && (
|
||||
<div className="mt-2 text-xs text-gray-400">
|
||||
<div className="mt-2 text-xs text-text-tertiary">
|
||||
Click to connect to Stravu
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Arrow pointing up */}
|
||||
<div className="absolute top-0 right-4 transform -translate-y-1">
|
||||
<div className="w-0 h-0 border-l-4 border-r-4 border-b-4 border-transparent border-b-gray-900"></div>
|
||||
<div className="w-0 h-0 border-l-4 border-r-4 border-b-4 border-transparent border-b-surface-tertiary"></div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
1125
frontend/src/components/TokenTest.tsx
Normal file
@ -1,5 +1,9 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { X, Download, AlertCircle, CheckCircle, Loader2 } from 'lucide-react';
|
||||
import { Download, AlertCircle, CheckCircle, Loader2 } from 'lucide-react';
|
||||
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { Button } from './ui/Button';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
|
||||
interface UpdateDialogProps {
|
||||
isOpen: boolean;
|
||||
@ -101,8 +105,8 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
try {
|
||||
setError(null);
|
||||
await window.electronAPI.updater.checkAndDownload();
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to check for updates');
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to check for updates');
|
||||
setUpdateState('error');
|
||||
}
|
||||
};
|
||||
@ -115,8 +119,8 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
try {
|
||||
setError(null);
|
||||
await window.electronAPI.updater.downloadUpdate();
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to download update');
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to download update');
|
||||
setUpdateState('error');
|
||||
}
|
||||
};
|
||||
@ -129,8 +133,8 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
try {
|
||||
await window.electronAPI.updater.installUpdate();
|
||||
// App will restart, so no need to handle response
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to install update');
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to install update');
|
||||
setUpdateState('error');
|
||||
}
|
||||
};
|
||||
@ -150,31 +154,23 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
|
||||
<div className="bg-gray-800 rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col">
|
||||
<div className="flex items-center justify-between p-6 border-b border-gray-700">
|
||||
<div className="flex items-center gap-3">
|
||||
<Download className="w-6 h-6 text-blue-400" />
|
||||
<h2 className="text-xl font-semibold text-gray-100">Software Update</h2>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-200 transition-colors"
|
||||
disabled={updateState === 'downloading'}
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="lg" showCloseButton={false}>
|
||||
<ModalHeader onClose={updateState === 'downloading' ? undefined : onClose}>
|
||||
<div className="flex items-center gap-3">
|
||||
<Download className="w-6 h-6 text-interactive" />
|
||||
<h2 className="text-xl font-semibold text-text-primary">Software Update</h2>
|
||||
</div>
|
||||
</ModalHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
<ModalBody className="space-y-6">
|
||||
{versionInfo && (
|
||||
<div className="mb-6">
|
||||
<div className="text-gray-300 mb-2">
|
||||
Current version: <span className="font-mono text-gray-100">{versionInfo.current}</span>
|
||||
<div>
|
||||
<div className="text-text-secondary mb-2">
|
||||
Current version: <span className="font-mono text-text-primary">{versionInfo.current}</span>
|
||||
</div>
|
||||
{versionInfo.hasUpdate && (
|
||||
<div className="text-gray-300">
|
||||
Latest version: <span className="font-mono text-green-400">{versionInfo.latest}</span>
|
||||
<div className="text-text-secondary">
|
||||
Latest version: <span className="font-mono text-status-success">{versionInfo.latest}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@ -183,76 +179,76 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
{/* Update State UI */}
|
||||
<div className="space-y-4">
|
||||
{updateState === 'idle' && versionInfo?.hasUpdate && (
|
||||
<div className="bg-gray-700 rounded-lg p-4">
|
||||
<h3 className="text-lg font-medium text-gray-100 mb-2">Update Available</h3>
|
||||
<p className="text-gray-300 mb-4">
|
||||
<div className="bg-surface-secondary rounded-lg p-4">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">Update Available</h3>
|
||||
<p className="text-text-secondary mb-4">
|
||||
A new version of Crystal is available.
|
||||
{isPackaged ? ' Click below to download and install the update.' : ' Auto-update is only available in the packaged app.'}
|
||||
</p>
|
||||
|
||||
{isPackaged ? (
|
||||
<button
|
||||
<Button
|
||||
onClick={handleCheckForUpdates}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
|
||||
variant="primary"
|
||||
icon={<Download className="w-4 h-4" />}
|
||||
>
|
||||
Download Update
|
||||
</button>
|
||||
</Button>
|
||||
) : (
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={() => versionInfo.releaseUrl && window.electronAPI.openExternal(versionInfo.releaseUrl)}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
View Release
|
||||
</button>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => versionInfo.releaseUrl && window.electronAPI.openExternal(versionInfo.releaseUrl)}
|
||||
variant="primary"
|
||||
>
|
||||
View Release
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{updateState === 'checking' && (
|
||||
<div className="flex items-center gap-3 text-gray-300">
|
||||
<div className="flex items-center gap-3 text-text-secondary">
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span>Checking for updates...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{updateState === 'available' && (
|
||||
<div className="bg-gray-700 rounded-lg p-4">
|
||||
<h3 className="text-lg font-medium text-gray-100 mb-2">Ready to Download</h3>
|
||||
<p className="text-gray-300 mb-4">
|
||||
<div className="bg-surface-secondary rounded-lg p-4">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">Ready to Download</h3>
|
||||
<p className="text-text-secondary mb-4">
|
||||
The update is ready to download. This may take a few minutes depending on your connection.
|
||||
</p>
|
||||
<button
|
||||
<Button
|
||||
onClick={handleDownloadUpdate}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
|
||||
variant="primary"
|
||||
icon={<Download className="w-4 h-4" />}
|
||||
>
|
||||
Start Download
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{updateState === 'downloading' && downloadProgress && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3 text-gray-300">
|
||||
<div className="flex items-center gap-3 text-text-secondary">
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span>Downloading update...</span>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-700 rounded-lg p-4 space-y-3">
|
||||
<div className="flex justify-between text-sm text-gray-400">
|
||||
<div className="bg-surface-secondary rounded-lg p-4 space-y-3">
|
||||
<div className="flex justify-between text-sm text-text-tertiary">
|
||||
<span>{formatBytes(downloadProgress.transferred)} / {formatBytes(downloadProgress.total)}</span>
|
||||
<span>{formatSpeed(downloadProgress.bytesPerSecond)}</span>
|
||||
</div>
|
||||
|
||||
<div className="w-full bg-gray-600 rounded-full h-2">
|
||||
<div className="w-full bg-surface-tertiary rounded-full h-2">
|
||||
<div
|
||||
className="bg-blue-500 h-2 rounded-full transition-all duration-300"
|
||||
className="bg-interactive h-2 rounded-full transition-all duration-300"
|
||||
style={{ width: `${downloadProgress.percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="text-center text-sm text-gray-400">
|
||||
<div className="text-center text-sm text-text-tertiary">
|
||||
{Math.round(downloadProgress.percent)}%
|
||||
</div>
|
||||
</div>
|
||||
@ -260,20 +256,21 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
)}
|
||||
|
||||
{updateState === 'downloaded' && (
|
||||
<div className="bg-green-900/30 border border-green-700 rounded-lg p-4">
|
||||
<div className="bg-status-success/10 border border-status-success/30 rounded-lg p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle className="w-5 h-5 text-green-400 mt-0.5" />
|
||||
<CheckCircle className="w-5 h-5 text-status-success mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h3 className="text-lg font-medium text-green-400 mb-2">Update Downloaded</h3>
|
||||
<p className="text-gray-300 mb-4">
|
||||
<h3 className="text-lg font-medium text-status-success mb-2">Update Downloaded</h3>
|
||||
<p className="text-text-secondary mb-4">
|
||||
The update has been downloaded successfully. Crystal will restart to apply the update.
|
||||
</p>
|
||||
<button
|
||||
<Button
|
||||
onClick={handleInstallUpdate}
|
||||
className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition-colors"
|
||||
variant="primary"
|
||||
className="bg-status-success hover:bg-status-success/90"
|
||||
>
|
||||
Restart and Install
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -283,37 +280,37 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
<div className="space-y-4">
|
||||
{/* Manual Download Box */}
|
||||
{versionInfo?.releaseUrl && (
|
||||
<div className="bg-blue-900/30 border border-blue-700 rounded-lg p-4">
|
||||
<div className="bg-interactive/10 border border-interactive/30 rounded-lg p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-blue-400 mb-1">Manual Update Available</h3>
|
||||
<p className="text-sm text-gray-300">
|
||||
<h3 className="text-lg font-medium text-interactive mb-1">Manual Update Available</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Automatic update failed, but you can download the latest version manually.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
<Button
|
||||
onClick={() => window.electronAPI.openExternal(versionInfo.releaseUrl!)}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors flex items-center gap-2"
|
||||
variant="primary"
|
||||
icon={<Download className="w-4 h-4" />}
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
Download from GitHub
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Details */}
|
||||
<div className="bg-red-900/30 border border-red-700 rounded-lg p-4">
|
||||
<div className="bg-status-error/10 border border-status-error/30 rounded-lg p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertCircle className="w-5 h-5 text-red-400 mt-0.5" />
|
||||
<AlertCircle className="w-5 h-5 text-status-error mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h3 className="text-lg font-medium text-red-400 mb-2">Update Error</h3>
|
||||
<p className="text-gray-300 mb-2">{error}</p>
|
||||
<h3 className="text-lg font-medium text-status-error mb-2">Update Error</h3>
|
||||
<p className="text-text-secondary mb-2">{error}</p>
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-gray-400">
|
||||
<p className="text-sm text-text-tertiary">
|
||||
To update manually:
|
||||
</p>
|
||||
<ol className="text-sm text-gray-300 list-decimal list-inside ml-2 space-y-2">
|
||||
<ol className="text-sm text-text-secondary list-decimal list-inside ml-2 space-y-2">
|
||||
<li>Click "Download from GitHub" above</li>
|
||||
<li>Download the .dmg file from the release page</li>
|
||||
<li>Close Crystal</li>
|
||||
@ -321,11 +318,11 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
<li>Drag Crystal to your Applications folder</li>
|
||||
<li>Launch the new version of Crystal</li>
|
||||
</ol>
|
||||
<p className="text-sm text-gray-400 mt-3">
|
||||
<p className="text-sm text-text-tertiary mt-3">
|
||||
Your settings and sessions will be preserved during the update.
|
||||
</p>
|
||||
{(error.includes('404') || error.includes('latest-mac.yml')) && (
|
||||
<div className="mt-3 p-2 bg-gray-800 rounded text-xs text-gray-500">
|
||||
<div className="mt-3 p-2 bg-surface-primary rounded text-xs text-text-tertiary">
|
||||
<p className="font-semibold mb-1">Technical Details:</p>
|
||||
<p>The release may be missing required update metadata files, or you may be testing with a development version.</p>
|
||||
</div>
|
||||
@ -334,7 +331,7 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
{versionInfo?.releaseUrl && (
|
||||
<button
|
||||
onClick={() => window.electronAPI.openExternal(versionInfo.releaseUrl!)}
|
||||
className="mt-3 text-sm text-blue-400 hover:text-blue-300 underline"
|
||||
className="mt-3 text-sm text-interactive hover:text-interactive-hover underline"
|
||||
>
|
||||
View Release on GitHub
|
||||
</button>
|
||||
@ -347,8 +344,8 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
|
||||
{!versionInfo?.hasUpdate && updateState === 'idle' && (
|
||||
<div className="text-center py-8">
|
||||
<CheckCircle className="w-12 h-12 text-green-400 mx-auto mb-3" />
|
||||
<p className="text-gray-300">You're running the latest version of Crystal!</p>
|
||||
<CheckCircle className="w-12 h-12 text-status-success mx-auto mb-3" />
|
||||
<p className="text-text-secondary">You're running the latest version of Crystal!</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@ -356,38 +353,67 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
{/* Release Notes */}
|
||||
{versionInfo?.releaseNotes && (
|
||||
<div className="mt-6">
|
||||
<h3 className="text-lg font-medium text-gray-100 mb-3">Release Notes</h3>
|
||||
<div className="bg-gray-700 rounded-lg p-4 max-h-64 overflow-y-auto">
|
||||
<pre className="text-sm text-gray-300 whitespace-pre-wrap font-sans">
|
||||
{versionInfo.releaseNotes}
|
||||
</pre>
|
||||
<h3 className="text-lg font-medium text-text-primary mb-3">Release Notes</h3>
|
||||
<div className="bg-surface-secondary rounded-lg p-4 max-h-64 overflow-y-auto">
|
||||
<div className="text-sm">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
components={{
|
||||
h1: ({ children }) => <h1 className="text-2xl font-bold mt-4 mb-3 text-text-primary">{children}</h1>,
|
||||
h2: ({ children }) => <h2 className="text-xl font-bold mt-3 mb-2 text-text-primary">{children}</h2>,
|
||||
h3: ({ children }) => <h3 className="text-lg font-bold mt-2 mb-2 text-text-primary">{children}</h3>,
|
||||
h4: ({ children }) => <h4 className="text-base font-bold mt-2 mb-1 text-text-primary">{children}</h4>,
|
||||
p: ({ children }) => <p className="mb-3 text-text-primary">{children}</p>,
|
||||
ul: ({ children }) => <ul className="list-disc mb-3 ml-6 text-text-primary">{children}</ul>,
|
||||
ol: ({ children }) => <ol className="list-decimal mb-3 ml-6 text-text-primary">{children}</ol>,
|
||||
li: ({ children }) => <li className="mb-1 text-text-primary">{children}</li>,
|
||||
blockquote: ({ children }) => (
|
||||
<blockquote className="border-l-4 border-border-secondary pl-4 italic my-3 text-text-tertiary">
|
||||
{children}
|
||||
</blockquote>
|
||||
),
|
||||
a: ({ href, children }) => (
|
||||
<a href={href} className="text-interactive hover:text-interactive-hover underline" target="_blank" rel="noopener noreferrer">
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
code: ({ children }) => (
|
||||
<code className="bg-surface-tertiary px-1 py-0.5 rounded text-text-primary font-mono text-xs">
|
||||
{children}
|
||||
</code>
|
||||
),
|
||||
hr: () => <hr className="my-4 border-border-primary" />,
|
||||
}}
|
||||
>
|
||||
{versionInfo.releaseNotes}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
<div className="p-6 border-t border-gray-700">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="text-sm text-gray-400">
|
||||
{versionInfo?.releaseUrl && (
|
||||
<button
|
||||
onClick={() => window.electronAPI.openExternal(versionInfo.releaseUrl!)}
|
||||
className="hover:text-gray-200 underline transition-colors"
|
||||
>
|
||||
View on GitHub
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 bg-gray-700 text-gray-300 rounded hover:bg-gray-600 transition-colors"
|
||||
disabled={updateState === 'downloading'}
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
<ModalFooter>
|
||||
<div className="flex justify-between items-center w-full">
|
||||
<div className="text-sm text-text-tertiary">
|
||||
{versionInfo?.releaseUrl && (
|
||||
<button
|
||||
onClick={() => window.electronAPI.openExternal(versionInfo.releaseUrl!)}
|
||||
className="hover:text-text-secondary underline transition-colors"
|
||||
>
|
||||
View on GitHub
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={onClose}
|
||||
variant="secondary"
|
||||
disabled={updateState === 'downloading'}
|
||||
>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -1,6 +1,8 @@
|
||||
import React from 'react';
|
||||
import { Zap, CheckCircle, GitBranch } from 'lucide-react';
|
||||
import crystalLogo from '../assets/crystal-logo.svg';
|
||||
import { Modal, ModalBody, ModalFooter } from './ui/Modal';
|
||||
import { Button } from './ui/Button';
|
||||
|
||||
interface WelcomeProps {
|
||||
isOpen: boolean;
|
||||
@ -40,37 +42,36 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden flex flex-col">
|
||||
{/* Header with gradient */}
|
||||
<div className="bg-gradient-to-r from-blue-600 to-purple-600 p-6 text-white">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<img src={crystalLogo} alt="Crystal" className="h-10 w-10 mr-3" />
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Welcome to Crystal</h1>
|
||||
<p className="text-blue-50">Multi-Session Claude Code Manager</p>
|
||||
</div>
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="lg">
|
||||
{/* Header with gradient */}
|
||||
<div className="bg-gradient-to-r from-interactive to-interactive-active p-6 text-on-interactive rounded-t-lg">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<img src={crystalLogo} alt="Crystal" className="h-10 w-10 mr-3" />
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Welcome to Crystal</h1>
|
||||
<p className="text-interactive-text/80">Multi-Session Claude Code Manager</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
</div>
|
||||
|
||||
<ModalBody className="max-h-96 overflow-y-auto">
|
||||
<div className="space-y-6">
|
||||
{/* Quick Start Guide */}
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
|
||||
<Zap className="h-6 w-6 mr-2 text-yellow-500" />
|
||||
<h2 className="text-xl font-semibold text-text-primary mb-4 flex items-center">
|
||||
<Zap className="h-6 w-6 mr-2 text-status-warning" />
|
||||
Quick Start Guide
|
||||
</h2>
|
||||
|
||||
{/* Prerequisites */}
|
||||
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 mb-4">
|
||||
<h3 className="font-semibold text-amber-900 dark:text-amber-200 mb-2 flex items-center">
|
||||
<div className="bg-status-warning/10 border border-status-warning/30 rounded-lg p-4 mb-4">
|
||||
<h3 className="font-semibold text-status-warning mb-2 flex items-center">
|
||||
<CheckCircle className="h-5 w-5 mr-2" />
|
||||
Before You Begin
|
||||
</h3>
|
||||
<ul className="space-y-2 text-amber-800 dark:text-amber-300">
|
||||
<ul className="space-y-2 text-status-warning/80">
|
||||
<li className="flex items-start">
|
||||
<span className="mr-2">•</span>
|
||||
<span>Claude Code must be installed with credentials configured</span>
|
||||
@ -81,7 +82,7 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
|
||||
</li>
|
||||
<li className="flex items-start">
|
||||
<span className="mr-2">•</span>
|
||||
<span>Crystal runs Claude Code with <code className="bg-amber-200 dark:bg-amber-800 px-1 rounded text-sm">--dangerously-ignore-permissions</code></span>
|
||||
<span>Crystal runs Claude Code with <code className="bg-status-warning/20 px-1 rounded text-sm">--dangerously-ignore-permissions</code></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -89,12 +90,12 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
|
||||
{/* Steps */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-blue-600 dark:bg-blue-900 rounded-full flex items-center justify-center text-white dark:text-blue-300 font-semibold">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-interactive rounded-full flex items-center justify-center text-on-interactive font-semibold">
|
||||
1
|
||||
</div>
|
||||
<div className="ml-4 flex-1">
|
||||
<h4 className="font-semibold text-gray-900 dark:text-white mb-1">Create or Select a Project</h4>
|
||||
<ul className="text-gray-600 dark:text-gray-400 space-y-1 text-sm">
|
||||
<h4 className="font-semibold text-text-primary mb-1">Create or Select a Project</h4>
|
||||
<ul className="text-text-secondary space-y-1 text-sm">
|
||||
<li>• Point to a <strong>new directory</strong> - Crystal will create it and initialize git</li>
|
||||
<li>• Or select an <strong>existing git repository</strong></li>
|
||||
</ul>
|
||||
@ -102,12 +103,12 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
|
||||
</div>
|
||||
|
||||
<div className="flex items-start">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-blue-600 dark:bg-blue-900 rounded-full flex items-center justify-center text-white dark:text-blue-300 font-semibold">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-interactive rounded-full flex items-center justify-center text-on-interactive font-semibold">
|
||||
2
|
||||
</div>
|
||||
<div className="ml-4 flex-1">
|
||||
<h4 className="font-semibold text-gray-900 dark:text-white mb-1">Create Sessions</h4>
|
||||
<ul className="text-gray-600 dark:text-gray-400 space-y-1 text-sm">
|
||||
<h4 className="font-semibold text-text-primary mb-1">Create Sessions</h4>
|
||||
<ul className="text-text-secondary space-y-1 text-sm">
|
||||
<li>• Enter a prompt describing what you want Claude to do</li>
|
||||
<li>• <strong>Create multiple sessions</strong> with different prompts to explore various approaches</li>
|
||||
<li>• Or <strong>run the same prompt multiple times</strong> to choose the best result</li>
|
||||
@ -116,13 +117,13 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
|
||||
</div>
|
||||
|
||||
<div className="flex items-start">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-blue-600 dark:bg-blue-900 rounded-full flex items-center justify-center text-white dark:text-blue-300 font-semibold">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-interactive rounded-full flex items-center justify-center text-on-interactive font-semibold">
|
||||
3
|
||||
</div>
|
||||
<div className="ml-4 flex-1">
|
||||
<h4 className="font-semibold text-gray-900 dark:text-white mb-1">Work with Results</h4>
|
||||
<ul className="text-gray-600 dark:text-gray-400 space-y-1 text-sm">
|
||||
<li>• View changes in the <strong>View Diff tab</strong></li>
|
||||
<h4 className="font-semibold text-text-primary mb-1">Work with Results</h4>
|
||||
<ul className="text-text-secondary space-y-1 text-sm">
|
||||
<li>• View changes in the <strong>Diff panel</strong></li>
|
||||
<li>• <strong>Continue conversations</strong> to refine the solution</li>
|
||||
<li>• <strong>Rebase back to main</strong> when you're done</li>
|
||||
</ul>
|
||||
@ -133,71 +134,67 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
|
||||
|
||||
{/* Key Features */}
|
||||
<section className="border-t pt-6">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
|
||||
<h3 className="font-semibold text-text-primary mb-3 flex items-center">
|
||||
<GitBranch className="h-5 w-5 mr-2" />
|
||||
Key Features
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div className="flex items-center text-gray-600 dark:text-gray-400">
|
||||
<CheckCircle className="h-4 w-4 mr-2 text-green-500 flex-shrink-0" />
|
||||
<div className="flex items-center text-text-secondary">
|
||||
<CheckCircle className="h-4 w-4 mr-2 text-status-success flex-shrink-0" />
|
||||
<span>Parallel sessions with git worktrees</span>
|
||||
</div>
|
||||
<div className="flex items-center text-gray-600 dark:text-gray-400">
|
||||
<CheckCircle className="h-4 w-4 mr-2 text-green-500 flex-shrink-0" />
|
||||
<div className="flex items-center text-text-secondary">
|
||||
<CheckCircle className="h-4 w-4 mr-2 text-status-success flex-shrink-0" />
|
||||
<span>Real-time status updates</span>
|
||||
</div>
|
||||
<div className="flex items-center text-gray-600 dark:text-gray-400">
|
||||
<CheckCircle className="h-4 w-4 mr-2 text-green-500 flex-shrink-0" />
|
||||
<div className="flex items-center text-text-secondary">
|
||||
<CheckCircle className="h-4 w-4 mr-2 text-status-success flex-shrink-0" />
|
||||
<span>Session persistence</span>
|
||||
</div>
|
||||
<div className="flex items-center text-gray-600 dark:text-gray-400">
|
||||
<CheckCircle className="h-4 w-4 mr-2 text-green-500 flex-shrink-0" />
|
||||
<div className="flex items-center text-text-secondary">
|
||||
<CheckCircle className="h-4 w-4 mr-2 text-status-success flex-shrink-0" />
|
||||
<span>Git integration</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
|
||||
<button
|
||||
onClick={async () => {
|
||||
const newValue = !dontShowAgain;
|
||||
console.log('[Welcome Debug] Don\'t show again clicked:', newValue);
|
||||
setDontShowAgain(newValue);
|
||||
if (window.electron?.invoke) {
|
||||
try {
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_welcome', newValue ? 'true' : 'false');
|
||||
if (result?.success) {
|
||||
console.log('[Welcome Debug] Successfully set hide_welcome preference to', newValue);
|
||||
} else {
|
||||
console.error('[Welcome Debug] Failed to set preference:', result?.error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Welcome Debug] Error setting preference:', error);
|
||||
<ModalFooter className="flex justify-between items-center">
|
||||
<Button
|
||||
onClick={async () => {
|
||||
const newValue = !dontShowAgain;
|
||||
console.log('[Welcome Debug] Don\'t show again clicked:', newValue);
|
||||
setDontShowAgain(newValue);
|
||||
if (window.electron?.invoke) {
|
||||
try {
|
||||
const result = await window.electron.invoke('preferences:set', 'hide_welcome', newValue ? 'true' : 'false');
|
||||
if (result?.success) {
|
||||
console.log('[Welcome Debug] Successfully set hide_welcome preference to', newValue);
|
||||
} else {
|
||||
console.error('[Welcome Debug] Failed to set preference:', result?.error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Welcome Debug] Error setting preference:', error);
|
||||
}
|
||||
// Close the popup when don't show again is clicked and set to true
|
||||
if (newValue) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
|
||||
dontShowAgain
|
||||
? 'bg-gray-200 dark:bg-gray-700 text-gray-900 dark:text-gray-100 hover:bg-gray-300 dark:hover:bg-gray-600'
|
||||
: 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
{dontShowAgain ? "Will hide on next launch" : "Don't show this again"}
|
||||
</button>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
Get Started
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
// Close the popup when don't show again is clicked and set to true
|
||||
if (newValue) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
variant={dontShowAgain ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
>
|
||||
{dontShowAgain ? "Will hide on next launch" : "Don't show this again"}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onClose}
|
||||
variant="primary"
|
||||
>
|
||||
Get Started
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -4,7 +4,7 @@ import type { RemoteStatus, MainBranchStatus } from '../../types/projectDashboar
|
||||
|
||||
interface MultiOriginStatusProps {
|
||||
mainBranch: string;
|
||||
mainBranchStatus: MainBranchStatus;
|
||||
mainBranchStatus?: MainBranchStatus;
|
||||
remotes?: RemoteStatus[];
|
||||
onReviewUpdates?: () => void;
|
||||
}
|
||||
@ -15,6 +15,11 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
|
||||
remotes = [],
|
||||
onReviewUpdates
|
||||
}) => {
|
||||
// Handle progressive loading - mainBranchStatus might not be available yet
|
||||
if (!mainBranchStatus) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Find upstream and origin remotes
|
||||
const upstream = remotes.find(r => r.isUpstream || r.name === 'upstream');
|
||||
const origin = remotes.find(r => !r.isUpstream && r.name === 'origin');
|
||||
@ -29,13 +34,13 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
|
||||
const getStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
case 'up-to-date':
|
||||
return <CheckCircle className="w-4 h-4 text-green-500" />;
|
||||
return <CheckCircle className="w-4 h-4 text-status-success" />;
|
||||
case 'behind':
|
||||
return <AlertCircle className="w-4 h-4 text-yellow-500" />;
|
||||
return <AlertCircle className="w-4 h-4 text-status-warning" />;
|
||||
case 'ahead':
|
||||
return <Clock className="w-4 h-4 text-blue-500" />;
|
||||
return <Clock className="w-4 h-4 text-interactive" />;
|
||||
case 'diverged':
|
||||
return <AlertCircle className="w-4 h-4 text-red-500" />;
|
||||
return <AlertCircle className="w-4 h-4 text-status-error" />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@ -75,15 +80,15 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
|
||||
if (!hasMultipleRemotes) {
|
||||
// Single remote view (original view)
|
||||
return (
|
||||
<div className="mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<div className="mb-6 p-4 bg-surface-secondary rounded-lg">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<GitBranch className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
<GitBranch className="w-5 h-5 text-text-tertiary" />
|
||||
<div>
|
||||
<h3 className="font-medium text-gray-900 dark:text-gray-100">
|
||||
<h3 className="font-medium text-text-primary">
|
||||
Main Branch ({mainBranch})
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 flex items-center gap-2 mt-1">
|
||||
<p className="text-sm text-text-tertiary flex items-center gap-2 mt-1">
|
||||
{getStatusIcon(mainBranchStatus.status)}
|
||||
{getLocalStatusText()}
|
||||
</p>
|
||||
@ -98,9 +103,9 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
|
||||
return (
|
||||
<div className="mb-6 space-y-3">
|
||||
{/* Multi-Origin Status Flow */}
|
||||
<div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
|
||||
<div className="bg-gray-50 dark:bg-gray-800 px-4 py-2 border-b border-gray-200 dark:border-gray-700">
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">Git Remote Status</h3>
|
||||
<div className="bg-surface-primary border border-border-primary rounded-lg overflow-hidden">
|
||||
<div className="bg-surface-secondary px-4 py-2 border-b border-border-primary">
|
||||
<h3 className="text-sm font-medium text-text-secondary">Git Remote Status</h3>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
@ -109,20 +114,20 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
|
||||
{/* Upstream Status */}
|
||||
{upstream && (
|
||||
<>
|
||||
<div className="flex-1 bg-purple-50 dark:bg-purple-900/20 rounded-lg p-3 border border-purple-200 dark:border-purple-800">
|
||||
<div className="flex-1 bg-interactive/10 rounded-lg p-3 border border-interactive/30">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<GitBranch className="w-4 h-4 text-purple-600 dark:text-purple-400" />
|
||||
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
<GitBranch className="w-4 h-4 text-interactive" />
|
||||
<span className="text-sm font-semibold text-text-primary">
|
||||
{upstream.name}/{upstream.branch}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-400">Source repository</div>
|
||||
<div className="text-xs text-text-tertiary">Source repository</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{upstream.status !== 'up-to-date' && (
|
||||
<span className="text-xs font-medium text-purple-700 dark:text-purple-300">
|
||||
<span className="text-xs font-medium text-interactive">
|
||||
{getStatusText(upstream)}
|
||||
</span>
|
||||
)}
|
||||
@ -131,33 +136,33 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ArrowRight className="w-5 h-5 text-gray-400 flex-shrink-0" />
|
||||
<ArrowRight className="w-5 h-5 text-text-tertiary flex-shrink-0" />
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Origin/Fork Status */}
|
||||
{origin && (
|
||||
<>
|
||||
<div className="flex-1 bg-blue-50 dark:bg-blue-900/20 rounded-lg p-3 border border-blue-200 dark:border-blue-800">
|
||||
<div className="flex-1 bg-interactive/10 rounded-lg p-3 border border-interactive/30">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<GitBranch className="w-4 h-4 text-blue-600 dark:text-blue-400" />
|
||||
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
<GitBranch className="w-4 h-4 text-interactive" />
|
||||
<span className="text-sm font-semibold text-text-primary">
|
||||
{origin.name}/{origin.branch}
|
||||
</span>
|
||||
{origin.isFork && (
|
||||
<span className="inline-flex items-center gap-1 text-xs bg-blue-100 dark:bg-blue-800 text-blue-700 dark:text-blue-300 px-1.5 py-0.5 rounded">
|
||||
<span className="inline-flex items-center gap-1 text-xs bg-interactive/20 text-interactive px-1.5 py-0.5 rounded">
|
||||
<GitFork className="w-3 h-3" />
|
||||
<span>fork</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-400">Your remote</div>
|
||||
<div className="text-xs text-text-tertiary">Your remote</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{origin.status !== 'up-to-date' && (
|
||||
<span className="text-xs font-medium text-blue-700 dark:text-blue-300">
|
||||
<span className="text-xs font-medium text-interactive">
|
||||
{getStatusText(origin)}
|
||||
</span>
|
||||
)}
|
||||
@ -166,28 +171,28 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ArrowRight className="w-5 h-5 text-gray-400 flex-shrink-0" />
|
||||
<ArrowRight className="w-5 h-5 text-text-tertiary flex-shrink-0" />
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Local Main Status */}
|
||||
<div className="flex-1 bg-gray-50 dark:bg-gray-800 rounded-lg p-3 border border-gray-200 dark:border-gray-700">
|
||||
<div className="flex-1 bg-surface-secondary rounded-lg p-3 border border-border-primary">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<GitBranch className="w-4 h-4 text-gray-600 dark:text-gray-400" />
|
||||
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
<GitBranch className="w-4 h-4 text-text-tertiary" />
|
||||
<span className="text-sm font-semibold text-text-primary">
|
||||
{mainBranch}
|
||||
</span>
|
||||
<span className="text-xs bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-1.5 py-0.5 rounded">
|
||||
<span className="text-xs bg-surface-tertiary text-text-secondary px-1.5 py-0.5 rounded">
|
||||
local
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-400">Base for sessions</div>
|
||||
<div className="text-xs text-text-tertiary">Base for sessions</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{mainBranchStatus.status !== 'up-to-date' && (
|
||||
<span className="text-xs font-medium text-gray-700 dark:text-gray-300">
|
||||
<span className="text-xs font-medium text-text-secondary">
|
||||
{getLocalStatusText()}
|
||||
</span>
|
||||
)}
|
||||
@ -200,18 +205,18 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
|
||||
|
||||
{/* Action Bar - Shows when updates are needed */}
|
||||
{hasUpdatesNeeded && (
|
||||
<div className="bg-amber-50 dark:bg-amber-900/20 border-t border-amber-200 dark:border-amber-800 px-4 py-3">
|
||||
<div className="bg-status-warning/10 border-t border-status-warning/30 px-4 py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-amber-600 dark:text-amber-400" />
|
||||
<span className="text-sm font-medium text-amber-800 dark:text-amber-200">
|
||||
<AlertCircle className="w-4 h-4 text-status-warning" />
|
||||
<span className="text-sm font-medium text-status-warning">
|
||||
Updates available in the cascade
|
||||
</span>
|
||||
</div>
|
||||
{onReviewUpdates && (
|
||||
<button
|
||||
onClick={onReviewUpdates}
|
||||
className="text-sm bg-amber-600 hover:bg-amber-700 text-white px-3 py-1.5 rounded font-medium transition-colors"
|
||||
className="text-sm bg-status-warning hover:bg-status-warning-hover text-white px-3 py-1.5 rounded font-medium transition-colors"
|
||||
>
|
||||
Review Updates →
|
||||
</button>
|
||||
@ -221,22 +226,22 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
|
||||
)}
|
||||
|
||||
{/* Flow Legend */}
|
||||
<div className="bg-gray-50 dark:bg-gray-800 px-4 py-2 border-t border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center gap-6 text-xs text-gray-600 dark:text-gray-400">
|
||||
<div className="bg-surface-secondary px-4 py-2 border-t border-border-primary">
|
||||
<div className="flex items-center gap-6 text-xs text-text-tertiary">
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle className="w-3 h-3 text-green-500" />
|
||||
<CheckCircle className="w-3 h-3 text-status-success" />
|
||||
<span>Synced</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="w-3 h-3 text-yellow-500" />
|
||||
<AlertCircle className="w-3 h-3 text-status-warning" />
|
||||
<span>Behind</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="w-3 h-3 text-blue-500" />
|
||||
<Clock className="w-3 h-3 text-interactive" />
|
||||
<span>Ahead</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="w-3 h-3 text-red-500" />
|
||||
<AlertCircle className="w-3 h-3 text-status-error" />
|
||||
<span>Diverged</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import React from 'react';
|
||||
import type { SessionBranchInfo } from '../../types/projectDashboard';
|
||||
import { Card } from '../ui/Card';
|
||||
|
||||
interface StatusSummaryCardsProps {
|
||||
sessions: SessionBranchInfo[];
|
||||
@ -12,40 +13,40 @@ export const StatusSummaryCards: React.FC<StatusSummaryCardsProps> = ({ sessions
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-3 gap-3 mb-6">
|
||||
<div className="bg-white dark:bg-gray-900 p-4 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm">
|
||||
<Card className="p-4">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Up to date</span>
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full"></div>
|
||||
<span className="text-xs font-medium text-text-tertiary uppercase tracking-wider">Up to date</span>
|
||||
<div className="w-2 h-2 bg-status-success rounded-full"></div>
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
|
||||
<div className="text-2xl font-bold text-text-primary">
|
||||
{upToDateCount}
|
||||
<span className="text-sm font-normal text-gray-500 dark:text-gray-400">/{sessions.length}</span>
|
||||
<span className="text-sm font-normal text-text-tertiary">/{sessions.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-900 p-4 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm">
|
||||
</Card>
|
||||
<Card className="p-4">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Stale</span>
|
||||
<div className="w-2 h-2 bg-yellow-500 rounded-full"></div>
|
||||
<span className="text-xs font-medium text-text-tertiary uppercase tracking-wider">Stale</span>
|
||||
<div className="w-2 h-2 bg-status-warning rounded-full"></div>
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
|
||||
<div className="text-2xl font-bold text-text-primary">
|
||||
{staleCount}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-900 p-4 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm">
|
||||
</Card>
|
||||
<Card className="p-4">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Changes</span>
|
||||
<div className="w-2 h-2 bg-orange-500 rounded-full"></div>
|
||||
<span className="text-xs font-medium text-text-tertiary uppercase tracking-wider">Changes</span>
|
||||
<div className="w-2 h-2 bg-status-warning rounded-full"></div>
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
|
||||
<div className="text-2xl font-bold text-text-primary">
|
||||
{needsAttentionCount}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
220
frontend/src/components/demos/ExtendedThinkingDemo.tsx
Normal file
@ -0,0 +1,220 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Cpu, Brain, Zap } from 'lucide-react';
|
||||
import { TogglePill } from '../ui/Pill';
|
||||
import { TogglePillImproved } from '../ui/TogglePillImproved';
|
||||
import { Switch } from '../ui/Switch';
|
||||
import { Card } from '../ui/Card';
|
||||
|
||||
export const ExtendedThinkingDemo: React.FC = () => {
|
||||
const [currentPill, setCurrentPill] = useState(false);
|
||||
const [improvedPill, setImprovedPill] = useState(false);
|
||||
const [switchState, setSwitchState] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="p-8 space-y-8 bg-bg-primary">
|
||||
<h1 className="text-2xl font-bold text-text-primary mb-8">
|
||||
Extended Thinking Toggle - Dark Mode UX Study
|
||||
</h1>
|
||||
|
||||
{/* Current Implementation */}
|
||||
<Card variant="bordered" className="p-6">
|
||||
<h2 className="text-lg font-semibold text-text-primary mb-4">
|
||||
Current Implementation
|
||||
</h2>
|
||||
<div className="flex items-center gap-4 mb-4">
|
||||
<TogglePill
|
||||
checked={currentPill}
|
||||
onCheckedChange={setCurrentPill}
|
||||
icon={<Cpu className="w-2 h-2" />}
|
||||
>
|
||||
Extended Thinking
|
||||
</TogglePill>
|
||||
<span className="text-sm text-text-tertiary">
|
||||
Current TogglePill component
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm text-text-secondary space-y-1">
|
||||
<p>Issues in dark mode:</p>
|
||||
<ul className="list-disc list-inside text-text-tertiary">
|
||||
<li>Poor idle state affordance (looks like static text)</li>
|
||||
<li>Weak hover state (barely visible)</li>
|
||||
<li>Focus ring shows on mouse clicks</li>
|
||||
<li>Small indicator (14px)</li>
|
||||
</ul>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Improved Pill Implementation */}
|
||||
<Card variant="bordered" className="p-6">
|
||||
<h2 className="text-lg font-semibold text-text-primary mb-4">
|
||||
Improved Pill Design
|
||||
</h2>
|
||||
<div className="flex items-center gap-4 mb-4">
|
||||
<TogglePillImproved
|
||||
checked={improvedPill}
|
||||
onCheckedChange={setImprovedPill}
|
||||
icon={<Cpu className="w-3 h-3" />}
|
||||
>
|
||||
Extended Thinking
|
||||
</TogglePillImproved>
|
||||
<span className="text-sm text-text-tertiary">
|
||||
Improved TogglePill with better affordance
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm text-text-secondary space-y-1">
|
||||
<p>Improvements:</p>
|
||||
<ul className="list-disc list-inside text-text-tertiary">
|
||||
<li>Clear interactive surface in idle state</li>
|
||||
<li>Visible hover with elevation and color change</li>
|
||||
<li>:focus-visible for keyboard-only focus</li>
|
||||
<li>Larger indicator (16px) with rounded square shape</li>
|
||||
<li>Smooth transitions on all states</li>
|
||||
</ul>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Recommended Switch Implementation */}
|
||||
<Card variant="bordered" className="p-6 bg-interactive-surface/10">
|
||||
<h2 className="text-lg font-semibold text-text-primary mb-4 flex items-center gap-2">
|
||||
<span className="text-interactive-on-dark">✨</span>
|
||||
Recommended: Switch Component
|
||||
</h2>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Switch
|
||||
checked={switchState}
|
||||
onCheckedChange={setSwitchState}
|
||||
label="Extended Thinking"
|
||||
icon={<Cpu />}
|
||||
size="md"
|
||||
/>
|
||||
<span className="text-sm text-text-tertiary">
|
||||
Industry-standard switch pattern
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="text-sm text-text-secondary space-y-1">
|
||||
<p>Benefits:</p>
|
||||
<ul className="list-disc list-inside text-text-tertiary">
|
||||
<li>Immediately recognizable as toggleable</li>
|
||||
<li>Clear on/off state with position</li>
|
||||
<li>Better accessibility (native switch semantics)</li>
|
||||
<li>Larger click target with label</li>
|
||||
<li>Smooth transitions and micro-interactions</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Size variations */}
|
||||
<div className="mt-6 space-y-3 pt-4 border-t border-border-primary">
|
||||
<h3 className="text-sm font-medium text-text-primary">Size Variations:</h3>
|
||||
<div className="space-y-2">
|
||||
<Switch
|
||||
checked={switchState}
|
||||
onCheckedChange={setSwitchState}
|
||||
label="Small"
|
||||
icon={<Zap />}
|
||||
size="sm"
|
||||
/>
|
||||
<Switch
|
||||
checked={switchState}
|
||||
onCheckedChange={setSwitchState}
|
||||
label="Medium (default)"
|
||||
icon={<Cpu />}
|
||||
size="md"
|
||||
/>
|
||||
<Switch
|
||||
checked={switchState}
|
||||
onCheckedChange={setSwitchState}
|
||||
label="Large"
|
||||
icon={<Brain />}
|
||||
size="lg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Side-by-side comparison */}
|
||||
<Card variant="bordered" className="p-6">
|
||||
<h2 className="text-lg font-semibold text-text-primary mb-4">
|
||||
Side-by-Side Comparison
|
||||
</h2>
|
||||
<div className="grid grid-cols-3 gap-6">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-text-secondary mb-3">Current</h3>
|
||||
<TogglePill
|
||||
checked={currentPill}
|
||||
onCheckedChange={setCurrentPill}
|
||||
icon={<Cpu className="w-2 h-2" />}
|
||||
>
|
||||
Extended Thinking
|
||||
</TogglePill>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-text-secondary mb-3">Improved Pill</h3>
|
||||
<TogglePillImproved
|
||||
checked={improvedPill}
|
||||
onCheckedChange={setImprovedPill}
|
||||
icon={<Cpu className="w-3 h-3" />}
|
||||
>
|
||||
Extended Thinking
|
||||
</TogglePillImproved>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-text-secondary mb-3">Switch (Recommended)</h3>
|
||||
<Switch
|
||||
checked={switchState}
|
||||
onCheckedChange={setSwitchState}
|
||||
label="Extended Thinking"
|
||||
icon={<Cpu />}
|
||||
size="md"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Interaction states preview */}
|
||||
<Card variant="bordered" className="p-6">
|
||||
<h2 className="text-lg font-semibold text-text-primary mb-4">
|
||||
Interaction States (Improved Pill)
|
||||
</h2>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-text-secondary mb-3">Off States</h3>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<TogglePillImproved checked={false} onCheckedChange={() => {}}>
|
||||
Idle
|
||||
</TogglePillImproved>
|
||||
<span className="text-xs text-text-tertiary">Default off state</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<TogglePillImproved checked={false} onCheckedChange={() => {}} disabled>
|
||||
Disabled
|
||||
</TogglePillImproved>
|
||||
<span className="text-xs text-text-tertiary">Disabled state</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-text-secondary mb-3">On States</h3>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<TogglePillImproved checked={true} onCheckedChange={() => {}} icon={<Cpu className="w-3 h-3" />}>
|
||||
Active
|
||||
</TogglePillImproved>
|
||||
<span className="text-xs text-text-tertiary">Active on state</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<TogglePillImproved checked={true} onCheckedChange={() => {}} disabled icon={<Cpu className="w-3 h-3" />}>
|
||||
Disabled
|
||||
</TogglePillImproved>
|
||||
<span className="text-xs text-text-tertiary">Disabled on state</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
34
frontend/src/components/dialog/BaseAIToolConfig.tsx
Normal file
@ -0,0 +1,34 @@
|
||||
import React from 'react';
|
||||
import { Card } from '../ui/Card';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
import type { AttachedImage, AttachedText } from '../../types/session';
|
||||
|
||||
export interface BaseAIToolConfig {
|
||||
prompt?: string;
|
||||
model?: string;
|
||||
attachedImages?: AttachedImage[];
|
||||
attachedTexts?: AttachedText[];
|
||||
ultrathink?: boolean;
|
||||
}
|
||||
|
||||
export interface BaseAIToolConfigProps {
|
||||
config: BaseAIToolConfig;
|
||||
onChange: (config: BaseAIToolConfig) => void;
|
||||
disabled?: boolean;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export const BaseAIToolConfigComponent: React.FC<BaseAIToolConfigProps> = ({
|
||||
children
|
||||
}) => {
|
||||
return (
|
||||
<Card variant="bordered" className="p-4 space-y-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Sparkles className="w-4 h-4 text-interactive" />
|
||||
<span className="text-sm font-medium text-text-secondary">AI Tool Configuration</span>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
334
frontend/src/components/dialog/ClaudeCodeConfig.tsx
Normal file
@ -0,0 +1,334 @@
|
||||
import React, { useRef } from 'react';
|
||||
import { Card } from '../ui/Card';
|
||||
import { Checkbox } from '../ui/Input';
|
||||
import { Shield, ShieldOff, Sparkles, Brain, Target, Zap, Paperclip, X, FileText } from 'lucide-react';
|
||||
import FilePathAutocomplete from '../FilePathAutocomplete';
|
||||
import type { AttachedImage, AttachedText } from '../../types/session';
|
||||
|
||||
export interface ClaudeCodeConfig {
|
||||
prompt?: string;
|
||||
model: 'auto' | 'sonnet' | 'opus' | 'haiku';
|
||||
permissionMode: 'ignore' | 'approve';
|
||||
ultrathink?: boolean;
|
||||
attachedImages?: AttachedImage[];
|
||||
attachedTexts?: AttachedText[];
|
||||
}
|
||||
|
||||
interface ClaudeCodeConfigProps {
|
||||
config: ClaudeCodeConfig;
|
||||
onChange: (config: ClaudeCodeConfig) => void;
|
||||
projectId?: string;
|
||||
disabled?: boolean;
|
||||
onPaste?: (e: React.ClipboardEvent) => void;
|
||||
onRemoveImage?: (id: string) => void;
|
||||
onRemoveText?: (id: string) => void;
|
||||
}
|
||||
|
||||
export const ClaudeCodeConfigComponent: React.FC<ClaudeCodeConfigProps> = ({
|
||||
config,
|
||||
onChange,
|
||||
projectId,
|
||||
disabled = false,
|
||||
onPaste,
|
||||
onRemoveImage,
|
||||
onRemoveText
|
||||
}) => {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const processFile = async (file: File): Promise<AttachedImage | null> => {
|
||||
const generateImageId = () => `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
|
||||
if (!file.type.startsWith('image/')) {
|
||||
console.warn('File is not an image:', file.name);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Limit file size to 10MB
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
console.warn('Image file too large (max 10MB):', file.name);
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
if (e.target?.result) {
|
||||
resolve({
|
||||
id: generateImageId(),
|
||||
name: file.name,
|
||||
dataUrl: e.target.result as string,
|
||||
size: file.size,
|
||||
type: file.type,
|
||||
});
|
||||
} else {
|
||||
resolve(null);
|
||||
}
|
||||
};
|
||||
reader.onerror = () => resolve(null);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
};
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Prompt Field - Hidden since it's now at the top level */}
|
||||
<div className="hidden">
|
||||
<label htmlFor="claude-prompt" className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Initial Prompt
|
||||
</label>
|
||||
{(config.attachedImages?.length ?? 0) > 0 || (config.attachedTexts?.length ?? 0) > 0 ? (
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{config.attachedTexts?.map(text => (
|
||||
<div key={text.id} className="relative group">
|
||||
<div className="h-12 px-3 flex items-center gap-2 bg-surface-secondary rounded border border-border-primary">
|
||||
<FileText className="w-4 h-4 text-text-secondary" />
|
||||
<span className="text-xs text-text-secondary max-w-[150px] truncate">
|
||||
{text.name}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (disabled) return;
|
||||
if (onRemoveText) {
|
||||
onRemoveText(text.id);
|
||||
} else {
|
||||
onChange({
|
||||
...config,
|
||||
attachedTexts: (config.attachedTexts || []).filter(item => item.id !== text.id)
|
||||
});
|
||||
}
|
||||
}}
|
||||
className="absolute -top-1 -right-1 bg-surface-primary border border-border-primary rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-sm"
|
||||
aria-label={`Remove ${text.name}`}
|
||||
>
|
||||
<X className="w-2.5 h-2.5 text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{config.attachedImages?.map(image => (
|
||||
<div key={image.id} className="relative group">
|
||||
<img
|
||||
src={image.dataUrl}
|
||||
alt={image.name}
|
||||
className="h-12 w-12 object-cover rounded border border-border-primary"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (disabled) return;
|
||||
if (onRemoveImage) {
|
||||
onRemoveImage(image.id);
|
||||
} else {
|
||||
onChange({
|
||||
...config,
|
||||
attachedImages: (config.attachedImages || []).filter(item => item.id !== image.id)
|
||||
});
|
||||
}
|
||||
}}
|
||||
className="absolute -top-1 -right-1 bg-surface-primary border border-border-primary rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-sm"
|
||||
aria-label={`Remove ${image.name}`}
|
||||
>
|
||||
<X className="w-2.5 h-2.5 text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="relative">
|
||||
<FilePathAutocomplete
|
||||
value={config.prompt || ''}
|
||||
onChange={(value) => onChange({ ...config, prompt: value })}
|
||||
projectId={projectId}
|
||||
placeholder="Describe your task... (use @ to reference files)"
|
||||
className="w-full px-3 py-2 pr-10 border border-border-primary rounded-md focus:outline-none focus:ring-2 focus:ring-interactive text-text-primary bg-surface-secondary placeholder-text-tertiary"
|
||||
isTextarea={true}
|
||||
rows={3}
|
||||
onPaste={onPaste}
|
||||
disabled={disabled}
|
||||
/>
|
||||
{/* Attachment button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="absolute bottom-2 right-2 p-1.5 rounded hover:bg-surface-hover transition-colors"
|
||||
title="Attach images"
|
||||
disabled={disabled}
|
||||
>
|
||||
<Paperclip className="w-4 h-4 text-text-tertiary hover:text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
{/* Hidden file input */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
disabled={disabled}
|
||||
onChange={async (e) => {
|
||||
const files = Array.from(e.target.files || []);
|
||||
for (const file of files) {
|
||||
const image = await processFile(file);
|
||||
if (image) {
|
||||
onChange({
|
||||
...config,
|
||||
attachedImages: [...(config.attachedImages || []), image]
|
||||
});
|
||||
}
|
||||
}
|
||||
e.target.value = ''; // Reset input
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Model Selection */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Model
|
||||
</label>
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
<Card
|
||||
variant={config.model === 'auto' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
config.model === 'auto'
|
||||
? 'border-interactive bg-interactive/10'
|
||||
: ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, model: 'auto' })}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Sparkles className={`w-5 h-5 ${config.model === 'auto' ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${config.model === 'auto' ? 'text-interactive' : ''}`}>Auto</span>
|
||||
<span className="text-xs opacity-75">Default</span>
|
||||
</div>
|
||||
{config.model === 'auto' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
variant={config.model === 'sonnet' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
config.model === 'sonnet'
|
||||
? 'border-interactive bg-interactive/10'
|
||||
: ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, model: 'sonnet' })}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Target className={`w-5 h-5 ${config.model === 'sonnet' ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${config.model === 'sonnet' ? 'text-interactive' : ''}`}>Sonnet</span>
|
||||
<span className="text-xs opacity-75">Balanced</span>
|
||||
</div>
|
||||
{config.model === 'sonnet' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
variant={config.model === 'opus' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
config.model === 'opus'
|
||||
? 'border-interactive bg-interactive/10'
|
||||
: ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, model: 'opus' })}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Brain className={`w-5 h-5 ${config.model === 'opus' ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${config.model === 'opus' ? 'text-interactive' : ''}`}>Opus</span>
|
||||
<span className="text-xs opacity-75">Maximum</span>
|
||||
</div>
|
||||
{config.model === 'opus' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
variant={config.model === 'haiku' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
config.model === 'haiku'
|
||||
? 'border-status-success bg-status-success/10'
|
||||
: ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, model: 'haiku' })}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Zap className={`w-5 h-5 ${config.model === 'haiku' ? 'text-status-success' : ''}`} />
|
||||
<span className={`text-sm font-medium ${config.model === 'haiku' ? 'text-status-success' : ''}`}>Haiku</span>
|
||||
<span className="text-xs opacity-75">Fast</span>
|
||||
</div>
|
||||
{config.model === 'haiku' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-status-success rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Additional Options */}
|
||||
<div className="space-y-3">
|
||||
{/* Ultrathink Mode */}
|
||||
<Checkbox
|
||||
id="claude-ultrathink"
|
||||
label="Enable ultrathink mode"
|
||||
checked={config.ultrathink || false}
|
||||
onChange={(e) => onChange({ ...config, ultrathink: e.target.checked })}
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
{/* Permission Mode */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Permission Mode
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Card
|
||||
variant={config.permissionMode === 'ignore' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
config.permissionMode === 'ignore'
|
||||
? 'border-interactive bg-interactive/10'
|
||||
: ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, permissionMode: 'ignore' })}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<ShieldOff className={`w-5 h-5 ${config.permissionMode === 'ignore' ? 'text-interactive' : 'text-text-tertiary'}`} />
|
||||
<span className={`text-sm font-medium ${config.permissionMode === 'ignore' ? 'text-interactive' : ''}`}>Skip</span>
|
||||
<span className="text-xs opacity-75">Default</span>
|
||||
</div>
|
||||
{config.permissionMode === 'ignore' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
variant={config.permissionMode === 'approve' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
config.permissionMode === 'approve'
|
||||
? 'border-status-success bg-status-success/10'
|
||||
: ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, permissionMode: 'approve' })}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Shield className={`w-5 h-5 ${config.permissionMode === 'approve' ? 'text-status-success' : ''}`} />
|
||||
<span className={`text-sm font-medium ${config.permissionMode === 'approve' ? 'text-status-success' : ''}`}>Manual</span>
|
||||
<span className="text-xs opacity-75">Approve</span>
|
||||
</div>
|
||||
{config.permissionMode === 'approve' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-status-success rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
344
frontend/src/components/dialog/CodexConfig.tsx
Normal file
@ -0,0 +1,344 @@
|
||||
import React, { useRef } from 'react';
|
||||
import { Card } from '../ui/Card';
|
||||
import { Cpu, Paperclip, X, FileText, Brain, Gauge, Zap } from 'lucide-react';
|
||||
import FilePathAutocomplete from '../FilePathAutocomplete';
|
||||
import { CODEX_MODELS, type OpenAICodexModel } from '../../../../shared/types/models';
|
||||
import type { AttachedImage, AttachedText } from '../../types/session';
|
||||
|
||||
export interface CodexConfig {
|
||||
prompt?: string;
|
||||
model?: OpenAICodexModel;
|
||||
modelProvider?: string;
|
||||
approvalPolicy?: 'auto' | 'manual';
|
||||
sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
|
||||
webSearch?: boolean;
|
||||
thinkingLevel?: 'low' | 'medium' | 'high';
|
||||
attachedImages?: AttachedImage[];
|
||||
attachedTexts?: AttachedText[];
|
||||
}
|
||||
|
||||
interface CodexConfigProps {
|
||||
config: CodexConfig;
|
||||
onChange: (config: CodexConfig) => void;
|
||||
projectId?: string;
|
||||
disabled?: boolean;
|
||||
onPaste?: (e: React.ClipboardEvent) => void;
|
||||
onRemoveImage?: (id: string) => void;
|
||||
onRemoveText?: (id: string) => void;
|
||||
}
|
||||
|
||||
export const CodexConfigComponent: React.FC<CodexConfigProps> = ({
|
||||
config,
|
||||
onChange,
|
||||
projectId,
|
||||
disabled = false,
|
||||
onPaste,
|
||||
onRemoveImage,
|
||||
onRemoveText
|
||||
}) => {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const processFile = async (file: File): Promise<AttachedImage | null> => {
|
||||
const generateImageId = () => `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
|
||||
if (!file.type.startsWith('image/')) {
|
||||
console.warn('File is not an image:', file.name);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Limit file size to 10MB
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
console.warn('Image file too large (max 10MB):', file.name);
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
if (e.target?.result) {
|
||||
resolve({
|
||||
id: generateImageId(),
|
||||
name: file.name,
|
||||
dataUrl: e.target.result as string,
|
||||
size: file.size,
|
||||
type: file.type,
|
||||
});
|
||||
} else {
|
||||
resolve(null);
|
||||
}
|
||||
};
|
||||
reader.onerror = () => resolve(null);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
};
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Prompt Field - Hidden since it's now at the top level */}
|
||||
<div className="hidden">
|
||||
<label htmlFor="codex-prompt" className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Initial Prompt
|
||||
</label>
|
||||
{(config.attachedImages?.length ?? 0) > 0 || (config.attachedTexts?.length ?? 0) > 0 ? (
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{config.attachedTexts?.map(text => (
|
||||
<div key={text.id} className="relative group">
|
||||
<div className="h-12 px-3 flex items-center gap-2 bg-surface-secondary rounded border border-border-primary">
|
||||
<FileText className="w-4 h-4 text-text-secondary" />
|
||||
<span className="text-xs text-text-secondary max-w-[150px] truncate">
|
||||
{text.name}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (disabled) return;
|
||||
if (onRemoveText) {
|
||||
onRemoveText(text.id);
|
||||
} else {
|
||||
onChange({
|
||||
...config,
|
||||
attachedTexts: (config.attachedTexts || []).filter(item => item.id !== text.id)
|
||||
});
|
||||
}
|
||||
}}
|
||||
className="absolute -top-1 -right-1 bg-surface-primary border border-border-primary rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-sm"
|
||||
aria-label={`Remove ${text.name}`}
|
||||
>
|
||||
<X className="w-2.5 h-2.5 text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{config.attachedImages?.map(image => (
|
||||
<div key={image.id} className="relative group">
|
||||
<img
|
||||
src={image.dataUrl}
|
||||
alt={image.name}
|
||||
className="h-12 w-12 object-cover rounded border border-border-primary"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (disabled) return;
|
||||
if (onRemoveImage) {
|
||||
onRemoveImage(image.id);
|
||||
} else {
|
||||
onChange({
|
||||
...config,
|
||||
attachedImages: (config.attachedImages || []).filter(item => item.id !== image.id)
|
||||
});
|
||||
}
|
||||
}}
|
||||
className="absolute -top-1 -right-1 bg-surface-primary border border-border-primary rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-sm"
|
||||
aria-label={`Remove ${image.name}`}
|
||||
>
|
||||
<X className="w-2.5 h-2.5 text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="relative">
|
||||
<FilePathAutocomplete
|
||||
value={config.prompt || ''}
|
||||
onChange={(value) => onChange({ ...config, prompt: value })}
|
||||
projectId={projectId}
|
||||
placeholder="Describe your task... (use @ to reference files)"
|
||||
className="w-full px-3 py-2 pr-10 border border-border-primary rounded-md focus:outline-none focus:ring-2 focus:ring-interactive text-text-primary bg-surface-secondary placeholder-text-tertiary"
|
||||
isTextarea={true}
|
||||
rows={3}
|
||||
onPaste={onPaste}
|
||||
disabled={disabled}
|
||||
/>
|
||||
{/* Attachment button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="absolute bottom-2 right-2 p-1.5 rounded hover:bg-surface-hover transition-colors"
|
||||
title="Attach images"
|
||||
disabled={disabled}
|
||||
>
|
||||
<Paperclip className="w-4 h-4 text-text-tertiary hover:text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
{/* Hidden file input */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
disabled={disabled}
|
||||
onChange={async (e) => {
|
||||
const files = Array.from(e.target.files || []);
|
||||
for (const file of files) {
|
||||
const image = await processFile(file);
|
||||
if (image) {
|
||||
onChange({
|
||||
...config,
|
||||
attachedImages: [...(config.attachedImages || []), image]
|
||||
});
|
||||
}
|
||||
}
|
||||
e.target.value = ''; // Reset input
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Model Selection */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Model
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{Object.values(CODEX_MODELS).filter(m => m.id !== 'auto').map(modelCfg => (
|
||||
<Card
|
||||
key={modelCfg.id}
|
||||
variant={config.model === modelCfg.id ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
config.model === modelCfg.id ? 'border-interactive bg-interactive/10' : ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, model: modelCfg.id as OpenAICodexModel, modelProvider: 'openai' })}
|
||||
title={modelCfg.description}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Cpu className={`w-5 h-5 ${config.model === modelCfg.id ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${config.model === modelCfg.id ? 'text-interactive' : ''}`}>{modelCfg.label}</span>
|
||||
<span className="text-xs opacity-75">OpenAI</span>
|
||||
</div>
|
||||
{config.model === modelCfg.id && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Thinking Level */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Thinking Level
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<Card
|
||||
variant={(config.thinkingLevel || 'medium') === 'low' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
(config.thinkingLevel || 'medium') === 'low' ? 'border-interactive bg-interactive/10' : ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, thinkingLevel: 'low' })}
|
||||
title="Low thinking - Faster responses with less reasoning"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Gauge className={`w-5 h-5 ${(config.thinkingLevel || 'medium') === 'low' ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${(config.thinkingLevel || 'medium') === 'low' ? 'text-interactive' : ''}`}>Low</span>
|
||||
<span className="text-xs opacity-75">Fast</span>
|
||||
</div>
|
||||
{(config.thinkingLevel || 'medium') === 'low' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
<Card
|
||||
variant={(config.thinkingLevel || 'medium') === 'medium' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
(config.thinkingLevel || 'medium') === 'medium' ? 'border-interactive bg-interactive/10' : ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, thinkingLevel: 'medium' })}
|
||||
title="Medium thinking - Balanced speed and reasoning (default)"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Brain className={`w-5 h-5 ${(config.thinkingLevel || 'medium') === 'medium' ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${(config.thinkingLevel || 'medium') === 'medium' ? 'text-interactive' : ''}`}>Medium</span>
|
||||
<span className="text-xs opacity-75">Balanced</span>
|
||||
</div>
|
||||
{(config.thinkingLevel || 'medium') === 'medium' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
<Card
|
||||
variant={(config.thinkingLevel || 'medium') === 'high' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
(config.thinkingLevel || 'medium') === 'high' ? 'border-interactive bg-interactive/10' : ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, thinkingLevel: 'high' })}
|
||||
title="High thinking - Slower but more thorough reasoning"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Zap className={`w-5 h-5 ${(config.thinkingLevel || 'medium') === 'high' ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${(config.thinkingLevel || 'medium') === 'high' ? 'text-interactive' : ''}`}>High</span>
|
||||
<span className="text-xs opacity-75">Thorough</span>
|
||||
</div>
|
||||
{(config.thinkingLevel || 'medium') === 'high' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Additional Options */}
|
||||
<div className="space-y-3">
|
||||
{/* Web Search - Hidden for Codex as it doesn't work */}
|
||||
{/* <Checkbox
|
||||
id="codex-websearch"
|
||||
label="Enable web search"
|
||||
checked={config.webSearch || false}
|
||||
onChange={(e) => onChange({ ...config, webSearch: e.target.checked })}
|
||||
disabled={disabled}
|
||||
/> */}
|
||||
|
||||
{/* Approval Policy - Hidden as Crystal doesn't implement approval handling for Codex */}
|
||||
{/* Manual approval mode requires implementing exec_approval_request and patch_approval_request handlers */}
|
||||
{/* which Crystal currently doesn't support, so we default to 'auto' */}
|
||||
|
||||
{/* Sandbox Mode */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Sandbox Mode
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
<label className={`flex items-center gap-2 cursor-pointer ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}>
|
||||
<input
|
||||
type="radio"
|
||||
name="codex-sandbox"
|
||||
value="read-only"
|
||||
checked={config.sandboxMode === 'read-only'}
|
||||
onChange={(e) => onChange({ ...config, sandboxMode: e.target.value as 'read-only' | 'workspace-write' | 'danger-full-access' })}
|
||||
className="text-interactive"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span className="text-sm text-text-secondary">Read-only</span>
|
||||
</label>
|
||||
<label className={`flex items-center gap-2 cursor-pointer ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}>
|
||||
<input
|
||||
type="radio"
|
||||
name="codex-sandbox"
|
||||
value="workspace-write"
|
||||
checked={config.sandboxMode === 'workspace-write'}
|
||||
onChange={(e) => onChange({ ...config, sandboxMode: e.target.value as 'read-only' | 'workspace-write' | 'danger-full-access' })}
|
||||
className="text-interactive"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span className="text-sm text-text-secondary">Workspace write</span>
|
||||
<span className="text-xs text-text-tertiary">(default)</span>
|
||||
</label>
|
||||
<label className={`flex items-center gap-2 cursor-pointer ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}>
|
||||
<input
|
||||
type="radio"
|
||||
name="codex-sandbox"
|
||||
value="danger-full-access"
|
||||
checked={config.sandboxMode === 'danger-full-access'}
|
||||
onChange={(e) => onChange({ ...config, sandboxMode: e.target.value as 'read-only' | 'workspace-write' | 'danger-full-access' })}
|
||||
className="text-interactive"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span className="text-sm text-status-error">Full access (dangerous)</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
35
frontend/src/components/icons/NimbalystIcon.tsx
Normal file
@ -0,0 +1,35 @@
|
||||
interface NimbalystIconProps {
|
||||
className?: string;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export function NimbalystIcon({ className = '', size = 16 }: NimbalystIconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 1024 1024"
|
||||
className={className}
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="m 196.40239,23.285532 c -0.54602,8.293741 -12.43549,6.934573 -14.77155,14.911232 -1.80051,6.147936 9.8144,9.871544 6.00441,15.021586 -4.94327,6.681938 -14.21051,-0.889398 -20.48824,4.558023 -4.8385,4.198549 2.91945,13.610539 -3.07004,15.883196 -7.77108,2.948667 -11.4738,-8.430992 -19.70006,-7.242327 -6.34031,0.916152 -4.90242,13.028284 -11.16979,11.702004 -8.13162,-1.720786 -5.09423,-13.295805 -12.65725,-16.74329 -5.82912,-2.657116 -11.1678,8.309642 -15.7232,3.80551 C 98.916245,59.337564 107.72938,51.24217 103.23082,44.253089 99.763598,38.86632 89.343337,45.205836 87.946205,38.953881 86.133492,30.842262 97.924274,28.796724 97.918427,20.48503 97.913921,14.078869 85.720439,13.77839 87.925159,7.7635646 90.785679,-0.04039043 101.81062,4.613372 106.29934,-2.3820311 c 3.45964,-5.3916419 -6.635717,-12.2367149 -1.52913,-16.1047469 6.62556,-5.01859 13.38432,4.856936 20.94247,1.398815 5.82538,-2.665315 1.03335,-13.881719 7.4205,-14.374885 8.28703,-0.639859 8.63374,11.322021 16.86167,12.499111 6.34159,0.907231 8.37433,-11.119376 14.01417,-8.081098 7.31742,3.942023 1.14202,14.192444 7.42741,19.6310273 4.8444,4.1917375 13.05652,-4.8267093 16.15844,0.7783797 4.02459,7.27234109 -6.71229,12.5568672 -4.365,20.530232 1.80914,6.145397 13.59336,2.998403 13.17252,9.390728 z"
|
||||
fill="#6395ff"
|
||||
transform="matrix(7.5995429,0,0,7.5995429,-560.09045,326.96861)"
|
||||
/>
|
||||
<text
|
||||
x="306.01437"
|
||||
y="668.91577"
|
||||
style={{
|
||||
fontWeight: 'bold',
|
||||
fontSize: '527.974px',
|
||||
fontFamily: 'Chalkboard SE',
|
||||
fill: '#ffffff',
|
||||
}}
|
||||
>
|
||||
#
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
45
frontend/src/components/panels/DashboardPanel.tsx
Normal file
@ -0,0 +1,45 @@
|
||||
import React from 'react';
|
||||
import { ProjectDashboard } from '../ProjectDashboard';
|
||||
import { useSession } from '../../contexts/SessionContext';
|
||||
|
||||
interface DashboardPanelProps {
|
||||
panelId: string;
|
||||
sessionId: string;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
const DashboardPanel: React.FC<DashboardPanelProps> = () => {
|
||||
const sessionContext = useSession();
|
||||
|
||||
// Get project info from session context
|
||||
const projectIdStr = sessionContext?.projectId;
|
||||
const projectName = sessionContext?.projectName || 'Project';
|
||||
|
||||
if (!projectIdStr) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full bg-gray-900">
|
||||
<div className="text-gray-400">No project selected</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const projectId = parseInt(projectIdStr, 10);
|
||||
if (isNaN(projectId)) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full bg-gray-900">
|
||||
<div className="text-gray-400">Invalid project ID</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full bg-gray-900 overflow-auto">
|
||||
<ProjectDashboard
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DashboardPanel;
|
||||