Compare commits

...

40 Commits

Author SHA1 Message Date
7ace1e2219 fix: validate sessionId and image mime type before building artifact paths
sessions:save-images and sessions:save-large-text (main/src/ipc/session.ts)
joined the caller-supplied sessionId directly into a filesystem path
(CRYSTAL_DIR/artifacts/<sessionId>) with no validation, and derived the
saved image's file extension directly from the caller-supplied MIME
`type` string. A sessionId like `pending_../../../../etc` or a type like
`image/../../../../tmp/x` let the resulting path escape the intended
artifacts directory entirely, allowing arbitrary-content file writes
anywhere the Electron main process can write.

Add main/src/utils/artifactPathSafety.ts with isSafeSessionId (rejects
anything but a plain id, matching both real crypto.randomUUID() session
ids and the renderer's `pending_<ts>_<rand>` ids) and
getSafeImageExtension (allow-list mapping from MIME type to extension,
defaulting to png), and use both in the two handlers before any path is
built. RED confirmed by temporarily short-circuiting isSafeSessionId to
always return true (3 tests failed); reverted and GREEN confirmed
(10/10 new tests pass). tsc --noEmit and eslint clean (0 new
errors/warnings). Full existing main test suite has 19 pre-existing
failures unrelated to this change (confirmed identical on a clean stash
of origin/main before this fix).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-21 04:04:01 +03:00
Jordan Bentley
1e18e0bc98
0.3.5
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 16:44:09 -05:00
Jordan Bentley
844d8a0708
feat: redesign Nimbalyst migration modal with preview image and centered layout
Replace the basic dialog with a custom BrowserWindow modal featuring the Nimbalyst
icon, app preview screenshot, centered layout, and styled action buttons. Include
main/assets in electron-builder files for production builds.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 16:13:30 -05:00
Jordan Bentley
9078c7ff30
feat: expand startup migration modal with website and download links 2026-02-26 13:11:05 -05:00
Jordan Bentley
1ffa091fde
docs: simplify top section and add main/download links 2026-02-26 13:01:20 -05:00
Jordan Bentley
189bb295a5
docs: replace video block with lead hero image 2026-02-26 12:58:45 -05:00
Jordan Bentley
7773fa02bb
docs: center top migration copy and website link 2026-02-26 12:55:27 -05:00
Jordan Bentley
49bcb91fc4
docs: add migration SEO updates and crystal deprecation FAQ 2026-02-26 12:53:00 -05:00
Jordan Bentley
4b2d6097c4
docs: improve dark-mode logo and center migration header section 2026-02-26 12:46:57 -05:00
Jordan Bentley
6a99b8af8c
docs: center migration heading and use github-safe video preview 2026-02-26 12:45:36 -05:00
Jordan Bentley
8c5274bbe8
chore: add nimbalyst migration messaging 2026-02-26 12:40:06 -05:00
Jordan Bentley
6207540804
update to 0.3.4
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-12-19 11:19:25 -05:00
Jordan Bentley
e9099062ff
add a discard and retry button to sessions
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-12-14 14:11:18 -05:00
Jordan Bentley
84073b7728
in a worktree, bring in all MCP servers from the base project
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-12-14 14:10:10 -05:00
Jordan Bentley
928e0e86b6
bugfix: git diff shows commits that are already on main
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-12-09 11:24:22 -05:00
Jordan Bentley
0f7bca7720
When I archive an entire folder it should also delete the folder if it is empty
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-12-02 11:12:21 -05:00
Jordan Bentley
3613ad5370
bugfix: overflow on slash command suggestion
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-12-01 13:31:30 -05:00
Jordan Bentley
a5a89d87cb
0.3.4RC
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 16:12:36 -05:00
Jordan Bentley
9e59515381
archive entire folders on merge
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 15:38:01 -05:00
Jordan Bentley
82dcc24014
run multiple agents in one worktree at a time
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 15:38:01 -05:00
Jordan Bentley
094eebfc8c
fix token usage parsing
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 15:38:01 -05:00
Jordan Bentley
d8849dbda4
add 'merge and archive' button
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 15:38:01 -05:00
Jordan Bentley
36c909de2b
bugfix: wrong script command for run script: https://github.com/stravu/crystal/issues/226
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 15:38:01 -05:00
Jordan Bentley
5d6db07de8
resize file changes panel
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 15:38:01 -05:00
Jordan Bentley
0e2df24cc8
make prompt box resizable
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 15:38:01 -05:00
Jordan Bentley
3bc9a50795
analytics opt-out
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 15:38:01 -05:00
Jordan Bentley
12070f4517
resizeable prompt panel
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-26 15:38:01 -05:00
Jordan Bentley
ab1dc4c366 Update package.json 2025-11-26 15:22:05 -05:00
Brian Caudill
5f36368add docs: Add Windows build requirements documentation
- Add detailed Windows build instructions to troubleshooting guide
- Document requirement for Visual Studio 2022 Spectre-mitigated libraries
- Add Windows build scripts (build:win, build:win:x64) to package.json
- Add Windows configuration for electron-builder (NSIS installer)
- Update README to highlight Windows prerequisites
- Bump version to 0.3.4

This addresses the common build error on Windows where users encounter
"LINK : fatal error LNK1181: cannot open input file 'MSVCRT.lib'"
due to missing Spectre-mitigated libraries.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-26 15:22:05 -05:00
Jordan Bentley
1ed521665f
fix linting errors
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-20 10:18:46 -05:00
Jordan Bentley
df974c9f22
fix dependencies
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-20 09:51:12 -05:00
Jordan Bentley
a551c866e4
when opening nimbalyst use the worktree filter
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-19 14:38:37 -05:00
Jordan Bentley
668be3f659
add anonymous analytics
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-19 12:53:19 -05:00
Jordan Bentley
59807b1166
Don't fail to load if codex/claude not installed
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-19 12:43:03 -05:00
Jordan Bentley
7b3cb5fa08
re-enable nimbalyst button
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-18 08:32:44 -05:00
Jordan Bentley
6e5bf1d94a
open Nimbalyst from crystal
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-11-17 16:24:00 -05:00
Jordan Bentley
ae60f94d27
fix run script state issues
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-10-21 14:44:46 -04:00
Jordan Bentley
551fce4b41
Revert "checkpoint: hi"
This reverts commit d0d7e1bb8f8c63f91a56b7fe5c3976a68ef59e38.
2025-10-20 11:17:24 -04:00
Jordan Bentley
ebb2bbe2eb
bugfix: folder collapse
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-10-20 11:17:24 -04:00
Jordan Bentley
7ed65d03b5
checkpoint: hi
💎 Built using [Crystal](https://github.com/stravu/crystal)

Co-Authored-By: Crystal <crystal@stravu.com>
2025-10-20 11:17:23 -04:00
74 changed files with 4944 additions and 727 deletions

View File

@ -1,6 +1,33 @@
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

138
NOTICES
View File

@ -28,12 +28,10 @@ The following packages are licensed under the MIT license:
- @babel/helper-validator-option (7.27.1) - The Babel Team (https://babel.dev/team)
- @babel/helpers (7.27.6) - The Babel Team (https://babel.dev/team)
- @babel/parser (7.28.0) - The Babel Team (https://babel.dev/team)
- @babel/parser (7.28.4) - The Babel Team (https://babel.dev/team)
- @babel/runtime (7.27.6) - The Babel Team (https://babel.dev/team)
- @babel/template (7.27.2) - The Babel Team (https://babel.dev/team)
- @babel/traverse (7.28.0) - The Babel Team (https://babel.dev/team)
- @babel/types (7.28.1) - The Babel Team (https://babel.dev/team)
- @babel/types (7.28.4) - The Babel Team (https://babel.dev/team)
- @bcoe/v8-coverage (0.2.3) - Charles Samborski <demurgos@demurgos.net> (https://demurgos.net)
- @braintree/sanitize-url (7.1.1)
- @develar/schema-utils (2.6.5) - webpack Contrib (https://github.com/webpack-contrib)
@ -57,7 +55,6 @@ The following packages are licensed under the MIT license:
- @emotion/weak-memoize (0.4.0)
- @esbuild/darwin-arm64 (0.21.5)
- @esbuild/darwin-arm64 (0.25.7)
- @eslint-community/eslint-utils (4.9.0) - Toru Nagashima
- @eslint-community/regexpp (4.12.1) - Toru Nagashima
- @floating-ui/core (1.7.2) - atomiks
- @floating-ui/dom (1.7.2) - atomiks
@ -67,21 +64,16 @@ The following packages are licensed under the MIT license:
- @iconify/types (2.0.0) - Vjacheslav Trushkin
- @iconify/utils (3.0.2) - Vjacheslav Trushkin
- @ioredis/commands (1.2.0) - Zihua Li <i@zihua.li> (http://zihua.li)
- @ioredis/commands (1.4.0) - Zihua Li <i@zihua.li> (http://zihua.li)
- @isaacs/balanced-match (4.0.1)
- @isaacs/brace-expansion (5.0.0)
- @istanbuljs/schema (0.1.3) - Corey Farrell
- @jridgewell/gen-mapping (0.3.12) - Justin Ridgewell <justin@ridgewell.name>
- @jridgewell/gen-mapping (0.3.13) - Justin Ridgewell <justin@ridgewell.name>
- @jridgewell/resolve-uri (3.1.2) - Justin Ridgewell <justin@ridgewell.name>
- @jridgewell/sourcemap-codec (1.5.4) - Justin Ridgewell <justin@ridgewell.name>
- @jridgewell/sourcemap-codec (1.5.5) - Justin Ridgewell <justin@ridgewell.name>
- @jridgewell/trace-mapping (0.3.29) - Justin Ridgewell <justin@ridgewell.name>
- @jridgewell/trace-mapping (0.3.31) - Justin Ridgewell <justin@ridgewell.name>
- @malept/flatpak-bundler (0.4.0) - Matt Watson <mattdangerw@gmail.com>
- @mermaid-js/parser (0.6.2) - Yokozuna59
- @modelcontextprotocol/sdk (1.16.0) - Anthropic, PBC (https://anthropic.com)
- @modelcontextprotocol/sdk (1.18.2) - Anthropic, PBC (https://anthropic.com)
- @monaco-editor/loader (1.5.0) - Suren Atoyan <contact@surenatoyan.com>
- @msgpackr-extract/msgpackr-extract-darwin-arm64 (3.0.3) - Kris Zyp
- @nodelib/fs.scandir (2.1.5)
@ -89,19 +81,17 @@ The following packages are licensed under the MIT license:
- @nodelib/fs.walk (1.2.8)
- @npmcli/move-file (2.0.1) - GitHub Inc.
- @pkgjs/parseargs (0.11.0)
- @posthog/core (1.5.2)
- @radix-ui/number (1.1.1)
- @radix-ui/primitive (1.1.2)
- @radix-ui/rect (1.1.1)
- @rolldown/pluginutils (1.0.0-beta.27)
- @rollup/rollup-darwin-arm64 (4.45.1) - Lukas Taegert-Atkinson
- @rollup/rollup-darwin-arm64 (4.52.3) - Lukas Taegert-Atkinson
- @sindresorhus/is (4.6.0) - Sindre Sorhus
- @standard-schema/spec (1.0.0) - Colin McDonnell
- @szmarczak/http-timer (4.0.6) - Szymon Marczak
- @tootallnate/once (2.0.0) - Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)
- @vitest/coverage-v8 (2.1.9) - Anthony Fu <anthonyfu117@hotmail.com>
- @vitest/expect (2.1.9)
- @vitest/mocker (2.1.9)
- @vitest/pretty-format (2.1.9)
- @vitest/runner (2.1.9)
- @vitest/snapshot (2.1.9)
@ -123,7 +113,6 @@ The following packages are licensed under the MIT license:
- ajv-keywords (3.5.2) - Evgeny Poberezkin
- ansi-regex (5.0.1) - Sindre Sorhus
- ansi-regex (6.1.0) - Sindre Sorhus
- ansi-regex (6.2.2) - Sindre Sorhus
- ansi-styles (4.3.0) - Sindre Sorhus
- ansi-styles (6.2.1) - Sindre Sorhus
- ansi-to-html (0.7.2) - Rob Burns
@ -169,7 +158,6 @@ The following packages are licensed under the MIT license:
- camelcase-css (2.0.1) - Steven Vachon <contact@svachon.com> (https://www.svachon.com/)
- ccount (2.0.1) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
- chai (5.2.1) - Jake Luer <jake@alogicalparadox.com>
- chai (5.3.3) - Jake Luer <jake@alogicalparadox.com>
- chalk (4.1.2)
- character-entities (2.0.2) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
- character-entities-html4 (2.1.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
@ -225,7 +213,6 @@ The following packages are licensed under the MIT license:
- dayjs (1.11.13) - iamkun
- debounce-fn (6.0.0) - Sindre Sorhus
- debug (4.4.1) - Josh Junon (https://github.com/qix-)
- debug (4.4.3) - Josh Junon (https://github.com/qix-)
- decode-named-character-reference (1.2.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
- decompress-response (6.0.0) - Sindre Sorhus
- deep-eql (5.0.2) - Jake Luer <jake@alogicalparadox.com>
@ -279,7 +266,6 @@ The following packages are licensed under the MIT license:
- etag (1.8.1)
- eventsource (3.0.7) - Espen Hovlandsdal <espen@hovlandsdal.com>
- eventsource-parser (3.0.3) - Espen Hovlandsdal <espen@hovlandsdal.com>
- eventsource-parser (3.0.6) - Espen Hovlandsdal <espen@hovlandsdal.com>
- express (5.1.0) - TJ Holowaychuk <tj@vision-media.ca>
- express-rate-limit (7.5.1) - Nathan Friedly
- exsolve (1.0.7)
@ -349,9 +335,7 @@ The following packages are licensed under the MIT license:
- indent-string (4.0.0) - Sindre Sorhus
- inline-style-parser (0.2.4)
- ioredis (5.6.1) - Zihua Li <i@zihua.li> (http://zihua.li)
- ioredis (5.8.0) - Zihua Li <i@zihua.li> (http://zihua.li)
- ip-address (9.0.5) - Beau Gunderson <beau@beaugunderson.com> (https://beaugunderson.com/)
- ip-address (10.0.1) - Beau Gunderson <beau@beaugunderson.com> (https://beaugunderson.com/)
- ipaddr.js (1.9.1) - whitequark <whitequark@whitequark.org>
- is-alphabetical (2.0.1) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
- is-alphanumerical (2.0.1) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
@ -408,12 +392,9 @@ The following packages are licensed under the MIT license:
- longest-streak (3.1.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
- loose-envify (1.4.0) - Andres Suarez <zertosh@gmail.com>
- loupe (3.1.4) - Veselin Todorov <hi@vesln.com>
- loupe (3.2.1) - Veselin Todorov <hi@vesln.com>
- lowercase-keys (2.0.0) - Sindre Sorhus
- luxon (3.7.1) - Isaac Cambron
- luxon (3.7.2) - Isaac Cambron
- magic-string (0.30.17) - Rich Harris
- magic-string (0.30.19) - Rich Harris
- magicast (0.3.5)
- make-dir (4.0.0) - Sindre Sorhus
- markdown-table (3.0.4) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
@ -529,7 +510,6 @@ The following packages are licensed under the MIT license:
- path-key (3.1.1) - Sindre Sorhus
- path-parse (1.0.7) - Javier Blanco <http://jbgutierrez.info>
- path-to-regexp (8.2.0)
- path-to-regexp (8.3.0)
- path-type (4.0.0) - Sindre Sorhus
- pathe (1.1.2)
- pathe (2.0.3)
@ -546,6 +526,7 @@ The following packages are licensed under the MIT license:
- plist (3.1.0) - Nathan Rajlich <nathan@tootallnate.net>
- points-on-curve (0.2.0) - Preet Shihn
- points-on-path (0.2.1) - Preet Shihn
- posthog-node (5.11.2) - PostHog
- prebuild-install (7.1.3) - Mathias Buus (@mafintosh)
- prelude-ls (1.2.1) - George Zahariev <z@georgezahariev.com>
- progress (2.0.3) - TJ Holowaychuk <tj@vision-media.ca>
@ -561,7 +542,6 @@ The following packages are licensed under the MIT license:
- quick-lru (5.1.1) - Sindre Sorhus
- range-parser (1.2.1) - TJ Holowaychuk <tj@vision-media.ca> (http://tjholowaychuk.com)
- raw-body (3.0.0) - Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)
- raw-body (3.0.1) - Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)
- react (19.1.0)
- react-diff-viewer-continued (3.4.0)
- react-dom (19.1.0)
@ -590,7 +570,6 @@ The following packages are licensed under the MIT license:
- retry (0.12.0) - Tim Koschützki <tim@debuggable.com> (http://debuggable.com/)
- reusify (1.1.0) - Matteo Collina <hello@matteocollina.com>
- rollup (4.45.1) - Rich Harris
- rollup (4.52.3) - Rich Harris
- roughjs (4.6.6) - Preet Shihn <preetshihn@gmail.com>
- router (2.2.0) - Douglas Christopher Wilson <doug@somethingdoug.com>
- run-parallel (1.2.0) - Feross Aboukhadijeh
@ -614,7 +593,6 @@ The following packages are licensed under the MIT license:
- slice-ansi (3.0.0)
- smart-buffer (4.2.0) - Josh Glazebrook
- socks (2.8.6) - Josh Glazebrook
- socks (2.8.7) - Josh Glazebrook
- socks-proxy-agent (7.0.0) - Nathan Rajlich
- socks-proxy-agent (8.0.5) - Nathan Rajlich
- source-map-support (0.5.21)
@ -632,7 +610,6 @@ The following packages are licensed under the MIT license:
- stringify-entities (4.0.4) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
- strip-ansi (6.0.1) - Sindre Sorhus
- strip-ansi (7.1.0) - Sindre Sorhus
- strip-ansi (7.1.2) - Sindre Sorhus
- strip-json-comments (2.0.1) - Sindre Sorhus
- strip-json-comments (3.1.1) - Sindre Sorhus
- style-to-js (1.1.17) - Mark <mark@remarkablemark.org>
@ -646,7 +623,6 @@ The following packages are licensed under the MIT license:
- tagged-tag (1.0.0) - Sindre Sorhus
- tailwind-merge (2.6.0) - Dany Castillo
- tar-fs (2.1.3) - Mathias Buus
- tar-fs (2.1.4) - Mathias Buus
- tar-stream (2.2.0) - Mathias Buus <mathiasbuus@gmail.com>
- temp-file (3.4.0) - Vladimir Krivosheev
- thenify (3.3.1) - Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)
@ -657,7 +633,6 @@ The following packages are licensed under the MIT license:
- tinyexec (0.3.2) - James Garbutt (https://github.com/43081j)
- tinyexec (1.0.1) - James Garbutt (https://github.com/43081j)
- tinyglobby (0.2.14) - Superchupu
- tinyglobby (0.2.15) - Superchupu
- tinypool (1.1.1)
- tinyrainbow (1.2.0)
- tinyspy (3.0.2)
@ -884,7 +859,6 @@ The following packages are licensed under the Apache-2.0 license:
- @chevrotain/utils (11.0.3) - Shahar Soel
- @humanfs/core (0.19.1) - Nicholas C. Zakas
- @humanfs/node (0.16.6) - Nicholas C. Zakas
- @humanfs/node (0.16.7) - Nicholas C. Zakas
- @humanwhocodes/module-importer (1.0.1) - Nicholas C. Zaks
- @humanwhocodes/retry (0.3.1) - Nicholas C. Zaks
- @humanwhocodes/retry (0.4.3) - Nicholas C. Zaks
@ -895,7 +869,6 @@ The following packages are licensed under the Apache-2.0 license:
- cluster-key-slot (1.1.2) - Mike Diarmid
- denque (2.1.0) - Invertase
- detect-libc (2.0.4) - Lovell Fuller <npm@lovell.info>
- detect-libc (2.1.1) - Lovell Fuller <npm@lovell.info>
- didyoumean (1.2.2) - Dave Porter
- ejs (3.1.10) - Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)
- expect-type (1.2.2)
@ -1499,46 +1472,6 @@ The complete list of contributors can be found at:
--------------------------------------------------------------------------------
Package: fast-uri
Version: 3.1.0
Author: Vincent Le Goff <vince.legoff@gmail.com> (https://github.com/zekth)
Homepage: https://github.com/fastify/fast-uri
Copyright (c) 2011-2021, Gary Court until https://github.com/garycourt/uri-js/commit/a1acf730b4bba3f1097c9f52e7d9d3aba8cdcaae
Copyright (c) 2021-present The Fastify team
All rights reserved.
The Fastify team members are listed at https://github.com/fastify/fastify#team.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of any contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* * *
The complete list of contributors can be found at:
- https://github.com/garycourt/uri-js/graphs/contributors
--------------------------------------------------------------------------------
Package: global-agent
Version: 3.0.0
Author: Gajus Kuizinas
@ -1718,38 +1651,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
Package: istanbul-reports
Version: 3.2.0
Author: Krishnan Anantheswaran <kananthmail-github@yahoo.com>
Homepage: https://istanbul.js.org/
Copyright 2012-2015 Yahoo! Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yahoo! Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
Package: joi
Version: 18.0.1
Repository: git://github.com/hapijs/joi
@ -2608,28 +2509,6 @@ DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
================================================================================
## SEE LICENSE IN README.md LICENSE
================================================================================
Package: @anthropic-ai/claude-code
Version: 2.0.0
Author: Anthropic <support@anthropic.com>
Homepage: https://github.com/anthropics/claude-code
© Anthropic PBC. All rights reserved. Use is subject to Anthropic's [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms).
--------------------------------------------------------------------------------
Package: @anthropic-ai/claude-code
Version: 2.0.1
Author: Anthropic <support@anthropic.com>
Homepage: https://github.com/anthropics/claude-code
© Anthropic PBC. All rights reserved. Use is subject to Anthropic's [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms).
--------------------------------------------------------------------------------
================================================================================
## (BSD-2-Clause OR MIT OR Apache-2.0) LICENSE
================================================================================
@ -3930,6 +3809,19 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
================================================================================
## SEE LICENSE IN README.md LICENSE
================================================================================
Package: @anthropic-ai/claude-code
Version: 2.0.0
Author: Anthropic <support@anthropic.com>
Homepage: https://github.com/anthropics/claude-code
© Anthropic PBC. All rights reserved. Use is subject to Anthropic's [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms).
--------------------------------------------------------------------------------
================================================================================
## Unlicense LICENSE
================================================================================

225
README.md
View File

@ -1,199 +1,56 @@
# Crystal - Multi-Session AI Code Assistant 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">
[![Build](https://github.com/stravu/crystal/actions/workflows/build.yml/badge.svg)](https://github.com/stravu/crystal/actions/workflows/build.yml)
[![Quality](https://github.com/stravu/crystal/actions/workflows/quality.yml/badge.svg)](https://github.com/stravu/crystal/actions/workflows/quality.yml)
[![Join our Discord](https://img.shields.io/badge/Join%20our-Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](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>
<div align="center">
<strong>Crystal lets you use AI on isolated copies of your code so you can work on multiple tasks instead of waiting for your agents to finish.</strong>
<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>
<br>
<br>
## Migration
<div align="center">
<img src="https://github.com/user-attachments/assets/45ca7166-e69a-4ed2-8ef5-ef83dc52ffd6" alt="Run one or more sessions with Claude Code, Codex, or both" width="400"/>
<p><em>Run one or more sessions with Claude Code, Codex, or both</em></p>
</div>
- Download Nimbalyst: https://nimbalyst.com/
- Documentation: https://docs.nimbalyst.com/
- GitHub repository: https://github.com/Nimbalyst/nimbalyst
<div align="center">
<table>
<tr>
<td align="center" width="50%">
<img src="https://github.com/user-attachments/assets/e180691e-aaa3-4171-bdae-3b0459dcc495" alt="Rich output for your agents" width="400"/>
<p><em>Rich output for your agents</em></p>
</td>
<td align="center" width="50%">
<img src="https://github.com/user-attachments/assets/1f64ac92-9158-4e83-997e-6650a9bc9072" alt="Run your code and test before merging" width="400"/>
<p><em>Run your code and test before merging</em></p>
</td>
</tr>
</table>
</div>
## Nimbalyst Features
<div align="center" style="max-width: 600px; margin: 0 auto;">
- 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
https://github.com/user-attachments/assets/5ca66e5b-8d05-4570-8417-5e8dcd7726ef
## FAQ
</div>
- **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/
---
## The Crystal Workflow
1. Create sessions from prompts, each in an isolated git worktree
2. Iterate with your AI assistant (Claude Code or Codex) 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 merge to your main branch.
---
## 🚀 Quick Start
### Prerequisites
- **For Claude Code**: Claude Code installed and logged in or API key provided
- **For Codex**: Codex installed (via npm: `@openai/codex` or Homebrew) with ChatGPT account or API key
- 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 your AI assistant 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
- **Windows** (Unofficial - Build from source): Windows is currently supported through local builds only. An installer will be provided in future releases.
- Follow the "Building from Source" instructions below
### Homebrew
```bash
brew install --cask stravu-crystal
```
---
## 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
### Using with Third-Party Deployments
To use Crystal with cloud providers or via corporate infrastructure, you should create a [settings](https://docs.anthropic.com/en/docs/claude-code/settings) file with `ENV` values to correctly connect to the provider.
For example, here is a minimal configuration to use Amazon Bedrock via an AWS Profile:
```json5
{
"env": {
"CLAUDE_CODE_USE_BEDROCK": "1",
"AWS_REGION": "us-east-2", // Replace with your AWS region
"AWS_PROFILE": "my-aws-profile" // Replace with your profile
},
}
```
Check the [deployment documentation](https://docs.anthropic.com/en/docs/claude-code/third-party-integrations) for more information on getting setup with your particular deployment.
---
## 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. Codex™ is a trademark of OpenAI, Inc. Crystal is not affiliated with, endorsed by, or sponsored by Anthropic or OpenAI. This tool is designed to work with Claude Code and Codex, 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>
</div>
For downloads, documentation, and updates, go to **https://nimbalyst.com/**.

View 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.

View 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 |

View File

@ -36,4 +36,40 @@ brew install python-setuptools
### pnpm permission errors
- Never use `sudo` with pnpm
- Fix npm permissions: `npm config set prefix ~/.npm-global`
- 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.

View File

@ -1,6 +1,6 @@
{
"name": "frontend",
"version": "0.3.3",
"version": "0.3.5",
"private": true,
"type": "module",
"scripts": {

View 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

View File

@ -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';
@ -39,6 +40,8 @@ interface PermissionRequest {
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<VersionUpdateInfo | null>(null);
@ -65,7 +68,36 @@ function App() {
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
@ -124,7 +156,8 @@ 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
if (!isLoaded || hasCheckedWelcome) {
// Don't show welcome while analytics consent dialog is open
if (!isLoaded || hasCheckedWelcome || isAnalyticsConsentOpen) {
return;
}
@ -132,7 +165,7 @@ function App() {
if (!window.electron?.invoke) {
return;
}
// Get preferences from database
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>;
@ -223,7 +256,7 @@ function App() {
// Set the flag first to prevent re-runs
setHasCheckedWelcome(true);
checkInitialState();
}, [isLoaded]); // Only depend on isLoaded, not hasCheckedWelcome to prevent loops
}, [isLoaded, isAnalyticsConsentOpen]); // Also wait for analytics consent dialog to close
// Discord popup logic is now combined with welcome screen logic above
@ -252,7 +285,9 @@ function App() {
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
);
};
@ -313,6 +348,10 @@ function App() {
/>
<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

View 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

View 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>
);
}

View File

@ -55,32 +55,63 @@ interface CreateSessionDialogProps {
projectId?: number;
initialPrompt?: string;
initialSessionName?: string;
// For "Discard and Retry" feature - pre-fill session creation settings
initialToolType?: 'claude' | 'codex' | 'none';
initialBaseBranch?: string;
initialFolderId?: string; // Folder to create the new session in
initialClaudeConfig?: {
model?: 'auto' | 'sonnet' | 'opus' | 'haiku';
permissionMode?: 'approve' | 'ignore';
ultrathink?: boolean;
};
initialCodexConfig?: {
model?: string;
modelProvider?: string;
sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
webSearch?: boolean;
thinkingLevel?: 'low' | 'medium' | 'high';
};
// Callback called after session is successfully created (for "Discard and Retry" to archive old session)
onSessionCreated?: () => void;
}
export function CreateSessionDialog({ isOpen, onClose, projectName, projectId, initialPrompt, initialSessionName }: CreateSessionDialogProps) {
export function CreateSessionDialog({
isOpen,
onClose,
projectName,
projectId,
initialPrompt,
initialSessionName,
initialToolType,
initialBaseBranch,
initialFolderId,
initialClaudeConfig,
initialCodexConfig,
onSessionCreated
}: CreateSessionDialogProps) {
const [sessionName, setSessionName] = useState<string>(initialSessionName || '');
const [sessionCount, setSessionCount] = useState<number>(1);
const [selectedTools, setSelectedTools] = useState<{ claude: boolean; codex: boolean }>({
claude: !!initialPrompt,
codex: false
claude: initialToolType === 'claude' || !!initialPrompt,
codex: initialToolType === 'codex'
});
const [sharedPrompt, setSharedPrompt] = useState<string>(initialPrompt || '');
const [claudeConfig, setClaudeConfig] = useState<ClaudeCodeConfig>({
prompt: initialPrompt || '',
model: 'auto',
permissionMode: 'ignore',
ultrathink: false,
model: initialClaudeConfig?.model || 'auto',
permissionMode: initialClaudeConfig?.permissionMode || 'ignore',
ultrathink: initialClaudeConfig?.ultrathink || false,
attachedImages: [],
attachedTexts: []
});
const [codexConfig, setCodexConfig] = useState<CodexConfig>({
prompt: initialPrompt || '',
model: DEFAULT_CODEX_MODEL,
modelProvider: 'openai',
model: (initialCodexConfig?.model as OpenAICodexModel) || DEFAULT_CODEX_MODEL,
modelProvider: initialCodexConfig?.modelProvider || 'openai',
approvalPolicy: 'auto', // Always 'auto' - manual mode not implemented
sandboxMode: 'workspace-write',
webSearch: false,
thinkingLevel: 'medium',
sandboxMode: initialCodexConfig?.sandboxMode || 'workspace-write',
webSearch: initialCodexConfig?.webSearch || false,
thinkingLevel: initialCodexConfig?.thinkingLevel || 'medium',
attachedImages: [],
attachedTexts: []
});
@ -88,7 +119,8 @@ export function CreateSessionDialog({ isOpen, onClose, projectName, projectId, i
prompt: initialPrompt || '',
worktreeTemplate: '',
count: 1,
permissionMode: 'ignore'
permissionMode: 'ignore',
baseBranch: initialBaseBranch
// Model is now managed at panel level, not session level
});
const [isSubmitting, setIsSubmitting] = useState(false);
@ -186,7 +218,7 @@ export function CreateSessionDialog({ isOpen, onClose, projectName, projectId, i
setSessionName(initialSessionName);
}
setSessionCount(1);
setFormData(prev => ({ ...prev, count: 1 }));
setFormData(prev => ({ ...prev, count: 1, baseBranch: initialBaseBranch }));
// Only clear prompts if there's no initialPrompt
if (!initialPrompt) {
syncPromptAcrossConfigs('');
@ -196,50 +228,91 @@ export function CreateSessionDialog({ isOpen, onClose, projectName, projectId, i
}
syncImageAttachments(() => []);
syncTextAttachments(() => []);
}
}, [isOpen, loadPreferences, syncPromptAcrossConfigs, syncImageAttachments, syncTextAttachments, initialPrompt, initialSessionName]);
// Apply loaded preferences to state
useEffect(() => {
if (preferences) {
// Map the old toolType preference to the new selectedTools state
if (initialPrompt) {
// If we have an initialPrompt, default to Claude being selected
setSelectedTools({ claude: true, codex: false });
} else if (preferences.selectedTools) {
// Apply initial tool type if provided (for "Discard and Retry")
if (initialToolType) {
setSelectedTools({
claude: !!preferences.selectedTools.claude,
codex: !!preferences.selectedTools.codex
});
} else if (preferences.toolType) {
// Map old preference format to new checkbox format
setSelectedTools({
claude: preferences.toolType === 'claude',
codex: preferences.toolType === 'codex'
claude: initialToolType === 'claude',
codex: initialToolType === 'codex'
});
}
setClaudeConfig(prev => ({
...prev,
model: preferences.claudeConfig.model,
permissionMode: preferences.claudeConfig.permissionMode,
ultrathink: preferences.claudeConfig.ultrathink
}));
setCodexConfig(prev => ({
...prev,
model: preferences.codexConfig.model as OpenAICodexModel,
modelProvider: preferences.codexConfig.modelProvider,
approvalPolicy: 'auto', // Always 'auto' - manual mode not implemented
sandboxMode: preferences.codexConfig.sandboxMode,
webSearch: preferences.codexConfig.webSearch,
thinkingLevel: preferences.codexConfig.thinkingLevel || 'medium'
}));
// Apply initial Claude config if provided
if (initialClaudeConfig) {
setClaudeConfig(prev => ({
...prev,
model: initialClaudeConfig.model ?? prev.model,
permissionMode: initialClaudeConfig.permissionMode ?? prev.permissionMode,
ultrathink: initialClaudeConfig.ultrathink ?? prev.ultrathink
}));
}
// Apply initial Codex config if provided
if (initialCodexConfig) {
setCodexConfig(prev => ({
...prev,
model: (initialCodexConfig.model as OpenAICodexModel) || prev.model,
modelProvider: initialCodexConfig.modelProvider || prev.modelProvider,
sandboxMode: initialCodexConfig.sandboxMode || prev.sandboxMode,
webSearch: initialCodexConfig.webSearch ?? prev.webSearch,
thinkingLevel: initialCodexConfig.thinkingLevel || prev.thinkingLevel
}));
}
}
}, [isOpen, loadPreferences, syncPromptAcrossConfigs, syncImageAttachments, syncTextAttachments, initialPrompt, initialSessionName, initialToolType, initialBaseBranch, initialClaudeConfig, initialCodexConfig]);
// Apply loaded preferences to state (only if initial configs not provided)
useEffect(() => {
if (preferences) {
// Map the old toolType preference to the new selectedTools state
// Skip if initialToolType is provided (for "Discard and Retry")
if (!initialToolType) {
if (initialPrompt) {
// If we have an initialPrompt, default to Claude being selected
setSelectedTools({ claude: true, codex: false });
} else if (preferences.selectedTools) {
setSelectedTools({
claude: !!preferences.selectedTools.claude,
codex: !!preferences.selectedTools.codex
});
} else if (preferences.toolType) {
// Map old preference format to new checkbox format
setSelectedTools({
claude: preferences.toolType === 'claude',
codex: preferences.toolType === 'codex'
});
}
}
// Only apply Claude config from preferences if no initial config provided
if (!initialClaudeConfig) {
setClaudeConfig(prev => ({
...prev,
model: preferences.claudeConfig.model,
permissionMode: preferences.claudeConfig.permissionMode,
ultrathink: preferences.claudeConfig.ultrathink
}));
}
// Only apply Codex config from preferences if no initial config provided
if (!initialCodexConfig) {
setCodexConfig(prev => ({
...prev,
model: preferences.codexConfig.model as OpenAICodexModel,
modelProvider: preferences.codexConfig.modelProvider,
approvalPolicy: 'auto', // Always 'auto' - manual mode not implemented
sandboxMode: preferences.codexConfig.sandboxMode,
webSearch: preferences.codexConfig.webSearch,
thinkingLevel: preferences.codexConfig.thinkingLevel || 'medium'
}));
}
setShowAdvanced(preferences.showAdvanced);
setCommitModeSettings(preferences.commitModeSettings);
// Note: we don't apply baseBranch as it should be project-specific
}
}, [preferences, initialPrompt]);
}, [preferences, initialPrompt, initialToolType, initialClaudeConfig, initialCodexConfig]);
// Save preferences when certain settings change
const savePreferences = useCallback(async (updates: Partial<SessionCreationPreferences>) => {
@ -597,10 +670,11 @@ export function CreateSessionDialog({ isOpen, onClose, projectName, projectId, i
// Determine if we need to create a folder
// Create folder when: multiple sessions (sessionCount > 1) OR multiple tools selected
const shouldCreateFolder = sessionCount > 1 || toolsToCreate.length > 1;
// But NOT if we already have an initialFolderId (from "Discard and Retry")
const shouldCreateFolder = !initialFolderId && (sessionCount > 1 || toolsToCreate.length > 1);
// Create folder first if needed
let folderId: string | undefined;
// Use initialFolderId if provided, otherwise create folder if needed
let folderId: string | undefined = initialFolderId;
if (shouldCreateFolder && projectId) {
try {
const folderResponse = await API.folders.create(baseSessionName, projectId);
@ -693,6 +767,11 @@ export function CreateSessionDialog({ isOpen, onClose, projectName, projectId, i
}
}
// Call onSessionCreated callback (e.g., to archive old session in "Discard and Retry")
if (onSessionCreated) {
onSessionCreated();
}
onClose();
} catch (error: unknown) {
console.error('Error creating session:', error);

View File

@ -99,6 +99,27 @@ export function DraggableProjectTreeView({ sessionSortAscending }: DraggableProj
const [isLoadingArchived, setIsLoadingArchived] = useState(false);
const [showCreateDialog, setShowCreateDialog] = useState(false);
const [selectedProjectForCreate, setSelectedProjectForCreate] = useState<Project | null>(null);
// State for "Discard and Retry" feature - pre-fill create dialog with previous session data
const [retrySessionData, setRetrySessionData] = useState<{
sessionId: string; // ID of session to archive after new session is created
prompt: string;
sessionName: string;
toolType: 'claude' | 'codex' | 'none';
baseBranch?: string;
folderId?: string; // Folder to create the new session in
claudeConfig?: {
model?: 'auto' | 'sonnet' | 'opus' | 'haiku';
permissionMode?: 'approve' | 'ignore';
ultrathink?: boolean;
};
codexConfig?: {
model?: string;
modelProvider?: string;
sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
webSearch?: boolean;
thinkingLevel?: 'low' | 'medium' | 'high';
};
} | null>(null);
const [showProjectSettings, setShowProjectSettings] = useState(false);
const [selectedProjectForSettings, setSelectedProjectForSettings] = useState<Project | null>(null);
const [showAddProjectDialog, setShowAddProjectDialog] = useState(false);
@ -190,24 +211,30 @@ export function DraggableProjectTreeView({ sessionSortAscending }: DraggableProj
const session = projectsWithSessions
.flatMap(project => project.sessions)
.find(s => s.id === activeSessionId);
if (session) {
console.log('[DraggableProjectTreeView] Active session changed to:', session.id, 'ensuring paths are expanded');
// Ensure project is expanded
if (session.projectId && !expandedProjects.has(session.projectId)) {
console.log('[DraggableProjectTreeView] Expanding project for active session:', session.projectId);
setExpandedProjects(prev => new Set([...prev, session.projectId!]));
}
setExpandedProjects(prev => {
if (session.projectId && !prev.has(session.projectId)) {
console.log('[DraggableProjectTreeView] Expanding project for active session:', session.projectId);
return new Set([...prev, session.projectId]);
}
return prev;
});
// Ensure folder is expanded
if (session.folderId && !expandedFolders.has(session.folderId)) {
console.log('[DraggableProjectTreeView] Expanding folder for active session:', session.folderId);
setExpandedFolders(prev => new Set([...prev, session.folderId!]));
}
setExpandedFolders(prev => {
if (session.folderId && !prev.has(session.folderId)) {
console.log('[DraggableProjectTreeView] Expanding folder for active session:', session.folderId);
return new Set([...prev, session.folderId]);
}
return prev;
});
}
}
}, [activeSessionId, projectsWithSessions, expandedProjects, expandedFolders]);
}, [activeSessionId, projectsWithSessions]);
const handleFolderCreated = (folder: Folder) => {
// Add the folder to the appropriate project
@ -394,14 +421,14 @@ export function DraggableProjectTreeView({ sessionSortAscending }: DraggableProj
// Handler for folder updates
const handleFolderUpdated = (updatedFolder: Folder) => {
console.log('[DraggableProjectTreeView] Folder updated event received:', updatedFolder);
// Update the folder in the appropriate project
setProjectsWithSessions(prevProjects =>
setProjectsWithSessions(prevProjects =>
prevProjects.map(project => {
if (project.id === updatedFolder.projectId) {
return {
...project,
folders: project.folders.map(folder =>
folders: project.folders.map(folder =>
folder.id === updatedFolder.id ? updatedFolder : folder
)
};
@ -411,6 +438,32 @@ export function DraggableProjectTreeView({ sessionSortAscending }: DraggableProj
);
};
// Handler for folder deletion
const handleFolderDeleted = (folderId: string) => {
console.log('[DraggableProjectTreeView] Folder deleted event received:', folderId);
// Remove the folder from the appropriate project
setProjectsWithSessions(prevProjects =>
prevProjects.map(project => {
const folderExists = project.folders?.some(f => f.id === folderId);
if (folderExists) {
return {
...project,
folders: project.folders.filter(f => f.id !== folderId)
};
}
return project;
})
);
// Remove from expanded folders set
setExpandedFolders(prev => {
const newSet = new Set(prev);
newSet.delete(folderId);
return newSet;
});
};
// Listen for IPC events
if (window.electronAPI?.events) {
const unsubscribeCreated = window.electronAPI.events.onSessionCreated(handleSessionCreated);
@ -418,7 +471,8 @@ export function DraggableProjectTreeView({ sessionSortAscending }: DraggableProj
const unsubscribeDeleted = window.electronAPI.events.onSessionDeleted(handleSessionDeleted);
const unsubscribeFolderCreated = window.electronAPI.events.onFolderCreated(handleFolderCreated);
const unsubscribeFolderUpdated = window.electronAPI.events.onFolderUpdated(handleFolderUpdated);
const unsubscribeFolderDeleted = window.electronAPI.events.onFolderDeleted(handleFolderDeleted);
// Listen for project updates
const unsubscribeProjectUpdated = window.electronAPI.events.onProjectUpdated((updatedProject: Project) => {
// Update the project in our state
@ -449,8 +503,9 @@ export function DraggableProjectTreeView({ sessionSortAscending }: DraggableProj
unsubscribeDeleted();
unsubscribeFolderCreated();
unsubscribeFolderUpdated();
unsubscribeFolderDeleted();
unsubscribeProjectUpdated();
// Clean up pending auto-selection timeout
if (pendingAutoSelect) {
clearTimeout(pendingAutoSelect.timeoutId);
@ -544,6 +599,51 @@ export function DraggableProjectTreeView({ sessionSortAscending }: DraggableProj
};
}, [runningProjectId, projectsWithSessions]);
// Listen for "Discard and Retry" events from session context menu
useEffect(() => {
const handleDiscardAndRetry = (event: CustomEvent<{
session: Session;
projectId: number;
folderId?: string;
}>) => {
const { session, projectId, folderId } = event.detail;
// Find the project for this session
const project = projectsWithSessions.find(p => p.id === projectId);
if (!project) {
console.error('[DraggableProjectTreeView] Project not found for discard-and-retry:', projectId);
return;
}
// Store the retry data including session ID for archiving later
setRetrySessionData({
sessionId: session.id,
prompt: session.prompt || '',
sessionName: session.name || '',
toolType: session.toolType || 'claude',
baseBranch: session.baseBranch,
folderId: folderId || session.folderId,
claudeConfig: session.toolType === 'claude' ? {
permissionMode: session.permissionMode
} : undefined,
codexConfig: session.toolType === 'codex' ? {
// Codex configs would need to be retrieved from panel settings
// For now, we'll use defaults
} : undefined
});
// Open the create dialog with this project selected
setSelectedProjectForCreate(project);
setShowCreateDialog(true);
};
window.addEventListener('discard-and-retry', handleDiscardAndRetry as EventListener);
return () => {
window.removeEventListener('discard-and-retry', handleDiscardAndRetry as EventListener);
};
}, [projectsWithSessions]);
const loadProjectsWithSessions = async () => {
try {
setIsLoading(true);
@ -2369,9 +2469,26 @@ export function DraggableProjectTreeView({ sessionSortAscending }: DraggableProj
onClose={() => {
setShowCreateDialog(false);
setSelectedProjectForCreate(null);
setRetrySessionData(null);
}}
projectName={selectedProjectForCreate?.name}
projectId={selectedProjectForCreate?.id}
initialPrompt={retrySessionData?.prompt}
initialSessionName={retrySessionData?.sessionName}
initialToolType={retrySessionData?.toolType}
initialBaseBranch={retrySessionData?.baseBranch}
initialFolderId={retrySessionData?.folderId}
initialClaudeConfig={retrySessionData?.claudeConfig}
initialCodexConfig={retrySessionData?.codexConfig}
onSessionCreated={retrySessionData?.sessionId ? async () => {
// Archive the old session after new session is created ("Discard and Retry")
try {
await API.sessions.delete(retrySessionData.sessionId);
console.log('[DraggableProjectTreeView] Archived old session after retry:', retrySessionData.sessionId);
} catch (error) {
console.error('[DraggableProjectTreeView] Failed to archive old session:', error);
}
} : undefined}
/>
)}

View File

@ -421,7 +421,7 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
};
return (
<div className="relative">
<div className="relative h-full w-full">
{isTextarea ? (
<textarea
ref={textareaRef || internalTextareaRef}

View 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>
);
}

View 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>
);
};

View File

@ -5,12 +5,15 @@ 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 { 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;
@ -32,6 +35,7 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
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);
@ -320,19 +324,65 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
const handleToggleFavorite = async (e: React.MouseEvent) => {
e.stopPropagation();
try {
const response = await API.sessions.toggleFavorite(session.id);
if (!response.success) {
throw new Error(response.error || 'Failed to toggle favorite status');
}
} 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 (
<>
@ -399,20 +449,30 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
size="sm"
className={cn(
'transition-all',
session.isFavorite
? 'text-status-warning hover:text-status-warning-hover'
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"
<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}
@ -483,14 +543,31 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
disabled={isClosing}
className={cn(
'w-full text-left px-4 py-2 text-sm',
isClosing
? 'text-text-tertiary cursor-wait'
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-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-status-error hover:bg-surface-hover hover:text-status-error"
@ -515,6 +592,11 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
isOpen={showRunScriptConfig}
onClose={() => setShowRunScriptConfig(false)}
/>
<NimbalystInstallDialog
isOpen={showNimbalystInstall}
onClose={() => setShowNimbalystInstall(false)}
/>
</>
);
});

View File

@ -12,6 +12,7 @@ import { SessionHeader } from './session/SessionHeader';
// import { SessionInputWithImages } from './panels/claude/ClaudeInputWithImages'; // Removed - now in panels
import { GitErrorDialog } from './session/GitErrorDialog';
import { CommitMessageDialog } from './session/CommitMessageDialog';
import { FolderArchiveDialog } from './session/FolderArchiveDialog';
// import { FileEditor } from './panels/editor/FileEditor'; // Removed - now in panels
import { ProjectView } from './ProjectView';
import { API } from '../utils/api';
@ -200,12 +201,24 @@ export const SessionView = memo(() => {
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]
);
@ -563,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
@ -580,6 +595,14 @@ export const SessionView = memo(() => {
onFileSelect={hook.handleStravuFileSelect}
/>
<FolderArchiveDialog
isOpen={hook.showFolderArchiveDialog}
sessionCount={hook.folderSessionCount}
onArchiveSessionOnly={hook.handleArchiveSessionOnly}
onArchiveEntireFolder={hook.handleArchiveEntireFolder}
onCancel={hook.handleCancelFolderArchive}
/>
</div>
);
});

View File

@ -5,17 +5,18 @@ import { useNotifications } from '../hooks/useNotifications';
import { API } from '../utils/api';
import type { AppConfig } from '../types/config';
import { useConfigStore } from '../stores/configStore';
import {
Shield,
ShieldOff,
Sun,
Moon,
import {
Shield,
ShieldOff,
Sun,
Moon,
Settings as SettingsIcon,
Palette,
Zap,
RefreshCw,
FileText,
Eye
Eye,
BarChart3
} from 'lucide-react';
import { Input, Textarea, Checkbox } from './ui/Input';
import { Button } from './ui/Button';
@ -50,7 +51,9 @@ 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();
@ -88,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');
}
@ -105,17 +115,37 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
.map(p => p.trim())
.filter(p => p.length > 0);
const response = await API.config.update({
verbose,
anthropicApiKey,
systemPromptAppend: globalSystemPrompt,
// 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,
devMode,
enableCrystalFooter,
additionalPaths: parsedPaths,
notifications: notificationSettings
notifications: notificationSettings,
analytics: {
enabled: analyticsEnabled
}
});
if (!response.success) {
@ -127,10 +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');
@ -170,6 +200,16 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
>
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-3 text-sm font-medium transition-colors ${
@ -489,7 +529,90 @@ 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">
{/* Stravu Introduction */}
@ -563,7 +686,7 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
</ModalBody>
{/* Footer */}
{(activeTab === 'general' || activeTab === 'notifications') && (
{(activeTab === 'general' || activeTab === 'notifications' || activeTab === 'analytics') && (
<ModalFooter>
<Button
type="button"

View 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>
);
}

View File

@ -2,10 +2,11 @@ import React, { useCallback, memo, useState, useRef, useEffect } from 'react';
import { Plus, X, Terminal, ChevronDown, MessageSquare, GitBranch, FileText, FileCode, MoreVertical, BarChart3, Code2, Edit2 } from 'lucide-react';
import { cn } from '../../utils/cn';
import { PanelTabBarProps } from '../../types/panelComponents';
import { ToolPanel, ToolPanelType, PANEL_CAPABILITIES, LogsPanelState } from '../../../../shared/types/panels';
import { ToolPanel, ToolPanelType, PANEL_CAPABILITIES, LogsPanelState, BaseAIPanelState, PanelStatus } from '../../../../shared/types/panels';
import { Button } from '../ui/Button';
import { Dropdown } from '../ui/Dropdown';
import { useSession } from '../../contexts/SessionContext';
import { StatusDot } from '../ui/StatusDot';
export const PanelTabBar: React.FC<PanelTabBarProps> = memo(({
panels,
@ -159,6 +160,45 @@ export const PanelTabBar: React.FC<PanelTabBarProps> = memo(({
}
};
// Get panel status indicator config for AI panels (claude/codex)
const getPanelStatusConfig = (panel: ToolPanel): { status: 'running' | 'waiting' | 'info' | 'error' | 'default'; animated: boolean; pulse: boolean } | null => {
// Only show status for AI panels
if (panel.type !== 'claude' && panel.type !== 'codex') {
return null;
}
const customState = panel.state?.customState as BaseAIPanelState | undefined;
const panelStatus: PanelStatus | undefined = customState?.panelStatus;
const hasUnviewedContent = customState?.hasUnviewedContent ?? false;
const isActivePanel = activePanel?.id === panel.id;
// Don't show status indicator if panel is active and doesn't have unviewed content
// (user is actively viewing it)
if (isActivePanel && !hasUnviewedContent && panelStatus !== 'running' && panelStatus !== 'waiting') {
return null;
}
switch (panelStatus) {
case 'running':
return { status: 'running', animated: true, pulse: false };
case 'waiting':
return { status: 'waiting', animated: false, pulse: true };
case 'error':
return { status: 'error', animated: false, pulse: false };
case 'completed_unviewed':
// Show blue dot for completed with unviewed content
return { status: 'info', animated: false, pulse: true };
case 'stopped':
case 'idle':
default:
// Only show if there's unviewed content and panel is not active
if (hasUnviewedContent && !isActivePanel) {
return { status: 'info', animated: false, pulse: true };
}
return null;
}
};
return (
<div className="panel-tab-bar bg-surface-secondary border-b border-border-primary dark:border-border-hover">
{/* Flex container that wraps when needed */}
@ -173,7 +213,8 @@ export const PanelTabBar: React.FC<PanelTabBarProps> = memo(({
const isEditing = editingPanelId === panel.id;
const isDiffPanel = panel.type === 'diff';
const displayTitle = isDiffPanel ? 'Diff' : panel.title;
const statusConfig = getPanelStatusConfig(panel);
return (
<div
key={panel.id}
@ -197,6 +238,16 @@ export const PanelTabBar: React.FC<PanelTabBarProps> = memo(({
}
}}
>
{/* Status indicator for AI panels */}
{statusConfig && (
<StatusDot
status={statusConfig.status}
size="sm"
animated={statusConfig.animated}
pulse={statusConfig.pulse}
className="mr-1"
/>
)}
{getPanelIcon(panel.type)}
{isEditing ? (

View File

@ -76,9 +76,9 @@ const SetupTasksPanel: React.FC<SetupTasksPanelProps> = ({ panelId, isActive })
if (!projectId) return;
try {
// First, update the project's run script to "crystal-run.sh"
// First, update the project's run script to "./crystal-run.sh"
const updateResponse = await API.projects.update(projectId, {
run_script: 'crystal-run.sh'
run_script: './crystal-run.sh'
});
if (!updateResponse.success) {
@ -87,7 +87,7 @@ const SetupTasksPanel: React.FC<SetupTasksPanelProps> = ({ panelId, isActive })
return;
}
console.log('[SetupTasksPanel] Successfully set run script to crystal-run.sh');
console.log('[SetupTasksPanel] Successfully set run script to ./crystal-run.sh');
// Now open the session dialog with the specific prompt
setShowSessionDialog(true);

View File

@ -83,7 +83,6 @@ export const SessionInputWithImages: React.FC<SessionInputWithImagesProps> = mem
const [isFocused, setIsFocused] = useState(false);
const [isToolbarActive, setIsToolbarActive] = useState(false);
const [selectedModel, setSelectedModel] = useState<string>('auto');
const [textareaHeight, setTextareaHeight] = useState<number>(52);
const [isSubmitting, setIsSubmitting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
@ -328,24 +327,6 @@ export const SessionInputWithImages: React.FC<SessionInputWithImagesProps> = mem
const resolvedContextDisplay = contextUsageDisplay ?? '-- tokens (--%)';
// Auto-resize textarea with requestAnimationFrame for better performance
useEffect(() => {
if (!textareaRef.current) return;
// Use requestAnimationFrame to batch DOM reads/writes
const rafId = requestAnimationFrame(() => {
if (textareaRef.current) {
// Reset height to auto to allow proper shrinking
textareaRef.current.style.height = 'auto';
const scrollHeight = textareaRef.current.scrollHeight;
const newHeight = Math.min(Math.max(scrollHeight, 52), 200);
setTextareaHeight(newHeight);
}
});
return () => cancelAnimationFrame(rafId);
}, [input, textareaRef]);
const handleFocus = useCallback(() => {
setIsFocused(true);
setIsToolbarActive(true);
@ -355,10 +336,10 @@ export const SessionInputWithImages: React.FC<SessionInputWithImagesProps> = mem
return (
<div className="border-t-2 border-border-primary flex-shrink-0 shadow-[0_-4px_20px_rgba(0,0,0,0.1)]">
<div className="bg-surface-secondary">
<div className="h-full flex flex-col shadow-[0_-4px_20px_rgba(0,0,0,0.1)]">
<div className="bg-surface-secondary flex flex-col flex-1 min-h-0">
{/* Context Bar */}
<div className="px-4 py-2 border-b border-border-primary bg-surface-primary">
<div className="px-4 py-2 border-b border-border-primary bg-surface-primary flex-shrink-0">
<div className="flex items-center justify-between text-xs">
<div className="flex items-center gap-3">
{/* Session status indicator */}
@ -426,8 +407,8 @@ export const SessionInputWithImages: React.FC<SessionInputWithImagesProps> = mem
</div>
{/* Command Input Area */}
<div
className="p-4 bg-surface-primary"
<div
className="p-4 bg-surface-primary flex-1 flex flex-col min-h-0"
data-toolbar-container
onDrop={handleDrop}
onDragOver={handleDragOver}
@ -441,7 +422,7 @@ export const SessionInputWithImages: React.FC<SessionInputWithImagesProps> = mem
setTimeout(() => {
const activeElement = document.activeElement;
const toolbar = e.currentTarget as HTMLElement;
if (!activeElement || !toolbar || !toolbar.contains(activeElement)) {
setIsToolbarActive(false);
}
@ -490,16 +471,16 @@ export const SessionInputWithImages: React.FC<SessionInputWithImagesProps> = mem
{/* Clean Input Container */}
<div className={`
relative z-10
bg-surface-primary
rounded-lg border border-border-primary
relative z-10 flex-1 flex flex-col min-h-0
bg-surface-primary
rounded-lg border border-border-primary
shadow-[0_4px_20px_rgba(0,0,0,0.1)] hover:shadow-[0_8px_30px_rgba(0,0,0,0.15)]
transition-all duration-200 backdrop-blur-sm
${(isFocused || isToolbarActive) ? (buttonConfig.color === 'green' ? 'command-bar-focus-green' : 'command-bar-focus') : ''}
`}>
{/* Command prompt field */}
<div className="relative">
<div className="absolute left-4 top-[50%] -translate-y-[50%] text-text-secondary select-none pointer-events-none font-mono text-sm">
<div className="relative flex-1 min-h-0 flex">
<div className="absolute left-4 top-4 text-text-secondary select-none pointer-events-none font-mono text-sm z-10">
&gt;
</div>
<FilePathAutocomplete
@ -508,7 +489,7 @@ export const SessionInputWithImages: React.FC<SessionInputWithImagesProps> = mem
sessionId={activeSession.id}
placeholder={isDragging ? "Drop images here..." : placeholder}
className={`
w-full pl-10 pr-4 py-4
w-full h-full pl-10 pr-4 py-4
bg-transparent
border-0 focus:outline-none
resize-none font-mono text-sm
@ -528,12 +509,8 @@ export const SessionInputWithImages: React.FC<SessionInputWithImagesProps> = mem
setIsToolbarActive(false);
onBlur?.();
}}
style={{
height: `${textareaHeight}px`,
minHeight: '52px',
maxHeight: '200px',
overflowY: textareaHeight >= 200 ? 'auto' : 'hidden',
transition: 'height 0.1s ease-out'
style={{
minHeight: '52px'
}}
/>
{/* Hidden file input */}
@ -558,7 +535,7 @@ export const SessionInputWithImages: React.FC<SessionInputWithImagesProps> = mem
</div>
{/* Unified Action Bar */}
<div className="flex items-center justify-between mt-3 gap-4">
<div className="flex items-center justify-between mt-3 gap-4 flex-shrink-0">
{/* Left Section - Tools and Settings */}
<div className="flex items-center gap-2">
{/* Attach Button */}

View File

@ -10,6 +10,7 @@ import { ClaudeMessageTransformer } from '../ai/transformers/ClaudeMessageTransf
import { Settings } from 'lucide-react';
import { useConfigStore } from '../../../stores/configStore';
import type { ClaudePanelState } from '../../../../../shared/types/panels';
import { ResizablePanel } from '../../ResizablePanel';
export const ClaudePanel: React.FC<AIPanelProps> = React.memo(({ panel, isActive }) => {
const hook = useClaudePanel(panel.id, isActive);
@ -187,28 +188,35 @@ export const ClaudePanel: React.FC<AIPanelProps> = React.memo(({ panel, isActive
{/* Claude Input - Always visible at bottom if not archived */}
{!activeSession.archived && (
<ClaudeInputWithImages
activeSession={activeSession}
viewMode="richOutput"
input={hook.input}
setInput={hook.setInput}
textareaRef={hook.textareaRef}
handleTerminalCommand={hook.handleTerminalCommand}
handleSendInput={hook.handleSendInput}
handleContinueConversation={hook.handleContinueConversation}
isStravuConnected={hook.isStravuConnected}
setShowStravuSearch={hook.setShowStravuSearch}
ultrathink={hook.ultrathink}
setUltrathink={hook.setUltrathink}
gitCommands={hook.gitCommands}
handleCompactContext={hook.handleCompactContext}
hasConversationHistory={hook.hasConversationHistory}
contextCompacted={hook.contextCompacted}
handleCancelRequest={hook.handleStopSession}
contextUsageDisplay={contextDisplay}
contextUpdating={isContextUpdating}
panelId={panel.id}
/>
<ResizablePanel
defaultHeight={200}
minHeight={140}
maxHeight={600}
storageKey="claude-input-panel-height"
>
<ClaudeInputWithImages
activeSession={activeSession}
viewMode="richOutput"
input={hook.input}
setInput={hook.setInput}
textareaRef={hook.textareaRef}
handleTerminalCommand={hook.handleTerminalCommand}
handleSendInput={hook.handleSendInput}
handleContinueConversation={hook.handleContinueConversation}
isStravuConnected={hook.isStravuConnected}
setShowStravuSearch={hook.setShowStravuSearch}
ultrathink={hook.ultrathink}
setUltrathink={hook.setUltrathink}
gitCommands={hook.gitCommands}
handleCompactContext={hook.handleCompactContext}
hasConversationHistory={hook.hasConversationHistory}
contextCompacted={hook.contextCompacted}
handleCancelRequest={hook.handleStopSession}
contextUsageDisplay={contextDisplay}
contextUpdating={isContextUpdating}
panelId={panel.id}
/>
</ResizablePanel>
)}
{/* Show archived message if session is archived */}

View File

@ -41,7 +41,6 @@ export const CodexInputPanelStyled: React.FC<CodexInputPanelStyledProps> = memo(
const [settingsLoaded, setSettingsLoaded] = useState(false);
const [isFocused, setIsFocused] = useState(false);
const [isToolbarActive, setIsToolbarActive] = useState(false);
const [textareaHeight, setTextareaHeight] = useState<number>(52);
// Use the shared hook for common functionality
const {
@ -171,16 +170,6 @@ export const CodexInputPanelStyled: React.FC<CodexInputPanelStyledProps> = memo(
}
}, [panel?.state?.customState]);
// Auto-resize textarea
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
const scrollHeight = textareaRef.current.scrollHeight;
const newHeight = Math.min(Math.max(scrollHeight, 52), 200);
setTextareaHeight(newHeight);
}
}, [input, textareaRef]);
const handleSubmit = async () => {
// Use the hook's handleSubmit which includes attachments
await hookHandleSubmit({
@ -254,10 +243,10 @@ export const CodexInputPanelStyled: React.FC<CodexInputPanelStyledProps> = memo(
const isAutoCommitEnabled = effectiveMode !== 'disabled';
return (
<div className="border-t-2 border-border-primary flex-shrink-0 shadow-[0_-4px_20px_rgba(0,0,0,0.1)]">
<div className="bg-surface-secondary">
<div className="h-full flex flex-col shadow-[0_-4px_20px_rgba(0,0,0,0.1)]">
<div className="bg-surface-secondary flex flex-col flex-1 min-h-0">
{/* Context Bar */}
<div className="px-4 py-2 border-b border-border-primary bg-surface-primary">
<div className="px-4 py-2 border-b border-border-primary bg-surface-primary flex-shrink-0">
<div className="flex items-center justify-between text-xs">
<div className="flex items-center gap-3">
{/* Session status indicator */}
@ -305,8 +294,8 @@ export const CodexInputPanelStyled: React.FC<CodexInputPanelStyledProps> = memo(
</div>
{/* Command Input Area */}
<div
className="p-4 bg-surface-primary"
<div
className="p-4 bg-surface-primary flex-1 flex flex-col min-h-0"
data-toolbar-container
onDrop={handleDrop}
onDragOver={handleDragOver}
@ -352,16 +341,16 @@ export const CodexInputPanelStyled: React.FC<CodexInputPanelStyledProps> = memo(
{/* Clean Input Container */}
<div className={`
relative z-10
bg-surface-primary
rounded-lg border border-border-primary
relative z-10 flex-1 flex flex-col min-h-0
bg-surface-primary
rounded-lg border border-border-primary
shadow-[0_4px_20px_rgba(0,0,0,0.1)] hover:shadow-[0_8px_30px_rgba(0,0,0,0.15)]
transition-all duration-200 backdrop-blur-sm
${(isFocused || isToolbarActive) ? 'command-bar-focus' : ''}
`}>
{/* Command prompt field */}
<div className="relative">
<div className="absolute left-4 top-[50%] -translate-y-[50%] text-text-secondary select-none pointer-events-none font-mono text-sm">
<div className="relative flex-1 min-h-0 flex">
<div className="absolute left-4 top-4 text-text-secondary select-none pointer-events-none font-mono text-sm z-10">
&gt;
</div>
<FilePathAutocomplete
@ -370,7 +359,7 @@ export const CodexInputPanelStyled: React.FC<CodexInputPanelStyledProps> = memo(
sessionId={session.id}
placeholder={isDragging ? "Drop images here..." : placeholder}
className={`
w-full pl-10 pr-4 py-4
w-full h-full pl-10 pr-4 py-4
bg-transparent
border-0 focus:outline-none
resize-none font-mono text-sm
@ -385,12 +374,8 @@ export const CodexInputPanelStyled: React.FC<CodexInputPanelStyledProps> = memo(
onPaste={handlePaste}
onFocus={handleFocus}
onBlur={() => handleBlur({} as React.FocusEvent)}
style={{
height: `${textareaHeight}px`,
minHeight: '52px',
maxHeight: '200px',
overflowY: textareaHeight >= 200 ? 'auto' : 'hidden',
transition: 'height 0.1s ease-out'
style={{
minHeight: '52px'
}}
/>
{/* Hidden file input */}
@ -406,7 +391,7 @@ export const CodexInputPanelStyled: React.FC<CodexInputPanelStyledProps> = memo(
</div>
{/* Unified Action Bar */}
<div className="flex items-center justify-between mt-3 gap-4">
<div className="flex items-center justify-between mt-3 gap-4 flex-shrink-0">
{/* Left Section - Tools and Settings */}
<div className="flex items-center gap-2">
{/* Attach Button */}

View File

@ -10,6 +10,7 @@ import { CodexInputPanelStyled } from './CodexInputPanelStyled';
import { useCodexPanel } from '../../../hooks/useCodexPanel';
import { DEFAULT_CODEX_MODEL, type CodexInputOptions } from '../../../../../shared/types/models';
import { useConfigStore } from '../../../stores/configStore';
import { ResizablePanel } from '../../ResizablePanel';
interface CodexPanelProps {
panel: ToolPanel;
@ -180,15 +181,22 @@ export const CodexPanel: React.FC<CodexPanelProps> = React.memo(({ panel, isActi
{/* Codex Input - Always visible at bottom */}
{!activeSession.archived && (
<CodexInputPanelStyled
session={activeSession}
panelId={panel.id}
panel={panel}
onSendMessage={hook.handleSendMessage as (message: string, options?: CodexInputOptions) => Promise<void>}
disabled={hook.isProcessing}
initialModel={model}
onCancel={hook.handleInterrupt}
/>
<ResizablePanel
defaultHeight={200}
minHeight={140}
maxHeight={600}
storageKey="codex-input-panel-height"
>
<CodexInputPanelStyled
session={activeSession}
panelId={panel.id}
panel={panel}
onSendMessage={hook.handleSendMessage as (message: string, options?: CodexInputOptions) => Promise<void>}
disabled={hook.isProcessing}
initialModel={model}
onCancel={hook.handleInterrupt}
/>
</ResizablePanel>
)}
</div>
);

View File

@ -10,8 +10,13 @@ import { Maximize2, Minimize2, RefreshCw } from 'lucide-react';
const HISTORY_LIMIT = 50;
const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
sessionId,
const SIDEBAR_STORAGE_KEY = 'diff-panel-sidebar-width';
const DEFAULT_SIDEBAR_WIDTH = 300;
const MIN_SIDEBAR_WIDTH = 150;
const MAX_SIDEBAR_WIDTH = 600;
const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
sessionId,
selectedExecutions: initialSelected,
isGitOperationRunning = false,
isMainRepo = false,
@ -31,9 +36,64 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
const [lastVisibleState, setLastVisibleState] = useState<boolean>(isVisible);
const [forceRefresh, setForceRefresh] = useState<number>(0);
const [selectedFile, setSelectedFile] = useState<string | undefined>();
// Resizable sidebar state
const [sidebarWidth, setSidebarWidth] = useState<number>(() => {
const stored = localStorage.getItem(SIDEBAR_STORAGE_KEY);
if (stored) {
const width = parseInt(stored, 10);
if (!isNaN(width) && width >= MIN_SIDEBAR_WIDTH && width <= MAX_SIDEBAR_WIDTH) {
return width;
}
}
return DEFAULT_SIDEBAR_WIDTH;
});
const [isResizing, setIsResizing] = useState(false);
const diffViewerRef = useRef<DiffViewerHandle>(null);
// Save sidebar width to localStorage
useEffect(() => {
localStorage.setItem(SIDEBAR_STORAGE_KEY, sidebarWidth.toString());
}, [sidebarWidth]);
// Handle resize mouse events
useEffect(() => {
if (!isResizing) return;
const handleMouseMove = (e: MouseEvent) => {
const container = document.querySelector('.combined-diff-view');
if (!container) return;
const containerRect = container.getBoundingClientRect();
const newWidth = e.clientX - containerRect.left;
const constrainedWidth = Math.max(MIN_SIDEBAR_WIDTH, Math.min(MAX_SIDEBAR_WIDTH, newWidth));
setSidebarWidth(constrainedWidth);
};
const handleMouseUp = () => {
setIsResizing(false);
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
// Change cursor globally while resizing
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
document.body.style.cursor = '';
document.body.style.userSelect = '';
};
}, [isResizing]);
const handleResizeStart = useCallback((e: React.MouseEvent) => {
e.preventDefault();
setIsResizing(true);
}, []);
// Load git commands to get main branch
useEffect(() => {
const loadGitCommands = async () => {
@ -552,34 +612,48 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
<div className="flex-1 flex min-h-0">
{/* Commits selection sidebar */}
{!isFullscreen && (
<div className="w-1/3 border-r border-border-primary bg-surface-secondary overflow-hidden flex flex-col">
{/* File list - show only when we have a diff */}
{filesFromDiff.length > 0 && (
<div className="h-1/3 border-b border-border-primary overflow-y-auto">
<FileList
files={filesFromDiff}
onFileClick={handleFileClick}
onFileDelete={handleFileDelete}
selectedFile={selectedFile}
<>
<div
className="border-r border-border-primary bg-surface-secondary overflow-hidden flex flex-col flex-shrink-0"
style={{ width: sidebarWidth }}
>
{/* File list - show only when we have a diff */}
{filesFromDiff.length > 0 && (
<div className="h-1/3 border-b border-border-primary overflow-y-auto">
<FileList
files={filesFromDiff}
onFileClick={handleFileClick}
onFileDelete={handleFileDelete}
selectedFile={selectedFile}
/>
</div>
)}
{/* Execution list */}
<div className={filesFromDiff.length > 0 ? "flex-1 overflow-hidden" : "h-full"}>
<ExecutionList
sessionId={sessionId}
executions={executions}
selectedExecutions={selectedExecutions}
onSelectionChange={handleSelectionChange}
onCommit={() => setShowCommitDialog(true)}
onRevert={handleRevert}
onRestore={handleRestore}
historyLimitReached={limitReached}
historyLimit={HISTORY_LIMIT}
/>
</div>
)}
{/* Execution list */}
<div className={filesFromDiff.length > 0 ? "flex-1 overflow-hidden" : "h-full"}>
<ExecutionList
sessionId={sessionId}
executions={executions}
selectedExecutions={selectedExecutions}
onSelectionChange={handleSelectionChange}
onCommit={() => setShowCommitDialog(true)}
onRevert={handleRevert}
onRestore={handleRestore}
historyLimitReached={limitReached}
historyLimit={HISTORY_LIMIT}
/>
</div>
</div>
{/* Resize handle */}
<div
className={`w-1 hover:bg-interactive cursor-col-resize flex-shrink-0 transition-colors ${
isResizing ? 'bg-interactive' : 'bg-transparent'
}`}
onMouseDown={handleResizeStart}
title="Drag to resize sidebar"
/>
</>
)}
{/* Diff preview */}

View File

@ -15,7 +15,9 @@ interface CommitMessageDialogProps {
shouldSquash: boolean;
setShouldSquash: (should: boolean) => void;
onConfirm: (message: string) => void;
onMergeAndArchive?: (message: string) => void;
isMerging: boolean;
isMergingAndArchiving?: boolean;
}
export const CommitMessageDialog: React.FC<CommitMessageDialogProps> = ({
@ -28,8 +30,11 @@ export const CommitMessageDialog: React.FC<CommitMessageDialogProps> = ({
shouldSquash,
setShouldSquash,
onConfirm,
onMergeAndArchive,
isMerging,
isMergingAndArchiving,
}) => {
const isProcessing = isMerging || isMergingAndArchiving;
return (
<Modal isOpen={isOpen} onClose={onClose} size="xl">
<ModalHeader>
@ -100,15 +105,25 @@ export const CommitMessageDialog: React.FC<CommitMessageDialogProps> = ({
</ModalBody>
<ModalFooter className="flex justify-end gap-3">
<Button onClick={onClose} variant="ghost">
<Button onClick={onClose} variant="ghost" disabled={isProcessing}>
Cancel
</Button>
{dialogType === 'squash' && onMergeAndArchive && (
<Button
onClick={() => onMergeAndArchive(commitMessage)}
disabled={(shouldSquash && !commitMessage.trim()) || isProcessing}
loading={isMergingAndArchiving}
variant="secondary"
>
{isMergingAndArchiving ? 'Merging...' : 'Merge & Archive'}
</Button>
)}
<Button
onClick={() => onConfirm(commitMessage)}
disabled={(shouldSquash && !commitMessage.trim()) || isMerging}
disabled={(shouldSquash && !commitMessage.trim()) || isProcessing}
loading={isMerging}
>
{isMerging ? 'Merging...' : (dialogType === 'squash' ? (shouldSquash ? 'Merge' : 'Merge') : 'Rebase')}
{isMerging ? 'Merging...' : (dialogType === 'squash' ? 'Merge' : 'Rebase')}
</Button>
</ModalFooter>
</Modal>

View File

@ -0,0 +1,50 @@
import React from 'react';
import { Modal, ModalHeader, ModalBody, ModalFooter } from '../ui/Modal';
import { Button } from '../ui/Button';
import { FolderArchive } from 'lucide-react';
interface FolderArchiveDialogProps {
isOpen: boolean;
sessionCount: number;
onArchiveSessionOnly: () => void;
onArchiveEntireFolder: () => void;
onCancel: () => void;
}
export const FolderArchiveDialog: React.FC<FolderArchiveDialogProps> = ({
isOpen,
sessionCount,
onArchiveSessionOnly,
onArchiveEntireFolder,
onCancel,
}) => {
return (
<Modal isOpen={isOpen} onClose={onCancel} size="md">
<ModalHeader>
<div className="flex items-center gap-2">
<FolderArchive className="w-5 h-5 text-text-secondary" />
Archive Folder?
</div>
</ModalHeader>
<ModalBody>
<p className="text-text-secondary">
This session is in a folder with {sessionCount} session{sessionCount !== 1 ? 's' : ''}.
Would you like to archive all sessions in the folder?
</p>
</ModalBody>
<ModalFooter className="flex justify-end gap-3">
<Button onClick={onCancel} variant="ghost">
Cancel
</Button>
<Button onClick={onArchiveSessionOnly} variant="secondary">
This Session Only
</Button>
<Button onClick={onArchiveEntireFolder}>
Archive Entire Folder
</Button>
</ModalFooter>
</Modal>
);
};

View File

@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { useSessionStore } from '../stores/sessionStore';
import { API } from '../utils/api';
import { AnalyticsService } from '../services/analyticsService';
// Extend window interface for webkit audio context compatibility
declare global {
@ -30,6 +31,11 @@ export function useNotifications() {
const settingsLoaded = useRef(false);
const initialLoadComplete = useRef(false);
// Track shown notifications to prevent duplicate analytics tracking
// Key format: `${sessionId}:${status}` for status notifications, or `${sessionId}:created` for new sessions
// This ensures we only track each unique notification once, even if the component re-renders
const trackedNotificationsRef = useRef<Set<string>>(new Set());
const requestPermission = async (): Promise<boolean> => {
if (!('Notification' in window)) {
console.warn('This browser does not support notifications');
@ -78,7 +84,7 @@ export function useNotifications() {
}
};
const showNotification = (title: string, body: string, icon?: string) => {
const showNotification = (title: string, body: string, icon?: string, triggerEvent?: string, trackingKey?: string) => {
if (!settings.enabled) return;
requestPermission().then((hasPermission) => {
@ -90,8 +96,29 @@ export function useNotifications() {
tag: 'claude-code-commander',
requireInteraction: false,
});
playNotificationSound();
// Track notification shown analytics - only if this is a unique notification
// trackingKey is used to deduplicate notifications (e.g., "sessionId:status")
// If no trackingKey is provided, we track every notification (backwards compatibility)
if (!trackingKey || !trackedNotificationsRef.current.has(trackingKey)) {
// Mark this notification as tracked
if (trackingKey) {
trackedNotificationsRef.current.add(trackingKey);
}
const notificationType = title.includes('Error') || title.includes('error') ? 'error' :
title.includes('Complete') || title.includes('complete') ? 'success' :
title.includes('Required') || title.includes('waiting') ? 'info' : 'other';
AnalyticsService.trackNotificationShown({
notification_type: notificationType,
trigger_event: triggerEvent || 'unknown',
}).catch((error) => {
console.error('[Notifications] Failed to track notification:', error);
});
}
}
});
};
@ -141,11 +168,14 @@ export function useNotifications() {
const prevSession = prevSessions.find(s => s.id === currentSession.id);
if (!prevSession) {
// New session created
// New session created - use tracking key to prevent duplicate tracking
if (settings.notifyOnStatusChange) {
showNotification(
`New Session Created ${getStatusEmoji('initializing')}`,
`"${currentSession.name}" is starting up`
`"${currentSession.name}" is starting up`,
undefined,
'session_created',
`${currentSession.id}:created` // Tracking key ensures we only track this once
);
}
return;
@ -155,27 +185,45 @@ export function useNotifications() {
if (prevSession.status !== currentSession.status) {
const emoji = getStatusEmoji(currentSession.status);
const message = getStatusMessage(currentSession.status);
// Use tracking key format: `sessionId:status` to deduplicate per-status notifications
// This ensures that if a session transitions from waiting->running->waiting,
// we track both 'waiting' notifications, but if the component re-renders while
// in 'waiting' state, we don't track it multiple times
const trackingKey = `${currentSession.id}:${currentSession.status}`;
// Notify based on specific status
if (currentSession.status === 'waiting' && settings.notifyOnWaiting) {
showNotification(
`Input Required ${emoji}`,
`"${currentSession.name}" is waiting for your response`
`"${currentSession.name}" is waiting for your response`,
undefined,
'status_waiting',
trackingKey
);
} else if (currentSession.status === 'completed_unviewed' && settings.notifyOnComplete) {
showNotification(
`Session Complete ✅`,
`"${currentSession.name}" has finished`
`"${currentSession.name}" has finished`,
undefined,
'status_completed',
trackingKey
);
} else if (currentSession.status === 'error') {
showNotification(
`Session Error ${emoji}`,
`"${currentSession.name}" encountered an error`
`"${currentSession.name}" encountered an error`,
undefined,
'status_error',
trackingKey
);
} else if (settings.notifyOnStatusChange) {
showNotification(
`Status Update ${emoji}`,
`"${currentSession.name}" ${message}`
`"${currentSession.name}" ${message}`,
undefined,
`status_${currentSession.status}`,
trackingKey
);
}
}

View File

@ -45,6 +45,7 @@ export const useSessionView = (
const [ultrathink, setUltrathink] = useState(false);
const [isLoadingOutput, setIsLoadingOutput] = useState(false);
const [isMerging, setIsMerging] = useState(false);
const [isMergingAndArchiving, setIsMergingAndArchiving] = useState(false);
const [mergeError, setMergeError] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [outputLoadState, setOutputLoadState] = useState<'idle' | 'loading' | 'loaded' | 'error'>('idle');
@ -64,7 +65,13 @@ export const useSessionView = (
const [contextCompacted, setContextCompacted] = useState(false);
const [compactedContext, setCompactedContext] = useState<string | null>(null);
const [hasConversationHistory, setHasConversationHistory] = useState(false);
// Folder archive dialog state
const [showFolderArchiveDialog, setShowFolderArchiveDialog] = useState(false);
const [folderArchiveSessionId, setFolderArchiveSessionId] = useState<string | null>(null);
const [folderArchiveFolderId, setFolderArchiveFolderId] = useState<string | null>(null);
const [folderSessionCount, setFolderSessionCount] = useState(0);
const [, forceUpdate] = useState({});
const [shouldReloadOutput, setShouldReloadOutput] = useState(false);
@ -1465,6 +1472,135 @@ export const useSessionView = (
}
};
const performSquashWithCommitMessageAndArchive = async (message: string) => {
if (!activeSession) return;
setIsMergingAndArchiving(true);
setMergeError(null);
setShowCommitMessageDialog(false);
try {
const response: GitErrorResponse = shouldSquash
? await API.sessions.squashAndRebaseToMain(activeSession.id, message)
: await API.sessions.rebaseToMain(activeSession.id);
if (!response.success) {
if (response.gitError) {
const gitError = response.gitError;
setGitErrorDetails({
title: 'Merge Failed',
message: response.error || `Failed to merge to main`,
commands: gitError.commands,
output: gitError.output || 'No output available',
workingDirectory: gitError.workingDirectory,
projectPath: gitError.projectPath,
});
setShowGitErrorDialog(true);
} else {
setMergeError(response.error || `Failed to merge to main`);
}
return;
}
// Merge succeeded - check if session is in a folder with other sessions
const sessionId = activeSession.id;
const folderId = activeSession.folderId;
if (folderId) {
// Check how many sessions are in this folder
const allSessions = useSessionStore.getState().sessions;
const sessionsInFolder = allSessions.filter(s => s.folderId === folderId && !s.archived);
if (sessionsInFolder.length > 1) {
// There are other sessions in the folder - show dialog
setFolderArchiveSessionId(sessionId);
setFolderArchiveFolderId(folderId);
setFolderSessionCount(sessionsInFolder.length);
setShowFolderArchiveDialog(true);
return; // Don't archive yet - wait for user decision
}
}
// No folder or only one session in folder - archive just this session
await archiveSingleSession(sessionId);
} catch (error) {
console.error(`[performSquashWithCommitMessageAndArchive] Error in try block`, error);
setMergeError(error instanceof Error ? error.message : `Failed to merge to main`);
} finally {
setIsMergingAndArchiving(false);
}
};
const archiveSingleSession = async (sessionId: string) => {
useSessionStore.getState().addDeletingSessionId(sessionId);
try {
const archiveResponse = await API.sessions.delete(sessionId);
if (!archiveResponse.success) {
console.error('[archiveSingleSession] Archive failed:', archiveResponse.error);
setMergeError(`Merge succeeded but archive failed: ${archiveResponse.error}`);
}
await useSessionStore.getState().setActiveSession(null);
} catch (archiveError) {
console.error('[archiveSingleSession] Archive error:', archiveError);
setMergeError(`Merge succeeded but archive failed: ${archiveError instanceof Error ? archiveError.message : 'Unknown error'}`);
}
};
const handleArchiveSessionOnly = async () => {
setShowFolderArchiveDialog(false);
if (folderArchiveSessionId) {
await archiveSingleSession(folderArchiveSessionId);
}
setFolderArchiveSessionId(null);
setFolderArchiveFolderId(null);
setFolderSessionCount(0);
setIsMergingAndArchiving(false);
};
const handleArchiveEntireFolder = async () => {
setShowFolderArchiveDialog(false);
if (folderArchiveFolderId) {
const allSessions = useSessionStore.getState().sessions;
const sessionsInFolder = allSessions.filter(s => s.folderId === folderArchiveFolderId && !s.archived);
// Add all sessions to deleting state
for (const session of sessionsInFolder) {
useSessionStore.getState().addDeletingSessionId(session.id);
}
// Archive all sessions in the folder
for (const session of sessionsInFolder) {
try {
const archiveResponse = await API.sessions.delete(session.id);
if (!archiveResponse.success) {
console.error(`[handleArchiveEntireFolder] Archive failed for session ${session.id}:`, archiveResponse.error);
}
} catch (archiveError) {
console.error(`[handleArchiveEntireFolder] Archive error for session ${session.id}:`, archiveError);
}
}
// Delete the folder after archiving all sessions
try {
await API.folders.delete(folderArchiveFolderId);
} catch (folderError) {
console.error('[handleArchiveEntireFolder] Folder delete error:', folderError);
}
await useSessionStore.getState().setActiveSession(null);
}
setFolderArchiveSessionId(null);
setFolderArchiveFolderId(null);
setFolderSessionCount(0);
setIsMergingAndArchiving(false);
};
const handleCancelFolderArchive = () => {
setShowFolderArchiveDialog(false);
setFolderArchiveSessionId(null);
setFolderArchiveFolderId(null);
setFolderSessionCount(0);
setIsMergingAndArchiving(false);
};
const handleOpenIDE = async () => {
if (!activeSession) return;
@ -1661,6 +1797,7 @@ export const useSessionView = (
isLoadingOutput,
outputLoadState,
isMerging,
isMergingAndArchiving,
mergeError,
loadError,
gitCommands,
@ -1692,6 +1829,7 @@ export const useSessionView = (
handleAbortRebaseAndUseClaude,
handleSquashAndRebaseToMain,
performSquashWithCommitMessage,
performSquashWithCommitMessageAndArchive,
handleOpenIDE,
isOpeningIDE,
handleStravuFileSelect,
@ -1711,5 +1849,11 @@ export const useSessionView = (
contextCompacted,
hasConversationHistory,
compactedContext,
// Folder archive dialog
showFolderArchiveDialog,
folderSessionCount,
handleArchiveSessionOnly,
handleArchiveEntireFolder,
handleCancelFolderArchive,
};
};

View File

@ -0,0 +1,333 @@
/**
* Frontend Analytics Service
*
* Helper utilities for tracking UI interaction events from the frontend.
* All tracking is routed through the backend's AnalyticsManager to ensure
* consistent privacy protections and event formatting.
*/
/**
* UI Interaction Event types
*/
export type UIEventName =
| 'view_switched'
| 'help_dialog_opened'
| 'settings_opened'
| 'settings_saved'
| 'sidebar_toggled'
| 'search_used'
| 'notification_shown'
| 'nimbalyst_button_clicked'
| 'nimbalyst_install_dialog_shown'
| 'nimbalyst_download_clicked'
| 'nimbalyst_opened';
/**
* Event property interfaces for type safety
*/
export interface ViewSwitchedProperties extends Record<string, string | number | boolean | string[] | undefined> {
from_view: string;
to_view: string;
session_id_hash?: string;
}
export interface HelpDialogOpenedProperties extends Record<string, string | number | boolean | string[] | undefined> {
from_location: string;
}
export interface SettingsOpenedProperties extends Record<string, string | number | boolean | string[] | undefined> {
from_location: string;
}
export interface SettingsSavedProperties extends Record<string, string | number | boolean | string[] | undefined> {
category: string;
setting_keys: string[];
}
export interface SidebarToggledProperties extends Record<string, string | number | boolean | string[] | undefined> {
is_visible: boolean;
}
export interface SearchUsedProperties extends Record<string, string | number | boolean | string[] | undefined> {
search_type: string;
result_count_category: string;
}
export interface NotificationShownProperties extends Record<string, string | number | boolean | string[] | undefined> {
notification_type: string;
trigger_event: string;
}
export interface NimbalystButtonClickedProperties extends Record<string, string | number | boolean | string[] | undefined> {
session_id_hash?: string;
}
export interface NimbalystInstallDialogShownProperties extends Record<string, string | number | boolean | string[] | undefined> {
session_id_hash?: string;
}
// Event type for Nimbalyst download clicked (no additional properties needed)
export type NimbalystDownloadClickedProperties = Record<string, string | number | boolean | string[] | undefined>;
export interface NimbalystOpenedProperties extends Record<string, string | number | boolean | string[] | undefined> {
session_id_hash?: string;
}
/**
* Analytics Service
*
* Provides type-safe methods for tracking UI events
*/
export class AnalyticsService {
private static isEnabled(): boolean {
// Check if analytics is available (electronAPI is exposed via preload script)
return typeof window !== 'undefined' && 'electronAPI' in window &&
window.electronAPI && 'analytics' in window.electronAPI;
}
/**
* Track a view switch event
*/
static async trackViewSwitched(properties: ViewSwitchedProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'view_switched',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track view_switched:', error);
}
}
/**
* Track help dialog opened event
*/
static async trackHelpDialogOpened(properties: HelpDialogOpenedProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'help_dialog_opened',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track help_dialog_opened:', error);
}
}
/**
* Track settings opened event
*/
static async trackSettingsOpened(properties: SettingsOpenedProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'settings_opened',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track settings_opened:', error);
}
}
/**
* Track settings saved event
*/
static async trackSettingsSaved(properties: SettingsSavedProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'settings_saved',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track settings_saved:', error);
}
}
/**
* Track sidebar toggled event
*/
static async trackSidebarToggled(properties: SidebarToggledProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'sidebar_toggled',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track sidebar_toggled:', error);
}
}
/**
* Track search used event
*/
static async trackSearchUsed(properties: SearchUsedProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'search_used',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track search_used:', error);
}
}
/**
* Track notification shown event
*/
static async trackNotificationShown(properties: NotificationShownProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'notification_shown',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track notification_shown:', error);
}
}
/**
* Helper: Categorize search result count for privacy
*/
static async categorizeResultCount(count: number): Promise<string> {
if (!this.isEnabled()) return 'unknown';
try {
const response = await window.electronAPI.analytics.categorizeResultCount(count);
return response.data || 'unknown';
} catch (error) {
console.error('[Analytics] Failed to categorize result count:', error);
return 'unknown';
}
}
/**
* Helper: Hash session ID for privacy
*/
static async hashSessionId(sessionId: string): Promise<string | undefined> {
if (!this.isEnabled()) return undefined;
try {
const response = await window.electronAPI.analytics.hashSessionId(sessionId);
return response.data;
} catch (error) {
console.error('[Analytics] Failed to hash session ID:', error);
return undefined;
}
}
/**
* Track Nimbalyst button clicked event
*/
static async trackNimbalystButtonClicked(properties: NimbalystButtonClickedProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'nimbalyst_button_clicked',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track nimbalyst_button_clicked:', error);
}
}
/**
* Track Nimbalyst install dialog shown event
*/
static async trackNimbalystInstallDialogShown(properties: NimbalystInstallDialogShownProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'nimbalyst_install_dialog_shown',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track nimbalyst_install_dialog_shown:', error);
}
}
/**
* Track Nimbalyst download clicked event
*/
static async trackNimbalystDownloadClicked(properties: NimbalystDownloadClickedProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'nimbalyst_download_clicked',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track nimbalyst_download_clicked:', error);
}
}
/**
* Track Nimbalyst successfully opened event
*/
static async trackNimbalystOpened(properties: NimbalystOpenedProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'nimbalyst_opened',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track nimbalyst_opened:', error);
}
}
/**
* Track analytics opted in event
* Called when user accepts analytics in the consent dialog
*/
static async trackAnalyticsOptedIn(): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'analytics_opted_in',
properties: {},
});
} catch (error) {
console.error('[Analytics] Failed to track analytics_opted_in:', error);
}
}
/**
* Track analytics opted out event
* Called when user declines analytics in the consent dialog
* Uses minimal tracking to ensure this event is captured even when disabling analytics
*/
static async trackAnalyticsOptedOut(): Promise<void> {
if (!this.isEnabled()) return;
try {
// Use the standard UI event tracking - the backend will use minimal tracking
// for opt-out events to ensure they're captured
await window.electronAPI.analytics.trackUIEvent({
event: 'analytics_opted_out',
properties: {},
});
} catch (error) {
console.error('[Analytics] Failed to track analytics_opted_out:', error);
}
}
}
// Export the class as a singleton-like service for static method usage
export const analyticsService = AnalyticsService;

View File

@ -60,6 +60,14 @@ export const panelApi = {
async emitPanelEvent(panelId: string, eventType: string, data: Record<string, unknown>): Promise<void> {
// Use direct invoke for event emission as there's no typed wrapper for this
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- IPC event emission returns void
return window.electron!.invoke('panels:emitEvent', panelId, eventType, data) as any;
return window.electron!.invoke('panels:emitEvent', panelId, eventType, data) as unknown as void;
},
async clearPanelUnviewedContent(panelId: string): Promise<void> {
// Clear the hasUnviewedContent flag and set status to 'stopped' for AI panels
const response = await window.electron!.invoke('panels:clearUnviewedContent', panelId);
if (!response.success) {
throw new Error(response.error || 'Failed to clear unviewed content');
}
}
};

View File

@ -46,4 +46,10 @@ export interface AppConfig {
};
// Crystal commit footer setting (enabled by default)
enableCrystalFooter?: boolean;
// PostHog analytics settings
analytics?: {
enabled: boolean;
posthogApiKey?: string;
posthogHost?: string;
};
}

View File

@ -341,6 +341,22 @@ interface ElectronAPI {
}>;
}>>;
};
// Nimbalyst integration
nimbalyst: {
checkInstalled: () => Promise<IPCResponse<boolean>>;
openWorktree: (worktreePath: string) => Promise<IPCResponse>;
};
// Analytics tracking
analytics: {
trackUIEvent: (eventData: {
event: string;
properties: Record<string, string | number | boolean | string[] | undefined>;
}) => Promise<IPCResponse>;
categorizeResultCount: (count: number) => Promise<IPCResponse<string>>;
hashSessionId: (sessionId: string) => Promise<IPCResponse<string>>;
};
}
// Additional electron interface for IPC event listeners

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

View File

@ -1,6 +1,6 @@
{
"name": "main",
"version": "0.3.3",
"version": "0.3.5",
"description": "Electron main process for Claude Code Commander",
"main": "dist/main/src/index.js",
"type": "commonjs",
@ -26,9 +26,11 @@
"electron-store": "^11.0.0",
"electron-updater": "^6.6.8",
"glob": "^11.0.0",
"posthog-node": "^5.11.2",
"web-streams-polyfill": "^3.3.3"
},
"devDependencies": {
"@electron/rebuild": "^4.0.1",
"@types/better-sqlite3": "^7.6.13",
"@types/bull": "^4.10.0",
"@types/glob": "^9.0.0",
@ -37,7 +39,6 @@
"@typescript-eslint/parser": "^8.19.0",
"@vitest/coverage-v8": "^2.1.8",
"electron": "^37.6.0",
"@electron/rebuild": "^4.0.1",
"eslint": "^9.17.0",
"mkdirp": "^3.0.1",
"rimraf": "^6.0.1",

View File

@ -724,13 +724,23 @@ export class DatabaseService {
id INTEGER PRIMARY KEY AUTOINCREMENT,
opened_at DATETIME DEFAULT CURRENT_TIMESTAMP,
welcome_hidden BOOLEAN DEFAULT 0,
discord_shown BOOLEAN DEFAULT 0
discord_shown BOOLEAN DEFAULT 0,
app_version TEXT
)
`).run();
this.db.prepare("CREATE INDEX idx_app_opens_opened_at ON app_opens(opened_at)").run();
console.log('[Database] Created app_opens table');
}
// Add app_version column to app_opens table if it doesn't exist
const appOpensTableInfo = this.db.prepare("PRAGMA table_info(app_opens)").all() as SqliteTableInfo[];
const hasAppVersionColumn = appOpensTableInfo.some((col: SqliteTableInfo) => col.name === 'app_version');
if (!hasAppVersionColumn) {
this.db.prepare("ALTER TABLE app_opens ADD COLUMN app_version TEXT").run();
console.log('[Database] Added app_version column to app_opens table');
}
// Remove model column from sessions table if it exists (moved to panel level)
const sessionTableInfoModel = this.db.prepare("PRAGMA table_info(sessions)").all() as SqliteTableInfo[];
const hasModelColumn = sessionTableInfoModel.some((col: SqliteTableInfo) => col.name === 'model');
@ -2509,30 +2519,43 @@ export class DatabaseService {
}
// App opens operations
recordAppOpen(welcomeHidden: boolean, discordShown: boolean = false): void {
recordAppOpen(welcomeHidden: boolean, discordShown: boolean = false, appVersion?: string): void {
this.db.prepare(`
INSERT INTO app_opens (welcome_hidden, discord_shown)
VALUES (?, ?)
`).run(welcomeHidden ? 1 : 0, discordShown ? 1 : 0);
INSERT INTO app_opens (welcome_hidden, discord_shown, app_version)
VALUES (?, ?, ?)
`).run(welcomeHidden ? 1 : 0, discordShown ? 1 : 0, appVersion || null);
}
getLastAppOpen(): { opened_at: string; welcome_hidden: boolean; discord_shown: boolean } | null {
getLastAppOpen(): { opened_at: string; welcome_hidden: boolean; discord_shown: boolean; app_version?: string } | null {
const result = this.db.prepare(`
SELECT opened_at, welcome_hidden, discord_shown
SELECT opened_at, welcome_hidden, discord_shown, app_version
FROM app_opens
ORDER BY opened_at DESC
LIMIT 1
`).get() as { opened_at: string; welcome_hidden: number; discord_shown: number } | undefined;
`).get() as { opened_at: string; welcome_hidden: number; discord_shown: number; app_version?: string } | undefined;
if (!result) return null;
return {
opened_at: result.opened_at,
welcome_hidden: Boolean(result.welcome_hidden),
discord_shown: Boolean(result.discord_shown)
discord_shown: Boolean(result.discord_shown),
app_version: result.app_version
};
}
getLastAppVersion(): string | null {
const result = this.db.prepare(`
SELECT app_version
FROM app_opens
WHERE app_version IS NOT NULL
ORDER BY opened_at DESC
LIMIT 1
`).get() as { app_version: string } | undefined;
return result?.app_version || null;
}
updateLastAppOpenDiscordShown(): void {
this.db.prepare(`
UPDATE app_opens

View File

@ -5,14 +5,15 @@ import type { VersionInfo } from './services/versionChecker';
import { addSessionLog } from './ipc/logs';
import { getCodexModelConfig } from '../../shared/types/models';
import { panelManager } from './services/panelManager';
import type { ToolPanel, CodexPanelState, ClaudePanelState } from '../../shared/types/panels';
import { terminalPanelManager } from './services/terminalPanelManager';
import type { ToolPanel, CodexPanelState, ClaudePanelState, BaseAIPanelState, PanelStatus } from '../../shared/types/panels';
import type { ClaudePanelManager } from './services/panels/claude/claudePanelManager';
import type { SessionOutput } from './types/session';
import {
validateSessionExists,
validateEventContext,
import {
validateSessionExists,
validateEventContext,
validatePanelEventContext,
logValidationFailure
logValidationFailure
} from './utils/sessionValidation';
import type { AbstractCliManager } from './services/panels/cli/AbstractCliManager';
import type { GitCommit } from './services/gitDiffManager';
@ -30,9 +31,16 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
worktreeManager,
archiveProgressManager,
databaseService,
logger
logger,
analyticsManager
} = services;
// Wire up analytics manager to panel managers
if (analyticsManager) {
panelManager.setAnalyticsManager(analyticsManager);
terminalPanelManager.setAnalyticsManager(analyticsManager);
}
let codexCliManager: AbstractCliManager | undefined;
try {
const { codexManager: resolvedCodexManager } = require('./ipc/codexPanel');
@ -68,7 +76,10 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
// eslint-disable-next-line no-control-regex
const ANSI_ESCAPE_REGEX = /\x1B\[[0-9;]*m/g;
// Original format: "76k/200k tokens (38%)"
const CONTEXT_USAGE_REGEX = /([0-9]+(?:\.[0-9]+)?k?\s*\/\s*[0-9]+(?:\.[0-9]+)?k?\s+tokens?\s*\(\d+%[^)]*\))/i;
// Alternative format: "Context: 76000/200000 tokens" or similar
const CONTEXT_USAGE_ALT_REGEX = /context[:\s]+([0-9,]+)\s*(?:\/|of)\s*([0-9,]+)\s*tokens?/i;
const extractCandidateStrings = (payload: unknown): string[] => {
const strings: string[] = [];
@ -113,33 +124,157 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
return strings;
};
// Helper to format token count (e.g., 76000 -> "76k", 200000 -> "200k")
const formatTokenCount = (count: number): string => {
if (count >= 1000) {
return `${Math.round(count / 1000)}k`;
}
return String(count);
};
// Try to extract context usage from JSON result message with modelUsage
const extractContextFromResultJson = (data: Record<string, unknown>): string | null => {
// Check for result type with modelUsage
if (data.type !== 'result' || !data.modelUsage) {
return null;
}
const modelUsage = data.modelUsage as Record<string, unknown>;
// Find the first model with contextWindow info
for (const modelData of Object.values(modelUsage)) {
if (typeof modelData !== 'object' || modelData === null) continue;
const model = modelData as Record<string, unknown>;
const contextWindow = model.contextWindow;
if (typeof contextWindow !== 'number' || contextWindow <= 0) continue;
// Calculate current context usage from cache tokens
// cacheReadInputTokens represents tokens read from cache (already in context)
const cacheRead = typeof model.cacheReadInputTokens === 'number' ? model.cacheReadInputTokens : 0;
const cacheCreation = typeof model.cacheCreationInputTokens === 'number' ? model.cacheCreationInputTokens : 0;
const inputTokens = typeof model.inputTokens === 'number' ? model.inputTokens : 0;
// Estimate current context as the input tokens for the most recent turn
// This is an approximation since we don't have exact current context size
const estimatedContext = Math.min(inputTokens + cacheRead, contextWindow);
if (estimatedContext > 0) {
const percentage = Math.round((estimatedContext / contextWindow) * 100);
return `${formatTokenCount(estimatedContext)}/${formatTokenCount(contextWindow)} tokens (${percentage}%)`;
}
}
return null;
};
// Try to extract context usage from system init message
const extractContextFromInitJson = (data: Record<string, unknown>): string | null => {
if (data.type !== 'system' || data.subtype !== 'init') {
return null;
}
// Check for context_tokens field (new format)
if (typeof data.context_tokens === 'number' && typeof data.context_window === 'number') {
const used = data.context_tokens;
const max = data.context_window;
const percentage = Math.round((used / max) * 100);
return `${formatTokenCount(used)}/${formatTokenCount(max)} tokens (${percentage}%)`;
}
return null;
};
const extractContextUsageFromOutputs = (outputs: SessionOutput[]): string | null => {
console.log(`[auto-context-debug] extractContextUsageFromOutputs called with ${outputs.length} outputs`);
// Log output types for debugging
const typeCounts: Record<string, number> = {};
for (const output of outputs) {
if (output.type !== 'stdout' || typeof output.data !== 'string') {
if (output.type === 'json' && output.data && typeof output.data === 'object') {
const candidates = extractCandidateStrings(output.data);
for (const candidate of candidates) {
const match = typeof candidate === 'string' ? candidate.match(CONTEXT_USAGE_REGEX) : null;
if (match) {
return match[1].replace(/\s+/g, ' ').trim();
}
const key = output.type === 'json' && output.data && typeof output.data === 'object'
? `json:${(output.data as Record<string, unknown>).type || 'unknown'}`
: output.type;
typeCounts[key] = (typeCounts[key] || 0) + 1;
}
console.log(`[auto-context-debug] Output types: ${JSON.stringify(typeCounts)}`);
for (const output of outputs) {
// Handle JSON outputs
if (output.type === 'json' && output.data && typeof output.data === 'object') {
const jsonData = output.data as Record<string, unknown>;
// Try to extract from result message (new format)
const resultContext = extractContextFromResultJson(jsonData);
if (resultContext) {
console.log(`[auto-context-debug] Found context in result JSON: ${resultContext}`);
return resultContext;
}
// Try to extract from init message
const initContext = extractContextFromInitJson(jsonData);
if (initContext) {
console.log(`[auto-context-debug] Found context in init JSON: ${initContext}`);
return initContext;
}
// Try original string extraction method
const candidates = extractCandidateStrings(output.data);
for (const candidate of candidates) {
if (typeof candidate !== 'string') continue;
// Try original regex
const match = candidate.match(CONTEXT_USAGE_REGEX);
if (match) {
console.log(`[auto-context-debug] Found context via original regex: ${match[1]}`);
return match[1].replace(/\s+/g, ' ').trim();
}
// Try alternative format
const altMatch = candidate.match(CONTEXT_USAGE_ALT_REGEX);
if (altMatch) {
const used = parseInt(altMatch[1].replace(/,/g, ''), 10);
const max = parseInt(altMatch[2].replace(/,/g, ''), 10);
const percentage = Math.round((used / max) * 100);
const result = `${formatTokenCount(used)}/${formatTokenCount(max)} tokens (${percentage}%)`;
console.log(`[auto-context-debug] Found context via alt regex: ${result}`);
return result;
}
}
continue;
}
// Handle stdout outputs
if (output.type !== 'stdout' || typeof output.data !== 'string') {
continue;
}
const cleanedLines = output.data
.replace(ANSI_ESCAPE_REGEX, '')
.split(/\r?\n/);
for (const line of cleanedLines) {
// Try original regex
const match = line.match(CONTEXT_USAGE_REGEX);
if (match) {
console.log(`[auto-context-debug] Found context in stdout via original regex: ${match[1]}`);
return match[1].replace(/\s+/g, ' ').trim();
}
// Try alternative format
const altMatch = line.match(CONTEXT_USAGE_ALT_REGEX);
if (altMatch) {
const used = parseInt(altMatch[1].replace(/,/g, ''), 10);
const max = parseInt(altMatch[2].replace(/,/g, ''), 10);
const percentage = Math.round((used / max) * 100);
const result = `${formatTokenCount(used)}/${formatTokenCount(max)} tokens (${percentage}%)`;
console.log(`[auto-context-debug] Found context in stdout via alt regex: ${result}`);
return result;
}
}
}
console.log(`[auto-context-debug] No context usage found in outputs`);
return null;
};
@ -189,6 +324,71 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
});
};
/**
* Update the status of an AI panel (claude/codex) and notify frontend
*/
const updateAIPanelStatus = async (
panelId: string,
status: PanelStatus,
hasUnviewedContent?: boolean
): Promise<void> => {
const { withLock } = await import('./utils/mutex');
return await withLock(`panel-state-${panelId}`, async () => {
const panel = panelManager.getPanel(panelId);
if (!panel) {
return;
}
// Only update status for AI panels (claude/codex)
if (panel.type !== 'claude' && panel.type !== 'codex') {
return;
}
const existing = (panel.state.customState as BaseAIPanelState | undefined) ?? {};
const nextCustomState: BaseAIPanelState = {
...existing,
panelStatus: status,
lastActivityTime: new Date().toISOString()
};
// Only update hasUnviewedContent if explicitly provided
if (hasUnviewedContent !== undefined) {
nextCustomState.hasUnviewedContent = hasUnviewedContent;
}
const nextPanelState = {
...panel.state,
customState: nextCustomState
};
await panelManager.updatePanel(panelId, { state: nextPanelState });
const mw = getMainWindow();
if (mw && !mw.isDestroyed()) {
try {
mw.webContents.send('panel:updated', {
...panel,
state: nextPanelState
});
} catch (ipcError) {
console.error(`[Main] Failed to send panel:updated event for panel ${panelId}:`, ipcError);
}
}
});
};
/**
* Check if the panel is currently the active panel for its session
*/
const isPanelActive = (panelId: string, _sessionId: string): boolean => {
// Check if this panel is the active panel by looking at the panel's isActive state
const panel = panelManager.getPanel(panelId);
if (!panel) return false;
// Use the panel's state.isActive property which is set when a panel becomes active
return panel.state.isActive === true;
};
const finalizeAutoContextRun = async (panelId: string): Promise<void> => {
console.log(`[auto-context-debug] finalizeAutoContextRun called for panel ${panelId}`);
try {
@ -312,6 +512,10 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
return;
}
// Update panel status to running
if (panelId) {
await updateAIPanelStatus(panelId, 'running');
}
await new Promise(resolve => setTimeout(resolve, 100));
@ -359,6 +563,14 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
const signalText = signal === null || signal === undefined ? 'null' : String(signal);
// Update panel status to stopped/completed_unviewed
if (panelId) {
const isActive = isPanelActive(panelId, sessionId);
// If panel is not active, mark as having unviewed content
const panelStatusOnExit: PanelStatus = exitCode === 0 && !isActive ? 'completed_unviewed' : 'stopped';
await updateAIPanelStatus(panelId, panelStatusOnExit, exitCode === 0 && !isActive);
}
if (exitCode !== null && exitCode !== undefined) {
await sessionManager.setSessionExitCode(sessionId, exitCode);
}
@ -367,23 +579,40 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
if (session) {
const dbSession = sessionManager.getDbSession(sessionId);
// If exit code is 0 (successful completion), mark as completed
// The updateSession method will handle converting to 'completed_unviewed' if not viewed
if (exitCode === 0 && dbSession && dbSession.status === 'running') {
// Update to 'stopped' which will be converted to 'completed_unviewed' by the mapping logic
// since the database status will be set to 'completed'
sessionManager.db.updateSession(sessionId, { status: 'completed' });
// Check if ALL panels for this session have stopped before updating session status
const sessionPanels = panelManager.getPanelsForSession(sessionId);
const aiPanels = sessionPanels.filter((p: ToolPanel) => p.type === 'claude' || p.type === 'codex');
// Get the updated session with proper status mapping
const updatedSession = sessionManager.getSession(sessionId);
if (updatedSession) {
// Manually emit the event since we bypassed updateSession for direct DB access
sessionManager.emit('session-updated', updatedSession);
// Check if any AI panel is still running
const hasRunningPanels = aiPanels.some((p: ToolPanel) => {
const customState = p.state?.customState as BaseAIPanelState | undefined;
return customState?.panelStatus === 'running' || customState?.panelStatus === 'waiting';
});
// Only update session status if no panels are still running
if (!hasRunningPanels) {
// If exit code is 0 (successful completion), mark as completed
// The updateSession method will handle converting to 'completed_unviewed' if not viewed
if (exitCode === 0 && dbSession && dbSession.status === 'running') {
// Update to 'stopped' which will be converted to 'completed_unviewed' by the mapping logic
// since the database status will be set to 'completed'
sessionManager.db.updateSession(sessionId, { status: 'completed' });
// Get the updated session with proper status mapping
const updatedSession = sessionManager.getSession(sessionId);
if (updatedSession) {
// Manually emit the event since we bypassed updateSession for direct DB access
sessionManager.emit('session-updated', updatedSession);
}
}
// For non-zero exit codes or already completed sessions
else if (dbSession && dbSession.status !== 'completed') {
await sessionManager.updateSession(sessionId, { status: 'stopped' });
}
}
// For non-zero exit codes or already completed sessions
else if (dbSession && dbSession.status !== 'completed') {
await sessionManager.updateSession(sessionId, { status: 'stopped' });
// If panels are still running, keep session in running state
else if (dbSession && dbSession.status !== 'running') {
await sessionManager.updateSession(sessionId, { status: 'running' });
}
}
@ -654,6 +883,10 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
// Check if Claude is waiting for user input
if (output.type === 'json' && typeof output.data === 'object' && output.data && 'type' in output.data && output.data.type === 'prompt') {
console.log(`[Main] Claude is waiting for user input in session ${output.sessionId}`);
// Update panel status to waiting
if (output.panelId) {
await updateAIPanelStatus(output.panelId, 'waiting');
}
await sessionManager.updateSession(output.sessionId, { status: 'waiting' });
}
@ -675,7 +908,7 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
claudeCodeManager.on('spawned', async ({ panelId, sessionId }: { panelId?: string; sessionId: string }) => {
// Validate the event context
const validation = panelId
const validation = panelId
? validatePanelEventContext({ panelId, sessionId }, panelId, sessionId)
: validateEventContext({ sessionId }, sessionId);
@ -684,6 +917,10 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
return; // Don't process invalid events
}
// Update panel status to running
if (panelId) {
await updateAIPanelStatus(panelId, 'running');
}
// Add a small delay to ensure the session is fully initialized
await new Promise(resolve => setTimeout(resolve, 100));
@ -906,6 +1143,8 @@ export function setupEventListeners(services: AppServices, getMainWindow: () =>
if (panelId) {
console.log(`Panel ${panelId} (session ${sessionId}) encountered an error: ${error}`);
// Update panel status to error
await updateAIPanelStatus(panelId, 'error');
} else {
console.log(`Session ${sessionId} encountered an error: ${error}`);
}

View File

@ -27,6 +27,7 @@ import { StravuAuthManager } from './services/stravuAuthManager';
import { StravuNotebookService } from './services/stravuNotebookService';
import { Logger } from './utils/logger';
import { ArchiveProgressManager } from './services/archiveProgressManager';
import { AnalyticsManager } from './services/analyticsManager';
import { initializeCommitManager } from './services/commitManager';
import { setCrystalDirectory } from './utils/crystalDirectory';
import { getCurrentWorktreeName } from './utils/worktreeUtils';
@ -83,6 +84,10 @@ let versionChecker: VersionChecker;
let stravuAuthManager: StravuAuthManager;
let stravuNotebookService: StravuNotebookService;
let archiveProgressManager: ArchiveProgressManager;
let analyticsManager: AnalyticsManager;
// Store app start time for session duration tracking
let appStartTime: number;
// Store original console methods before overriding
// These must be captured immediately when the module loads
@ -92,6 +97,176 @@ const originalWarn: typeof console.warn = console.warn;
const originalInfo: typeof console.info = console.info;
const isDevelopment = process.env.NODE_ENV !== 'production' && !app.isPackaged;
const NIMBALYST_URL = 'https://nimbalyst.com/';
const NIMBALYST_DOWNLOAD_URL = 'https://nimbalyst.com/download/';
async function showNimbalystMigrationPopup(): Promise<void> {
if (!mainWindow || mainWindow.isDestroyed()) {
return;
}
// Load preview image as base64 data URI
let previewImageSrc = '';
try {
const imagePath = path.join(app.getAppPath(), 'main/assets/nimbalyst-preview.jpg');
const imageData = fs.readFileSync(imagePath);
previewImageSrc = `data:image/jpeg;base64,${imageData.toString('base64')}`;
} catch {
// Image not found — modal will just skip the preview
}
const modal = new BrowserWindow({
parent: mainWindow,
modal: true,
width: 660,
height: 760,
resizable: false,
minimizable: false,
maximizable: false,
show: false,
title: 'Crystal Is Now Nimbalyst',
webPreferences: {
contextIsolation: true,
nodeIntegration: false
}
});
modal.removeMenu();
modal.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
const modalHtml = `
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Crystal Is Now Nimbalyst</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #0f1219;
color: #f9fafb;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
text-align: center;
padding: 32px 44px;
max-width: 600px;
width: 100%;
}
.logo {
width: 56px;
height: 56px;
margin: 0 auto 16px;
}
h1 {
font-size: 21px;
font-weight: 700;
margin-bottom: 6px;
letter-spacing: -0.3px;
}
.subtitle {
font-size: 13px;
line-height: 1.5;
color: #9ca3af;
margin-bottom: 20px;
}
.preview {
margin-bottom: 20px;
border-radius: 10px;
overflow: hidden;
border: 1px solid #1e2433;
}
.preview img {
width: 100%;
display: block;
}
.actions {
display: flex;
flex-direction: column;
gap: 8px;
}
button {
border: none;
border-radius: 10px;
padding: 11px 16px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
transition: opacity 0.15s, transform 0.1s;
width: 100%;
}
button:hover { opacity: 0.9; }
button:active { transform: scale(0.98); }
.btn-row {
display: flex;
gap: 8px;
}
.btn-row button { flex: 1; }
#download {
background: linear-gradient(135deg, #4f6ef7, #6395ff);
color: white;
}
#website {
background: #1a1f2e;
color: #d1d5db;
}
#continue {
background: none;
color: #6b7280;
font-size: 13px;
padding: 6px;
}
#continue:hover { color: #9ca3af; }
</style>
</head>
<body>
<div class="container">
<div class="logo">
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#6395ff" 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';fill:#ffffff" x="306.01437" y="668.91577">#</text></svg>
</div>
<h1>Crystal is now Nimbalyst</h1>
<p class="subtitle">Crystal has evolved into Nimbalyst with powerful new features. We recommend making the switch.</p>
${previewImageSrc ? `<div class="preview"><img src="${previewImageSrc}" alt="Nimbalyst preview" /></div>` : ''}
<div class="actions">
<button id="download">Download Nimbalyst</button>
<div class="btn-row">
<button id="website">Visit Website</button>
<button id="continue">Continue with Crystal</button>
</div>
</div>
</div>
<script>
document.getElementById('website')?.addEventListener('click', () => {
window.open('${NIMBALYST_URL}', '_blank', 'noopener,noreferrer');
});
document.getElementById('download')?.addEventListener('click', () => {
window.open('${NIMBALYST_DOWNLOAD_URL}', '_blank', 'noopener,noreferrer');
});
document.getElementById('continue')?.addEventListener('click', () => {
window.close();
});
</script>
</body>
</html>`;
modal.once('ready-to-show', () => {
modal.show();
});
await modal.loadURL(`data:text/html;charset=UTF-8,${encodeURIComponent(modalHtml)}`);
await new Promise<void>((resolve) => {
modal.once('closed', () => resolve());
});
}
// Reset debug log files at startup in development mode
if (isDevelopment) {
@ -537,9 +712,17 @@ async function initializeServices() {
databaseService = new DatabaseService(dbPath);
databaseService.initialize();
sessionManager = new SessionManager(databaseService);
// Initialize analytics manager early so it can be used by SessionManager
analyticsManager = new AnalyticsManager(configManager);
await analyticsManager.initialize();
// Set analytics manager on logsManager for script execution tracking
const { logsManager } = await import('./services/panels/logPanel/logsManager');
logsManager.setAnalyticsManager(analyticsManager);
sessionManager = new SessionManager(databaseService, analyticsManager);
sessionManager.initializeFromDatabase();
archiveProgressManager = new ArchiveProgressManager();
// Start permission IPC server
@ -559,8 +742,8 @@ async function initializeServices() {
permissionIpcServer = null;
}
// Create worktree manager with configManager
worktreeManager = new WorktreeManager(configManager);
// Create worktree manager with configManager and analyticsManager
worktreeManager = new WorktreeManager(configManager, analyticsManager);
// Initialize the active project's worktree directory if one exists
const activeProject = sessionManager.getActiveProject();
@ -570,20 +753,22 @@ async function initializeServices() {
// Initialize CLI manager factory
cliManagerFactory = CliManagerFactory.getInstance(logger, configManager);
// Create default CLI manager (Claude) with permission IPC path
// Skip validation during startup - tools will be validated when actually used
defaultCliManager = await cliManagerFactory.createManager('claude', {
sessionManager,
logger,
configManager,
additionalOptions: { permissionIpcPath }
additionalOptions: { permissionIpcPath },
skipValidation: true // Allow Crystal to start even if Claude Code is not installed
});
gitDiffManager = new GitDiffManager();
gitDiffManager = new GitDiffManager(logger, analyticsManager);
gitStatusManager = new GitStatusManager(sessionManager, worktreeManager, gitDiffManager, logger);
executionTracker = new ExecutionTracker(sessionManager, gitDiffManager);
worktreeNameGenerator = new WorktreeNameGenerator(configManager);
runCommandManager = new RunCommandManager(databaseService);
// Initialize version checker
versionChecker = new VersionChecker(configManager, logger);
stravuAuthManager = new StravuAuthManager(logger);
@ -619,6 +804,7 @@ async function initializeServices() {
getMainWindow: () => mainWindow,
logger,
archiveProgressManager,
analyticsManager,
};
// Initialize IPC handlers first so managers (like ClaudePanelManager) are ready
@ -654,15 +840,53 @@ async function initializeServices() {
}
app.whenReady().then(async () => {
// Record app start time
appStartTime = Date.now();
console.log('[Main] App is ready, initializing services...');
await initializeServices();
console.log('[Main] Services initialized, creating window...');
await createWindow();
console.log('[Main] Window created successfully');
await showNimbalystMigrationPopup();
// Track app lifecycle events
try {
const currentVersion = app.getVersion();
const lastVersion = databaseService.getLastAppVersion();
const isFirstLaunch = lastVersion === null;
// Check if version changed (app update)
if (lastVersion && lastVersion !== currentVersion) {
console.log(`[Analytics] App updated from ${lastVersion} to ${currentVersion}`);
analyticsManager.track('app_updated', {
previous_version: lastVersion,
new_version: currentVersion
});
}
// Track app opened - use minimal tracking if analytics is disabled
console.log(`[Analytics] App opened (version: ${currentVersion}, first_launch: ${isFirstLaunch}, analytics_enabled: ${configManager.isAnalyticsEnabled()})`);
if (configManager.isAnalyticsEnabled()) {
analyticsManager.track('app_opened', {
is_first_launch: isFirstLaunch
});
} else {
// Track minimal app_opened event even when opted out
analyticsManager.trackMinimalEvent('app_opened', {
is_first_launch: isFirstLaunch
});
}
// Record app open in database with version
databaseService.recordAppOpen(false, false, currentVersion);
} catch (error) {
console.error('[Analytics] Failed to track app lifecycle events:', error);
}
// Configure auto-updater
setupAutoUpdater(() => mainWindow);
// Check for updates after window is created
setTimeout(async () => {
console.log('[Main] Performing startup version check...');
@ -764,6 +988,23 @@ app.on('before-quit', async (event) => {
versionChecker.stopPeriodicCheck();
}
// Track app closed event with session duration
if (analyticsManager && appStartTime) {
try {
const sessionDurationSeconds = Math.floor((Date.now() - appStartTime) / 1000);
console.log(`[Analytics] App closed after ${sessionDurationSeconds} seconds`);
analyticsManager.track('app_closed', {
session_duration_seconds: sessionDurationSeconds
});
// Flush analytics events before shutdown
await analyticsManager.flush();
await analyticsManager.shutdown();
} catch (error) {
console.error('[Analytics] Failed to track app_closed event:', error);
}
}
// Close logger to ensure all logs are flushed
if (logger) {
logger.close();

152
main/src/ipc/analytics.ts Normal file
View File

@ -0,0 +1,152 @@
import { IpcMain } from 'electron';
import type { AppServices } from './types';
/**
* UI Interaction Event properties
*/
interface ViewSwitchedEvent extends Record<string, string | number | boolean | string[] | undefined> {
from_view: string;
to_view: string;
session_id_hash?: string;
}
interface HelpDialogOpenedEvent extends Record<string, string | number | boolean | string[] | undefined> {
from_location: string;
}
interface SettingsOpenedEvent extends Record<string, string | number | boolean | string[] | undefined> {
from_location: string;
}
interface SettingsSavedEvent extends Record<string, string | number | boolean | string[] | undefined> {
category: string;
setting_keys: string[];
}
interface SidebarToggledEvent extends Record<string, string | number | boolean | string[] | undefined> {
is_visible: boolean;
}
interface SearchUsedEvent extends Record<string, string | number | boolean | string[] | undefined> {
search_type: string;
result_count_category: string;
}
interface NotificationShownEvent extends Record<string, string | number | boolean | string[] | undefined> {
notification_type: string;
trigger_event: string;
}
// Event types for analytics opt-in/opt-out (no additional properties needed)
type AnalyticsOptedOutEvent = Record<string, string | number | boolean | string[] | undefined>;
type AnalyticsOptedInEvent = Record<string, string | number | boolean | string[] | undefined>;
interface NimbalystButtonClickedEvent extends Record<string, string | number | boolean | string[] | undefined> {
session_id_hash?: string;
}
interface NimbalystInstallDialogShownEvent extends Record<string, string | number | boolean | string[] | undefined> {
session_id_hash?: string;
}
// Event type for Nimbalyst download clicked (no additional properties needed)
type NimbalystDownloadClickedEvent = Record<string, string | number | boolean | string[] | undefined>;
interface NimbalystOpenedEvent extends Record<string, string | number | boolean | string[] | undefined> {
session_id_hash?: 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: 'analytics_opted_out'; properties: AnalyticsOptedOutEvent }
| { event: 'analytics_opted_in'; properties: AnalyticsOptedInEvent }
| { event: 'nimbalyst_button_clicked'; properties: NimbalystButtonClickedEvent }
| { event: 'nimbalyst_install_dialog_shown'; properties: NimbalystInstallDialogShownEvent }
| { event: 'nimbalyst_download_clicked'; properties: NimbalystDownloadClickedEvent }
| { event: 'nimbalyst_opened'; properties: NimbalystOpenedEvent };
/**
* Register IPC handlers for analytics tracking
*/
export function registerAnalyticsHandlers(ipcMain: IpcMain, services: AppServices): void {
const { analyticsManager } = services;
if (!analyticsManager) {
console.warn('[Analytics IPC] AnalyticsManager not available, analytics tracking disabled');
return;
}
/**
* Track UI interaction events from the frontend
*/
ipcMain.handle('analytics:track-ui-event', async (_event, data: AnalyticsEventData) => {
try {
// Validate event data
if (!data || !data.event || !data.properties) {
console.error('[Analytics IPC] Invalid event data:', data);
return { success: false, error: 'Invalid event data' };
}
// Special handling for opt-out event: use minimal tracking to ensure it's captured
if (data.event === 'analytics_opted_out') {
// Use minimal tracking for opt-out events (works even when analytics is disabled)
analyticsManager.trackMinimalEvent(data.event, data.properties);
} else {
// Normal tracking (respects enabled/disabled state)
analyticsManager.track(data.event, data.properties);
}
return { success: true };
} catch (error) {
console.error('[Analytics IPC] Failed to track UI event:', error);
return { success: false, error: 'Failed to track event' };
}
});
/**
* Track minimal events (used for opt-out tracking and basic app opens when opted out)
*/
ipcMain.handle('analytics:track-minimal-event', async (_event, eventName: string, properties?: Record<string, string | number | boolean | string[] | undefined>) => {
try {
analyticsManager.trackMinimalEvent(eventName, properties);
return { success: true };
} catch (error) {
console.error('[Analytics IPC] Failed to track minimal event:', error);
return { success: false, error: 'Failed to track minimal event' };
}
});
/**
* Helper to categorize search result counts
*/
ipcMain.handle('analytics:categorize-result-count', async (_event, count: number) => {
try {
const category = analyticsManager.categorizeNumber(count, [0, 5, 10, 25, 50, 100]);
return { success: true, data: category };
} catch (error) {
console.error('[Analytics IPC] Failed to categorize result count:', error);
return { success: false, error: 'Failed to categorize result count' };
}
});
/**
* Helper to hash session IDs
*/
ipcMain.handle('analytics:hash-session-id', async (_event, sessionId: string) => {
try {
const hash = analyticsManager.hashSessionId(sessionId);
return { success: true, data: hash };
} catch (error) {
console.error('[Analytics IPC] Failed to hash session ID:', error);
return { success: false, error: 'Failed to hash session ID' };
}
});
console.log('[Analytics IPC] Analytics IPC handlers registered');
}

View File

@ -59,14 +59,15 @@ export abstract class BaseAIPanelHandler {
*/
protected registerExistingPanels(): void {
const { databaseService, logger } = this.services;
logger?.info(`[${this.config.panelTypeName}] Registering existing ${this.config.panelTypeName} panels from database...`);
const activePanels = databaseService.getActivePanels();
const typedPanels = activePanels.filter(panel => panel.type === this.config.panelType);
for (const panel of typedPanels) {
try {
this.panelManager.registerPanel(panel.id, panel.sessionId);
// Pass false for isUserInitiated since this is restoration from database
this.panelManager.registerPanel(panel.id, panel.sessionId, undefined, false);
logger?.info(`[${this.config.panelTypeName}] Registered existing panel ${panel.id} for session ${panel.sessionId}`);
} catch (error) {
logger?.error(`[${this.config.panelTypeName}] Failed to register existing panel ${panel.id}: ${error}`);

View File

@ -10,8 +10,8 @@ let claudePanelManager: ClaudePanelManager;
class ClaudePanelHandler extends BaseAIPanelHandler {
protected createPanelManager(): ClaudePanelManager {
const { sessionManager, claudeCodeManager, logger, configManager } = this.services;
return new ClaudePanelManager(claudeCodeManager, sessionManager, logger, configManager);
const { sessionManager, claudeCodeManager, logger, configManager, analyticsManager } = this.services;
return new ClaudePanelManager(claudeCodeManager, sessionManager, logger, configManager, analyticsManager);
}
protected getInitialPanelState(): Partial<ClaudePanelState> {

View File

@ -14,15 +14,15 @@ export let codexPanelManager: CodexPanelManager;
class CodexPanelHandler extends BaseAIPanelHandler {
protected createPanelManager(): CodexPanelManager {
const { sessionManager, logger, configManager } = this.services;
const { sessionManager, logger, configManager, analyticsManager } = this.services;
// Initialize singleton instances if needed
if (!codexManager) {
this.services.logger?.info('[codex-debug] Initializing CodexManager singleton');
codexManager = new CodexManager(sessionManager, logger, configManager);
}
return new CodexPanelManager(codexManager, sessionManager, logger, configManager);
return new CodexPanelManager(codexManager, sessionManager, logger, configManager, analyticsManager);
}
protected getInitialPanelState(): Partial<CodexPanelState> {
@ -62,11 +62,13 @@ class CodexPanelHandler extends BaseAIPanelHandler {
logger?.info(`[codex-debug] Panel ${panelId} has existing codexSessionId: ${existingCodexSessionId}`);
// Just register the panel - the frontend will handle resuming when the user sends a message
logger?.info(`[codex-debug] Registering panel ${panelId} with session ${sessionId} for potential resume`);
(this.panelManager as CodexPanelManager).registerPanel(panelId, sessionId);
// Pass false for isUserInitiated since this is runtime initialization, not panel creation
(this.panelManager as CodexPanelManager).registerPanel(panelId, sessionId, undefined, false);
} else {
// Register the panel with the manager
logger?.info(`[codex-debug] Registering new panel ${panelId} with session ${sessionId}`);
(this.panelManager as CodexPanelManager).registerPanel(panelId, sessionId);
// Pass false for isUserInitiated since this is runtime initialization, not panel creation
(this.panelManager as CodexPanelManager).registerPanel(panelId, sessionId, undefined, false);
// If a prompt is provided, start the Codex process
if (prompt) {

View File

@ -16,7 +16,7 @@ export function convertDbFolderToFolder(dbFolder: Folder) {
}
export function registerFolderHandlers(ipcMain: IpcMain, services: AppServices) {
const { databaseService, getMainWindow } = services;
const { databaseService, getMainWindow, analyticsManager } = services;
// Get all folders for a project
ipcMain.handle('folders:get-by-project', async (_, projectId: number) => {
@ -35,6 +35,15 @@ export function registerFolderHandlers(ipcMain: IpcMain, services: AppServices)
try {
const folder = databaseService.createFolder(name, projectId, parentFolderId);
const convertedFolder = convertDbFolderToFolder(folder);
// Track folder creation
if (analyticsManager) {
const nestingLevel = parentFolderId ? databaseService.getFolderDepth(folder.id) : 0;
analyticsManager.track('folder_created', {
nesting_level: nestingLevel
});
}
return { success: true, data: convertedFolder };
} catch (error: unknown) {
console.error('[IPC] Failed to create folder:', error);
@ -45,12 +54,17 @@ export function registerFolderHandlers(ipcMain: IpcMain, services: AppServices)
// Update a folder
ipcMain.handle('folders:update', async (_, folderId: string, updates: { name?: string; display_order?: number; parent_folder_id?: string | null }) => {
try {
// Track folder rename if name is being updated
if (analyticsManager && updates.name !== undefined) {
analyticsManager.track('folder_renamed', {});
}
databaseService.updateFolder(folderId, updates);
// Get the updated folder to emit the event
const updatedFolder = databaseService.getFolder(folderId);
if (updatedFolder) {
// Emit the folder:updated event to notify the frontend
const mainWindow = getMainWindow();
if (mainWindow && !mainWindow.isDestroyed()) {
@ -59,7 +73,7 @@ export function registerFolderHandlers(ipcMain: IpcMain, services: AppServices)
mainWindow.webContents.send('folder:updated', convertedFolder);
}
}
return { success: true };
} catch (error: unknown) {
console.error('[IPC] Failed to update folder:', error);
@ -70,7 +84,29 @@ export function registerFolderHandlers(ipcMain: IpcMain, services: AppServices)
// Delete a folder
ipcMain.handle('folders:delete', async (_, folderId: string) => {
try {
// Count sessions in the folder before deletion for analytics
if (analyticsManager) {
const folder = databaseService.getFolder(folderId);
if (folder) {
// Count sessions in this folder (including all nested folders)
const allSessions = databaseService.getAllSessions(folder.project_id);
const sessionsInFolder = allSessions.filter(s => s.folder_id === folderId);
analyticsManager.track('folder_deleted', {
contained_session_count: sessionsInFolder.length
});
}
}
databaseService.deleteFolder(folderId);
// Emit the folder:deleted event to notify the frontend
const mainWindow = getMainWindow();
if (mainWindow && !mainWindow.isDestroyed()) {
console.log(`[IPC] Emitting folder:deleted event for folder ${folderId}`);
mainWindow.webContents.send('folder:deleted', folderId);
}
return { success: true };
} catch (error: unknown) {
console.error('[IPC] Failed to delete folder:', error);

View File

@ -20,6 +20,8 @@ import { registerPanelHandlers } from './panels';
import { registerClaudePanelHandlers } from './claudePanel';
import { registerCodexPanelHandlers } from './codexPanel';
import { registerEditorPanelHandlers } from './editorPanel';
import { registerNimbalystHandlers } from './nimbalyst';
import { registerAnalyticsHandlers } from './analytics';
export function registerIpcHandlers(services: AppServices): void {
@ -43,4 +45,6 @@ export function registerIpcHandlers(services: AppServices): void {
registerClaudePanelHandlers(ipcMain, services);
registerCodexPanelHandlers(ipcMain, services);
registerEditorPanelHandlers(ipcMain, services);
registerNimbalystHandlers(ipcMain, services);
registerAnalyticsHandlers(ipcMain, services);
}

63
main/src/ipc/nimbalyst.ts Normal file
View File

@ -0,0 +1,63 @@
import { IpcMain } from 'electron';
import { spawn } from 'child_process';
import { existsSync } from 'fs';
import type { AppServices } from './types';
const NIMBALYST_PATH = '/Applications/Nimbalyst.app/Contents/MacOS/Nimbalyst';
export function registerNimbalystHandlers(ipcMain: IpcMain, services: AppServices): void {
// Check if Nimbalyst is installed
ipcMain.handle('nimbalyst:check-installed', () => {
try {
const isInstalled = existsSync(NIMBALYST_PATH);
return { success: true, data: isInstalled };
} catch (error) {
console.error('Error checking Nimbalyst installation:', error);
return { success: false, error: error instanceof Error ? error.message : 'Failed to check Nimbalyst installation' };
}
});
// Open a worktree in Nimbalyst
ipcMain.handle('nimbalyst:open-worktree', async (_event, worktreePath: string) => {
try {
// Check if Nimbalyst is installed
if (!existsSync(NIMBALYST_PATH)) {
return {
success: false,
error: 'Nimbalyst is not installed. Please download it from https://nimbalyst.com/'
};
}
// Check if worktree path exists
if (!existsSync(worktreePath)) {
return {
success: false,
error: `Worktree path does not exist: ${worktreePath}`
};
}
// Spawn Nimbalyst with the worktree path and git-worktree filter
const args = ['--workspace', worktreePath, '--filter', 'git-worktree'];
console.log('[Nimbalyst] Opening with command:', NIMBALYST_PATH, args.join(' '));
console.log('[Nimbalyst] Full args array:', JSON.stringify(args));
const child = spawn(NIMBALYST_PATH, args, {
detached: true,
stdio: 'ignore'
});
// Unref the child process so it can continue running independently
child.unref();
console.log('[Nimbalyst] Process spawned successfully for worktree:', worktreePath);
return { success: true };
} catch (error) {
console.error('Error opening worktree in Nimbalyst:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to open worktree in Nimbalyst'
};
}
});
}

View File

@ -1,8 +1,8 @@
import { IpcMain } from 'electron';
import { IpcMain, BrowserWindow } from 'electron';
import { panelManager } from '../services/panelManager';
import { terminalPanelManager } from '../services/terminalPanelManager';
import { databaseService } from '../services/database';
import { CreatePanelRequest, PanelEventType, ToolPanel } from '../../../shared/types/panels';
import { CreatePanelRequest, PanelEventType, ToolPanel, BaseAIPanelState } from '../../../shared/types/panels';
import type { AppServices } from './types';
export function registerPanelHandlers(ipcMain: IpcMain, services: AppServices) {
@ -94,6 +94,16 @@ export function registerPanelHandlers(ipcMain: IpcMain, services: AppServices) {
ipcMain.handle('panels:update', async (_, panelId: string, updates: Partial<ToolPanel>) => {
try {
// Track panel rename if title is being updated
if (updates.title) {
const panel = panelManager.getPanel(panelId);
if (panel && panel.title !== updates.title && services.analyticsManager) {
services.analyticsManager.track('panel_renamed', {
panel_type: panel.type
});
}
}
const result = await panelManager.updatePanel(panelId, updates);
return { success: true, data: result };
} catch (error) {
@ -184,6 +194,56 @@ export function registerPanelHandlers(ipcMain: IpcMain, services: AppServices) {
ipcMain.handle('panels:emitEvent', async (_, panelId: string, eventType: PanelEventType, data: unknown) => {
return panelManager.emitPanelEvent(panelId, eventType, data);
});
// Clear unviewed content flag for AI panels
ipcMain.handle('panels:clearUnviewedContent', async (event, panelId: string) => {
try {
const panel = panelManager.getPanel(panelId);
if (!panel) {
return { success: false, error: 'Panel not found' };
}
// Only applicable to AI panels
if (panel.type !== 'claude' && panel.type !== 'codex') {
return { success: true };
}
const customState = (panel.state.customState as BaseAIPanelState | undefined) ?? {};
// Clear unviewed content flag and reset status if it was completed_unviewed
const nextCustomState: BaseAIPanelState = {
...customState,
hasUnviewedContent: false,
panelStatus: customState.panelStatus === 'completed_unviewed' ? 'stopped' : customState.panelStatus,
lastActivityTime: new Date().toISOString()
};
const nextPanelState = {
...panel.state,
customState: nextCustomState
};
await panelManager.updatePanel(panelId, { state: nextPanelState });
// Notify frontend of the update
const webContents = event.sender;
if (webContents && !webContents.isDestroyed()) {
try {
webContents.send('panel:updated', {
...panel,
state: nextPanelState
});
} catch (ipcError) {
console.error(`[Panels IPC] Failed to send panel:updated event for panel ${panelId}:`, ipcError);
}
}
return { success: true };
} catch (error) {
console.error('[IPC] Failed to clear unviewed content:', error);
return { success: false, error: (error as Error).message };
}
});
// Panel-specific terminal handlers (called via panels: namespace from frontend)
ipcMain.handle('panels:resize-terminal', async (_, panelId: string, cols: number, rows: number) => {

View File

@ -44,7 +44,7 @@ async function stopProjectScriptInternal(projectId?: number): Promise<{ success:
}
export function registerProjectHandlers(ipcMain: IpcMain, services: AppServices): void {
const { databaseService, sessionManager, worktreeManager } = services;
const { databaseService, sessionManager, worktreeManager, analyticsManager } = services;
ipcMain.handle('projects:get-all', async () => {
try {
@ -151,6 +151,16 @@ export function registerProjectHandlers(ipcMain: IpcMain, services: AppServices)
}
console.log('[Main] Project created successfully:', project);
// Track project creation
if (analyticsManager && project) {
const allProjects = databaseService.getAllProjects();
analyticsManager.track('project_created', {
was_auto_initialized: !isGitRepo,
project_count: allProjects.length
});
}
return { success: true, data: project };
} catch (error) {
console.error('[Main] Failed to create project:', error);
@ -193,6 +203,16 @@ export function registerProjectHandlers(ipcMain: IpcMain, services: AppServices)
if (project) {
sessionManager.setActiveProject(project);
await worktreeManager.initializeProject(project.path);
// Track project switch
if (analyticsManager) {
const projectIdNum = parseInt(projectId);
const projectSessions = databaseService.getAllSessions(projectIdNum);
const hasActiveSessions = projectSessions.some(s => s.status === 'running' || s.status === 'pending');
analyticsManager.track('project_switched', {
has_active_sessions: hasActiveSessions
});
}
}
return { success: true };
} catch (error) {
@ -233,6 +253,27 @@ export function registerProjectHandlers(ipcMain: IpcMain, services: AppServices)
sessionManager.emit('project:updated', project);
}
// Track project settings update
if (analyticsManager && project) {
// Determine which category of setting was updated
let settingCategory = 'other';
if (updates.system_prompt !== undefined) {
settingCategory = 'system_prompt';
} else if (updates.run_script !== undefined || updates.build_script !== undefined) {
settingCategory = 'scripts';
} else if (updates.commit_mode !== undefined || updates.commit_structured_prompt_template !== undefined || updates.commit_checkpoint_prefix !== undefined) {
settingCategory = 'commit';
} else if (updates.open_ide_command !== undefined) {
settingCategory = 'ide';
} else if (updates.name !== undefined) {
settingCategory = 'name';
}
analyticsManager.track('project_settings_updated', {
setting_category: settingCategory
});
}
return { success: true, data: project };
} catch (error) {
console.error('Failed to update project:', error);
@ -258,12 +299,14 @@ export function registerProjectHandlers(ipcMain: IpcMain, services: AppServices)
console.log(`[Main] Deleting project ${project.name} with ${allProjectSessions.length} total sessions`);
// Check if any session from this project has a running script
const currentRunningSessionId = sessionManager.getCurrentRunningSessionId();
if (currentRunningSessionId) {
const runningSession = projectSessions.find(s => s.id === currentRunningSessionId);
if (runningSession) {
console.log(`[Main] Stopping running script for session ${currentRunningSessionId} before deleting project`);
sessionManager.stopRunningScript();
const runningScript = scriptExecutionTracker.getRunningScript();
if (runningScript) {
const runningSession = projectSessions.find(s => s.id === runningScript.id);
if (runningSession && runningScript.type === 'session') {
console.log(`[Main] Stopping running script for session ${runningScript.id} before deleting project`);
await sessionManager.stopRunningScript();
// Ensure tracker is updated even if sessionManager's internal update fails
scriptExecutionTracker.stop('session', runningScript.id);
}
}
@ -285,7 +328,9 @@ export function registerProjectHandlers(ipcMain: IpcMain, services: AppServices)
try {
console.log(`[Main] Removing worktree '${session.worktree_name}' for session ${session.id}`);
await worktreeManager.removeWorktree(project.path, session.worktree_name, project.worktree_folder || undefined);
// Pass session creation date for analytics tracking
const sessionCreatedAt = session.created_at ? new Date(session.created_at) : undefined;
await worktreeManager.removeWorktree(project.path, session.worktree_name, project.worktree_folder || undefined, sessionCreatedAt);
worktreeCleanupCount++;
} catch (error) {
// Log error but continue with other worktrees
@ -294,7 +339,16 @@ export function registerProjectHandlers(ipcMain: IpcMain, services: AppServices)
}
console.log(`[Main] Cleaned up ${worktreeCleanupCount} worktrees for project ${project.name}`);
// Track project deletion before actually deleting
if (analyticsManager) {
const projectAge = Math.floor((Date.now() - new Date(project.created_at).getTime()) / (1000 * 60 * 60 * 24));
analyticsManager.track('project_deleted', {
session_count: projectSessions.length,
project_age_days: projectAge
});
}
// Now safe to delete the project
const success = databaseService.deleteProject(projectIdNum);
return { success: true, data: success };

View File

@ -43,15 +43,27 @@ export function registerScriptHandlers(ipcMain: IpcMain, { sessionManager }: App
// Check if there's already a running script (any type) and stop it
const runningScript = scriptExecutionTracker.getRunningScript();
if (runningScript) {
console.log(`[Main] Stopping currently running ${runningScript.type} script for ${runningScript.type}:${runningScript.id}`);
console.log(`[Script] Stopping currently running ${runningScript.type} script for ${runningScript.type}:${runningScript.id} before starting new script for session ${sessionId}`);
// Mark the old script as closing
scriptExecutionTracker.markClosing(runningScript.type, runningScript.id);
// Stop the script based on its type
if (runningScript.type === 'session') {
// Stop through session manager (will update tracker)
await sessionManager.stopRunningScript();
console.log('[Script] Stopping session script via logs panel');
// Find and stop the logs panel for this session
const panels = await panelManager.getPanelsForSession(runningScript.id as string);
const logsPanel = panels?.find((p: { type: string }) => p.type === 'logs');
if (logsPanel) {
console.log('[Script] Found logs panel, stopping:', logsPanel.id);
await logsManager.stopScript(logsPanel.id);
} else {
console.log('[Script] No logs panel found, calling sessionManager.stopRunningScript');
await sessionManager.stopRunningScript();
}
// Ensure tracker is updated
scriptExecutionTracker.stop('session', runningScript.id);
console.log('[Script] Session script stopped and tracker updated');
} else if (runningScript.type === 'project') {
// Stop project script through logs panel
if (runningScript.sessionId) {
@ -66,10 +78,14 @@ export function registerScriptHandlers(ipcMain: IpcMain, { sessionManager }: App
}
}
console.log(`[Script] Starting new script for session ${sessionId}`);
// Use logs panel instead of old script running mechanism
const commandString = commands.join(' && ');
await logsManager.runScript(sessionId, commandString, session.worktreePath);
console.log(`[Script] Script started successfully for session ${sessionId}`);
// Track this session script as running
scriptExecutionTracker.start('session', sessionId);
@ -95,7 +111,35 @@ export function registerScriptHandlers(ipcMain: IpcMain, { sessionManager }: App
await logsManager.stopScript(logsPanel.id);
}
} else {
// Get running script info before stopping
const runningScript = scriptExecutionTracker.getRunningScript();
console.log('[Script] Stopping script (no sessionId provided), running script:', runningScript);
// If it's a session script, stop the logs panel process (critical!)
if (runningScript && runningScript.type === 'session') {
console.log('[Script] Finding logs panel for session:', runningScript.id);
const panels = await panelManager.getPanelsForSession(runningScript.id as string);
const logsPanel = panels?.find((p: { type: string }) => p.type === 'logs');
if (logsPanel) {
console.log('[Script] Stopping logs panel:', logsPanel.id);
await logsManager.stopScript(logsPanel.id);
console.log('[Script] Logs panel stopped successfully');
} else {
console.log('[Script] No logs panel found for session');
}
}
// Also call old mechanism for backward compatibility
await sessionManager.stopRunningScript();
// Ensure tracker is updated even if sessionManager's internal update fails
if (runningScript && runningScript.type === 'session') {
console.log('[Script] Updating tracker to stopped state for session:', runningScript.id);
scriptExecutionTracker.stop('session', runningScript.id);
}
console.log('[Script] Stop script completed');
}
return { success: true };
} catch (error) {

View File

@ -5,6 +5,7 @@ import { existsSync } from 'fs';
import type { AppServices } from './types';
import type { CreateSessionRequest } from '../types/session';
import { getCrystalSubdirectory } from '../utils/crystalDirectory';
import { isSafeSessionId, getSafeImageExtension } from '../utils/artifactPathSafety';
import { convertDbFolderToFolder } from './folders';
import { panelManager } from '../services/panelManager';
import {
@ -255,9 +256,11 @@ export function registerSessionHandlers(ipcMain: IpcMain, services: AppServices)
if (archiveProgressManager) {
archiveProgressManager.updateTaskStatus(sessionId, 'removing-worktree');
}
await worktreeManager.removeWorktree(project.path, dbSession.worktree_name, project.worktree_folder || undefined);
// Pass session creation date for analytics tracking
const sessionCreatedAt = dbSession.created_at ? new Date(dbSession.created_at) : undefined;
await worktreeManager.removeWorktree(project.path, dbSession.worktree_name, project.worktree_folder || undefined, sessionCreatedAt);
cleanupMessage += `\x1b[32m✓ Worktree removed successfully\x1b[0m\r\n`;
} catch (worktreeError) {
// Log the error but don't fail
@ -1610,10 +1613,18 @@ export function registerSessionHandlers(ipcMain: IpcMain, services: AppServices)
// Save images for a session
ipcMain.handle('sessions:save-images', async (_event, sessionId: string, images: Array<{ name: string; dataUrl: string; type: string }>) => {
try {
// sessionId is used to build a file-system path below, so it must be
// validated before anything else: a crafted value like
// 'pending_../../../../etc' would otherwise let the artifacts
// directory escape outside CRYSTAL_DIR.
if (!isSafeSessionId(sessionId)) {
throw new Error('Invalid session ID');
}
// For pending sessions (those created before the actual session), we still need to save the files
// Check if this is a pending session ID (starts with 'pending_')
const isPendingSession = sessionId.startsWith('pending_');
if (!isPendingSession) {
// For real sessions, verify it exists
const session = await sessionManager.getSession(sessionId);
@ -1634,7 +1645,10 @@ export function registerSessionHandlers(ipcMain: IpcMain, services: AppServices)
// Generate unique filename
const timestamp = Date.now();
const randomStr = Math.random().toString(36).substring(2, 9);
const extension = image.type.split('/')[1] || 'png';
// Derived from an allow-list, not from the raw `image.type` string,
// so a crafted MIME type cannot smuggle path separators or `..`
// traversal segments into the filename.
const extension = getSafeImageExtension(image.type);
const filename = `${timestamp}_${randomStr}.${extension}`;
const filePath = path.join(imagesDir, filename);
@ -1659,10 +1673,16 @@ export function registerSessionHandlers(ipcMain: IpcMain, services: AppServices)
// Save large text for a session
ipcMain.handle('sessions:save-large-text', async (_event, sessionId: string, text: string) => {
try {
// See the matching check in sessions:save-images: sessionId feeds
// directly into a file-system path and must be validated first.
if (!isSafeSessionId(sessionId)) {
throw new Error('Invalid session ID');
}
// For pending sessions (those created before the actual session), we still need to save the files
// Check if this is a pending session ID (starts with 'pending_')
const isPendingSession = sessionId.startsWith('pending_');
if (!isPendingSession) {
// For real sessions, verify it exists
const session = await sessionManager.getSession(sessionId);

View File

@ -17,6 +17,7 @@ import type { CliManagerFactory } from '../services/cliManagerFactory';
import type { AbstractCliManager } from '../services/panels/cli/AbstractCliManager';
import type { Logger } from '../utils/logger';
import type { ArchiveProgressManager } from '../services/archiveProgressManager';
import type { AnalyticsManager } from '../services/analyticsManager';
export interface AppServices {
app: App;
@ -38,4 +39,5 @@ export interface AppServices {
getMainWindow: () => BrowserWindow | null;
logger?: Logger;
archiveProgressManager?: ArchiveProgressManager;
analyticsManager?: AnalyticsManager;
}

View File

@ -599,6 +599,22 @@ contextBridge.exposeInMainWorld('electronAPI', {
debug: {
getTableStructure: (tableName: 'folders' | 'sessions'): Promise<IPCResponse> => ipcRenderer.invoke('debug:get-table-structure', tableName),
},
// Nimbalyst integration
nimbalyst: {
checkInstalled: (): Promise<IPCResponse> => ipcRenderer.invoke('nimbalyst:check-installed'),
openWorktree: (worktreePath: string): Promise<IPCResponse> => ipcRenderer.invoke('nimbalyst:open-worktree', worktreePath),
},
// Analytics tracking
analytics: {
trackUIEvent: (eventData: {
event: 'view_switched' | 'help_dialog_opened' | 'settings_opened' | 'settings_saved' | 'sidebar_toggled' | 'search_used';
properties: Record<string, string | number | boolean | string[]>;
}): Promise<IPCResponse> => ipcRenderer.invoke('analytics:track-ui-event', eventData),
categorizeResultCount: (count: number): Promise<IPCResponse<string>> => ipcRenderer.invoke('analytics:categorize-result-count', count),
hashSessionId: (sessionId: string): Promise<IPCResponse<string>> => ipcRenderer.invoke('analytics:hash-session-id', sessionId),
},
});
// Expose electron event listeners and utilities for permission requests

View File

@ -0,0 +1,280 @@
import { PostHog } from 'posthog-node';
import { EventEmitter } from 'events';
import type { ConfigManager } from './configManager';
import { app } from 'electron';
import * as crypto from 'crypto';
import * as os from 'os'; // Still needed for platform info in track() method
export interface AnalyticsEvent {
eventName: string;
properties?: Record<string, string | number | boolean | string[] | undefined>;
}
export class AnalyticsManager extends EventEmitter {
private client: PostHog | null = null;
private configManager: ConfigManager;
private distinctId: string;
private isInitialized = false;
private minimalClient: PostHog | null = null; // Separate client for minimal tracking when opted out
constructor(configManager: ConfigManager) {
super();
this.configManager = configManager;
this.distinctId = this.generateDistinctId();
}
/**
* Generate a stable, anonymous distinct ID for this installation
* Uses a random UUID stored in config for privacy
*/
private generateDistinctId(): string {
// Check if we already have a distinct ID stored
const existingId = this.configManager.getAnalyticsDistinctId();
if (existingId) {
return existingId;
}
// Generate new random UUID for this installation
const uuid = crypto.randomUUID();
const distinctId = `crystal_${uuid}`;
// Store it for future use (async, but don't wait)
this.configManager.setAnalyticsDistinctId(distinctId).catch(err => {
console.error('[Analytics] Failed to save distinct ID:', err);
});
return distinctId;
}
/**
* Initialize PostHog client
*/
async initialize(): Promise<void> {
const settings = this.configManager.getAnalyticsSettings();
// Always initialize minimal client for basic tracking (even when opted out)
if (settings.posthogApiKey) {
try {
this.minimalClient = new PostHog(settings.posthogApiKey, {
host: settings.posthogHost || 'https://app.posthog.com',
flushAt: 1, // Flush immediately for minimal events
flushInterval: 1000,
});
console.log('[Analytics] Minimal PostHog client initialized');
} catch (error) {
console.error('[Analytics] Failed to initialize minimal PostHog client:', error);
}
}
// Don't initialize full client if analytics is disabled
if (!settings.enabled || !settings.posthogApiKey) {
console.log('[Analytics] Full analytics disabled or no API key configured');
this.isInitialized = false;
return;
}
try {
this.client = new PostHog(settings.posthogApiKey, {
host: settings.posthogHost || 'https://app.posthog.com',
flushAt: 20, // Send batch after 20 events
flushInterval: 10000, // Send batch every 10 seconds
});
this.isInitialized = true;
console.log('[Analytics] PostHog initialized successfully');
} catch (error) {
console.error('[Analytics] Failed to initialize PostHog:', error);
this.isInitialized = false;
}
}
/**
* Track an event
*/
track(eventName: string, properties?: Record<string, string | number | boolean | string[] | undefined>): void {
// Skip if analytics is disabled
if (!this.isInitialized || !this.client || !this.configManager.isAnalyticsEnabled()) {
return;
}
try {
// Add common properties
const enhancedProperties = {
...properties,
app_version: app.getVersion(),
platform: os.platform(),
electron_version: process.versions.electron,
};
// Remove undefined values
const cleanedProperties = Object.fromEntries(
Object.entries(enhancedProperties).filter(([_, v]) => v !== undefined)
);
this.client.capture({
distinctId: this.distinctId,
event: eventName,
properties: cleanedProperties,
});
if (this.configManager.isVerbose()) {
console.log(`[Analytics] Tracked event: ${eventName}`, cleanedProperties);
}
} catch (error) {
console.error(`[Analytics] Failed to track event ${eventName}:`, error);
}
}
/**
* Track a minimal event even when analytics is disabled
* Used for: app_opened when opted out, analytics_opted_out event
*/
trackMinimalEvent(eventName: string, properties?: Record<string, string | number | boolean | string[] | undefined>): void {
if (!this.minimalClient) {
console.log('[Analytics] Minimal client not available, skipping minimal event');
return;
}
try {
// Only include very basic properties for privacy
const minimalProperties = {
...properties,
app_version: app.getVersion(),
platform: os.platform(),
analytics_enabled: this.configManager.isAnalyticsEnabled(),
};
// Remove undefined values
const cleanedProperties = Object.fromEntries(
Object.entries(minimalProperties).filter(([_, v]) => v !== undefined)
);
this.minimalClient.capture({
distinctId: this.distinctId,
event: eventName,
properties: cleanedProperties,
});
console.log(`[Analytics] Tracked minimal event: ${eventName}`);
} catch (error) {
console.error(`[Analytics] Failed to track minimal event ${eventName}:`, error);
}
}
/**
* Identify the user (with anonymous ID)
*/
identify(properties?: Record<string, string | number | boolean | undefined>): void {
if (!this.isInitialized || !this.client || !this.configManager.isAnalyticsEnabled()) {
return;
}
try {
this.client.identify({
distinctId: this.distinctId,
properties: {
...properties,
app_version: app.getVersion(),
platform: os.platform(),
},
});
} catch (error) {
console.error('[Analytics] Failed to identify user:', error);
}
}
/**
* Flush any pending events
*/
async flush(): Promise<void> {
if (!this.client) {
return;
}
try {
await this.client.flush();
console.log('[Analytics] Events flushed');
} catch (error) {
console.error('[Analytics] Failed to flush events:', error);
}
}
/**
* Shutdown the client
*/
async shutdown(): Promise<void> {
const shutdownPromises: Promise<void>[] = [];
if (this.client) {
shutdownPromises.push(
this.client.shutdown().then(() => {
console.log('[Analytics] PostHog client shut down');
}).catch((error) => {
console.error('[Analytics] Failed to shut down PostHog client:', error);
})
);
}
if (this.minimalClient) {
shutdownPromises.push(
this.minimalClient.shutdown().then(() => {
console.log('[Analytics] Minimal PostHog client shut down');
}).catch((error) => {
console.error('[Analytics] Failed to shut down minimal PostHog client:', error);
})
);
}
await Promise.all(shutdownPromises);
}
/**
* Helper to hash session IDs for privacy
*/
hashSessionId(sessionId: string): string {
return crypto.createHash('sha256').update(sessionId).digest('hex').substring(0, 16);
}
/**
* Categorize numeric values for privacy
*/
categorizeNumber(value: number, thresholds: number[]): string {
for (let i = 0; i < thresholds.length; i++) {
if (value <= thresholds[i]) {
return i === 0 ? `0-${thresholds[i]}` : `${thresholds[i - 1] + 1}-${thresholds[i]}`;
}
}
return `${thresholds[thresholds.length - 1] + 1}+`;
}
/**
* Categorize duration for privacy
*/
categorizeDuration(seconds: number): string {
if (seconds < 10) return '0-10s';
if (seconds < 30) return '10-30s';
if (seconds < 60) return '30-60s';
if (seconds < 300) return '1-5m';
if (seconds < 600) return '5-10m';
if (seconds < 1800) return '10-30m';
if (seconds < 3600) return '30-60m';
return '60m+';
}
/**
* Categorize prompt length for privacy
*/
categorizePromptLength(length: number): string {
if (length < 50) return 'short';
if (length < 200) return 'medium';
if (length < 500) return 'long';
return 'very_long';
}
/**
* Check if analytics is enabled
*/
isEnabled(): boolean {
return this.isInitialized && this.configManager.isAnalyticsEnabled();
}
}

View File

@ -16,15 +16,18 @@ import {
export interface CliManagerFactoryConfig {
/** Session manager instance */
sessionManager: unknown;
/** Logger instance */
logger?: Logger;
/** Configuration manager instance */
configManager?: ConfigManager;
/** Additional tool-specific options */
additionalOptions?: Record<string, unknown>;
/** Skip tool availability validation (useful for startup) */
skipValidation?: boolean;
}
/**
@ -60,16 +63,17 @@ export class CliManagerFactory {
* Create a CLI manager for the specified tool
*/
public async createManager(
toolId: string,
toolId: string,
config: CliManagerFactoryConfig
): Promise<AbstractCliManager> {
try {
this.validateConfig(config);
const manager = await this.registry.createManager(
toolId,
config.sessionManager as SessionManager,
config.additionalOptions
config.additionalOptions,
config.skipValidation
);
this.logger?.info(`[CliManagerFactory] Created ${toolId} manager successfully`);

View File

@ -303,7 +303,8 @@ export class CliToolRegistry extends EventEmitter {
public async createManager(
toolId: string,
sessionManager: SessionManager,
additionalOptions?: Record<string, unknown>
additionalOptions?: Record<string, unknown>,
skipValidation = false
): Promise<AbstractCliManager> {
const tool = this.tools.get(toolId);
if (!tool) {
@ -317,10 +318,12 @@ export class CliToolRegistry extends EventEmitter {
return existingManager;
}
// Validate tool availability
const availability = await this.checkToolAvailability(toolId);
if (!availability.available) {
throw new Error(`CLI tool '${toolId}' is not available: ${availability.error}`);
// Validate tool availability (unless skipValidation is true)
if (!skipValidation) {
const availability = await this.checkToolAvailability(toolId);
if (!availability.available) {
throw new Error(`CLI tool '${toolId}' is not available: ${availability.error}`);
}
}
// Create new manager instance

View File

@ -56,6 +56,11 @@ export class ConfigManager extends EventEmitter {
mode: 'checkpoint',
checkpointPrefix: 'checkpoint: '
}
},
analytics: {
enabled: false, // Opt-in: disabled by default until user consents
posthogApiKey: 'phc_uwOqT2KUa4C9Qx5WbEPwQSN9mUCoSGFg1aY0b670ft5',
posthogHost: 'https://us.i.posthog.com'
}
};
}
@ -95,6 +100,10 @@ export class ConfigManager extends EventEmitter {
...this.config.sessionCreationPreferences?.commitModeSettings,
...loadedConfig.sessionCreationPreferences?.commitModeSettings
}
},
analytics: {
...this.config.analytics,
...loadedConfig.analytics
}
};
} catch (error) {
@ -189,4 +198,32 @@ export class ConfigManager extends EventEmitter {
}
};
}
getAnalyticsSettings() {
return this.config.analytics || {
enabled: false, // Opt-in: disabled by default until user consents
posthogApiKey: 'phc_uwOqT2KUa4C9Qx5WbEPwQSN9mUCoSGFg1aY0b670ft5',
posthogHost: 'https://us.i.posthog.com'
};
}
isAnalyticsEnabled(): boolean {
return this.config.analytics?.enabled ?? false; // Opt-in: default to false
}
getAnalyticsDistinctId(): string | undefined {
return this.config.analytics?.distinctId;
}
async setAnalyticsDistinctId(distinctId: string): Promise<void> {
if (!this.config.analytics) {
this.config.analytics = {
enabled: true,
posthogApiKey: 'phc_uwOqT2KUa4C9Qx5WbEPwQSN9mUCoSGFg1aY0b670ft5',
posthogHost: 'https://us.i.posthog.com'
};
}
this.config.analytics.distinctId = distinctId;
await this.saveConfig();
}
}

View File

@ -1,5 +1,6 @@
import { execSync } from '../utils/commandExecutor';
import type { Logger } from '../utils/logger';
import type { AnalyticsManager } from './analyticsManager';
export interface GitDiffStats {
additions: number;
@ -24,7 +25,10 @@ export interface GitCommit {
}
export class GitDiffManager {
constructor(private logger?: Logger) {}
constructor(
private logger?: Logger,
private analyticsManager?: AnalyticsManager
) {}
/**
* Capture git diff for a worktree directory
@ -100,8 +104,10 @@ export class GitDiffManager {
try {
// Get commit log with stats, excluding commits that are in main branch
// This shows only commits unique to the current branch
// Using --cherry-pick to also exclude commits that have equivalent patches on main
// (e.g., commits that were cherry-picked or rebased to main)
const logFormat = '%H|%s|%ai|%an';
const gitCommand = `git log --format="${logFormat}" --numstat -n ${limit} HEAD --not ${mainBranch} --`;
const gitCommand = `git log --format="${logFormat}" --numstat -n ${limit} --cherry-pick --left-only HEAD...${mainBranch} --`;
console.log(`[GitDiffManager] Getting commit history for worktree: ${worktreePath}`);
console.log(`[GitDiffManager] Main branch: ${mainBranch}`);
@ -319,7 +325,20 @@ export class GitDiffManager {
}
async getGitDiff(worktreePath: string): Promise<GitDiffResult> {
return this.captureWorkingDirectoryDiff(worktreePath);
const result = await this.captureWorkingDirectoryDiff(worktreePath);
// Track git diff viewed
if (this.analyticsManager) {
const fileCountCategory = this.analyticsManager.categorizeNumber(result.stats.filesChanged, [1, 5, 10, 25, 50]);
const hasUncommitted = this.hasChanges(worktreePath);
this.analyticsManager.track('git_diff_viewed', {
file_count_category: fileCountCategory,
has_uncommitted: hasUncommitted
});
}
return result;
}
async getCombinedDiff(worktreePath: string, mainBranch: string): Promise<GitDiffResult> {

View File

@ -4,10 +4,16 @@ import { databaseService } from './database';
import { panelEventBus } from './panelEventBus';
import { mainWindow } from '../index';
import { withLock } from '../utils/mutex';
import type { AnalyticsManager } from './analyticsManager';
export class PanelManager {
private panels = new Map<string, ToolPanel>();
private analyticsManager: AnalyticsManager | null = null;
setAnalyticsManager(analyticsManager: AnalyticsManager): void {
this.analyticsManager = analyticsManager;
}
constructor() {
// Load panels from database on startup (but don't initialize processes)
this.loadPanelsFromDatabase();
@ -108,9 +114,18 @@ export class PanelManager {
if (mainWindow) {
mainWindow.webContents.send('panel:created', panel);
}
// Track terminal panel creation analytics (only for new panels, not restoration)
if (request.type === 'terminal' && this.analyticsManager) {
const terminalCount = this.getPanelsBySessionAndType(request.sessionId, 'terminal').length;
this.analyticsManager.track('terminal_panel_created', {
session_id_hash: this.analyticsManager.hashSessionId(request.sessionId),
terminal_count: terminalCount
});
}
console.log(`[PanelManager] Created panel ${panelId} of type ${request.type} for session ${request.sessionId}`);
return panel;
});
}
@ -137,16 +152,21 @@ export class PanelManager {
console.warn(`[PanelManager] Panel ${panelId} not found for deletion`);
return;
}
// Check if panel is permanent
if (panel.metadata.permanent) {
console.warn(`[PanelManager] Cannot delete permanent panel ${panelId}`);
return;
}
// Calculate panel lifetime for analytics
const createdAt = new Date(panel.metadata.createdAt);
const now = new Date();
const lifetimeSeconds = Math.floor((now.getTime() - createdAt.getTime()) / 1000);
// Clean up event subscriptions
panelEventBus.unsubscribePanel(panelId);
// If this was the active panel, activate another one
const activePanelId = databaseService.getActivePanel(panel.sessionId)?.id;
if (activePanelId === panelId) {
@ -157,18 +177,26 @@ export class PanelManager {
await this.setActivePanel(panel.sessionId, null);
}
}
// Remove from database
databaseService.deletePanel(panelId);
// Remove from cache
this.panels.delete(panelId);
// Emit IPC event to notify frontend
if (mainWindow) {
mainWindow.webContents.send('panel:deleted', { panelId, sessionId: panel.sessionId });
}
// Track panel closure
if (this.analyticsManager) {
this.analyticsManager.track('panel_closed', {
panel_type: panel.type,
panel_lifetime_seconds: lifetimeSeconds
});
}
console.log(`[PanelManager] Deleted panel ${panelId}`);
});
}
@ -204,9 +232,17 @@ export class PanelManager {
async setActivePanel(sessionId: string, panelId: string | null): Promise<void> {
return await withLock(`panel-active-${sessionId}`, async () => {
// Get current active panel for analytics
const currentActivePanel = databaseService.getActivePanel(sessionId);
const fromPanelType = currentActivePanel?.type;
// Update database
databaseService.setActivePanel(sessionId, panelId);
// Get new active panel for analytics
const newActivePanel = panelId ? this.getPanel(panelId) : null;
const toPanelType = newActivePanel?.type;
// Update panel states
const panels = this.getPanelsForSession(sessionId);
panels.forEach(panel => {
@ -222,17 +258,25 @@ export class PanelManager {
state: panel.state,
metadata: panel.metadata
});
// Update in cache
this.panels.set(panel.id, panel);
}
});
// Emit IPC event to notify frontend
if (mainWindow) {
mainWindow.webContents.send('panel:activeChanged', { sessionId, panelId });
}
// Track panel switching (only if both from and to panels exist)
if (this.analyticsManager && fromPanelType && toPanelType && fromPanelType !== toPanelType) {
this.analyticsManager.track('panel_switched', {
from_panel_type: fromPanelType,
to_panel_type: toPanelType
});
}
console.log(`[PanelManager] Set active panel for session ${sessionId} to ${panelId}`);
});
}

View File

@ -1,6 +1,7 @@
import { AbstractCliManager } from '../cli/AbstractCliManager';
import type { Logger } from '../../../utils/logger';
import type { ConfigManager } from '../../configManager';
import type { AnalyticsManager } from '../../analyticsManager';
import type { ConversationMessage } from '../../../database/models';
import { PanelEvent, PanelEventType } from '../../../../../shared/types/panels';
import { AIPanelConfig, StartPanelConfig, ContinuePanelConfig, AIPanelState } from '../../../../../shared/types/aiPanelConfig';
@ -23,14 +24,17 @@ export interface PanelMapping {
export abstract class AbstractAIPanelManager {
protected panelMappings = new Map<string, PanelMapping>();
protected resumeIdToPanel = new Map<string, string>();
protected promptStartTimes = new Map<string, number>(); // Track when prompts were submitted
constructor(
protected cliManager: AbstractCliManager,
protected sessionManager: import('../../sessionManager').SessionManager,
protected logger?: Logger,
protected configManager?: ConfigManager
protected configManager?: ConfigManager,
protected analyticsManager?: AnalyticsManager
) {
this.setupEventHandlers();
this.setupAnalyticsEventHandlers();
}
/**
@ -129,6 +133,30 @@ export abstract class AbstractAIPanelManager {
});
}
/**
* Setup analytics event handlers to track AI responses
*/
protected setupAnalyticsEventHandlers(): void {
if (!this.analyticsManager) return;
// Listen for panel response events to track AI responses
this.sessionManager.on('panel-response-added', (data: { panelId: string; content: string }) => {
const { panelId, content } = data;
// Only track if this panel is registered with this manager
if (!this.panelMappings.has(panelId)) return;
// Check if the content contains tool calls (simple heuristic)
// This is a simplified check - could be enhanced based on actual message structure
const hadToolCalls = content.includes('tool_use') ||
content.includes('tool_call') ||
content.includes('"type":"tool_use"') ||
content.includes('"name":"');
this.trackAIResponse(panelId, hadToolCalls);
});
}
/**
* Subscribe panel to git events for the same session only
*/
@ -190,23 +218,55 @@ export abstract class AbstractAIPanelManager {
/**
* Register a panel with optional initial state
* @param panelId - The panel ID to register
* @param sessionId - The session ID this panel belongs to
* @param initialState - Optional initial state for the panel
* @param isUserInitiated - If true, track analytics event (default: true). Set to false during app startup/restoration.
*/
registerPanel(panelId: string, sessionId: string, initialState?: AIPanelState): void {
registerPanel(panelId: string, sessionId: string, initialState?: AIPanelState, isUserInitiated = true): void {
const resumeId = initialState?.resumeId || this.generateResumeId(panelId);
const mapping: PanelMapping = {
panelId,
sessionId,
resumeId,
config: initialState?.config
};
this.panelMappings.set(panelId, mapping);
this.resumeIdToPanel.set(resumeId, panelId);
this.subscribeToGitEvents(panelId, sessionId);
this.logger?.info(`[${this.getAgentName()}PanelManager] Registered panel ${panelId} for session ${sessionId}`);
// Track panel creation event only for user-initiated panel creation
if (isUserInitiated) {
this.trackPanelCreation(sessionId);
}
}
/**
* Track panel creation analytics event
*/
protected trackPanelCreation(sessionId: string): void {
if (!this.analyticsManager) return;
const agentName = this.getAgentName().toLowerCase();
const eventName = `${agentName}_panel_created`;
// Count how many panels exist for this session
let panelCount = 0;
for (const mapping of this.panelMappings.values()) {
if (mapping.sessionId === sessionId) {
panelCount++;
}
}
this.analyticsManager.track(eventName, {
session_id_hash: this.analyticsManager.hashSessionId(sessionId),
panel_count: panelCount
});
}
/**
@ -229,7 +289,7 @@ export abstract class AbstractAIPanelManager {
*/
async startPanel(config: StartPanelConfig): Promise<void> {
const { panelId, sessionId, worktreePath, prompt } = config;
const mapping = this.panelMappings.get(panelId);
if (!mapping) {
throw new Error(`Panel ${panelId} not registered`);
@ -237,13 +297,16 @@ export abstract class AbstractAIPanelManager {
// Store config for future reference
mapping.config = config;
const resolvedSessionId = sessionId || mapping.sessionId;
this.logger?.info(`[${this.getAgentName()}PanelManager] Starting panel ${panelId} (session: ${resolvedSessionId})`);
// Track prompt submission
this.trackPromptSubmission(panelId, prompt);
// Extract agent-specific parameters using the subclass implementation
const agentParams = this.extractAgentConfig(config);
return this.cliManager.startPanel(
panelId,
resolvedSessionId,
@ -258,7 +321,7 @@ export abstract class AbstractAIPanelManager {
*/
async continuePanel(config: ContinuePanelConfig): Promise<void> {
const { panelId, worktreePath, prompt, conversationHistory } = config;
const mapping = this.panelMappings.get(panelId);
if (!mapping) {
throw new Error(`Panel ${panelId} not registered`);
@ -266,21 +329,25 @@ export abstract class AbstractAIPanelManager {
// Merge with stored config
mapping.config = { ...mapping.config, ...config };
this.logger?.info(`[${this.getAgentName()}PanelManager] Continuing panel ${panelId} (session: ${mapping.sessionId})`);
// Extract agent-specific parameters
const agentParams = this.extractAgentConfig(config);
// Convert conversation history to database format
const dbConversationHistory: ConversationMessage[] = conversationHistory.map((msg, index) => ({
id: msg.id || index + 1, // Use index if id not provided
session_id: msg.session_id || mapping.sessionId,
// Convert conversation history to database format first
const dbConversationHistory: ConversationMessage[] = conversationHistory.map((msg, index): ConversationMessage => ({
id: msg.id ?? (index + 1),
session_id: msg.session_id ?? mapping.sessionId,
message_type: msg.message_type,
content: msg.content,
timestamp: msg.timestamp || new Date().toISOString()
timestamp: msg.timestamp ?? new Date().toISOString()
}));
// Track prompt submission and conversation turn
this.trackPromptSubmission(panelId, prompt);
this.trackConversationTurn(panelId, dbConversationHistory);
// Extract agent-specific parameters
const agentParams = this.extractAgentConfig(config);
return this.cliManager.continuePanel(
panelId,
mapping.sessionId,
@ -393,4 +460,64 @@ export abstract class AbstractAIPanelManager {
this.logger?.info(`[${this.getAgentName()}PanelManager] Cleaned up ${panelsToCleanup.length} panels for session ${sessionId}`);
}
/**
* Track prompt submission analytics event
*/
protected trackPromptSubmission(panelId: string, prompt: string): void {
if (!this.analyticsManager) return;
const agentName = this.getAgentName().toLowerCase();
// Store timestamp for calculating response duration later
this.promptStartTimes.set(panelId, Date.now());
this.analyticsManager.track('ai_prompt_submitted', {
prompt_length_category: this.analyticsManager.categorizePromptLength(prompt.length),
panel_type: agentName
});
}
/**
* Track conversation turn analytics event
*/
protected trackConversationTurn(panelId: string, conversationHistory: Array<{id?: number; session_id?: string; message_type: 'user' | 'assistant'; content: string; timestamp?: string}>): void {
if (!this.analyticsManager) return;
const agentName = this.getAgentName().toLowerCase();
// Calculate turn number based on conversation history
// Each pair of user + assistant messages is one turn
const userMessages = conversationHistory.filter(msg => msg.message_type === 'user');
const turnNumber = userMessages.length + 1; // +1 for the current turn
this.analyticsManager.track('ai_conversation_turn', {
turn_number: turnNumber,
panel_type: agentName
});
}
/**
* Track AI response received analytics event
* Should be called when an assistant message is added
*/
protected trackAIResponse(panelId: string, hadToolCalls: boolean): void {
if (!this.analyticsManager) return;
const agentName = this.getAgentName().toLowerCase();
// Calculate duration if we have a start time
const startTime = this.promptStartTimes.get(panelId);
let durationSeconds: number | undefined;
if (startTime) {
durationSeconds = Math.round((Date.now() - startTime) / 1000);
this.promptStartTimes.delete(panelId); // Clean up
}
this.analyticsManager.track('ai_response_received', {
duration_seconds: durationSeconds,
had_tool_calls: hadToolCalls,
panel_type: agentName
});
}
}

View File

@ -137,7 +137,15 @@ export class ClaudeCodeManager extends AbstractCliManager {
// Add MCP configuration if provided
if (mcpConfigPath) {
args.push('--mcp-config', mcpConfigPath, '--permission-prompt-tool', 'mcp__crystal-permissions__approve_permission', '--allowedTools', 'mcp__crystal-permissions__approve_permission');
args.push('--mcp-config', mcpConfigPath);
// Only add permission-specific flags if Crystal's permission server is included
// (which happens when permission mode is 'approve')
const defaultMode = this.configManager?.getConfig()?.defaultPermissionMode || 'ignore';
const effectiveMode = permissionMode || defaultMode;
if (effectiveMode === 'approve' && this.permissionIpcPath) {
args.push('--permission-prompt-tool', 'mcp__crystal-permissions__approve_permission', '--allowedTools', 'mcp__crystal-permissions__approve_permission');
}
}
return args;
@ -277,6 +285,22 @@ export class ClaudeCodeManager extends AbstractCliManager {
}, 5000); // 5 second delay
}
// Clean up base project MCP config file if it exists (not .mcp.json from project)
const baseConfigPath = globalThis[`mcp_base_config_${sessionId}`];
if (baseConfigPath && fs.existsSync(baseConfigPath)) {
setTimeout(() => {
try {
if (fs.existsSync(baseConfigPath)) {
fs.unlinkSync(baseConfigPath);
this.logger?.verbose(`[MCP] Cleaned up base project config file: ${baseConfigPath}`);
}
delete globalThis[`mcp_base_config_${sessionId}`];
} catch (error) {
this.logger?.error(`Failed to delete base project MCP config file:`, error instanceof Error ? error : undefined);
}
}, 5000); // 5 second delay
}
// Clean up temporary MCP script file if it exists
const mcpScriptPath = globalThis[`mcp_script_${sessionId}`];
if (mcpScriptPath && fs.existsSync(mcpScriptPath)) {
@ -377,10 +401,15 @@ export class ClaudeCodeManager extends AbstractCliManager {
// Set up MCP configuration if needed and add to args
const defaultMode = this.configManager?.getConfig()?.defaultPermissionMode || 'ignore';
const effectiveMode = permissionMode || defaultMode;
let mcpConfigPath: string | null = null;
if (effectiveMode === 'approve' && this.permissionIpcPath) {
// Full MCP setup with permission server + base project MCP servers
mcpConfigPath = await this.setupMcpConfigurationSync(sessionId);
} else {
// Even without approval mode, check for base project MCP servers
// This ensures worktrees can access MCP servers from the base project
mcpConfigPath = await this.setupBaseProjectMcpConfig(sessionId);
}
// Store MCP config path in options for buildCommandArgs to use
@ -530,6 +559,94 @@ export class ClaudeCodeManager extends AbstractCliManager {
// Private helper methods
/**
* Get MCP servers configured for the base project.
* Claude Code stores project-specific MCP config in ~/.claude.json under projects[path].mcpServers
* and project-level config in .mcp.json files.
*
* When running in a worktree, Claude doesn't see MCP servers from the base project
* because it uses the worktree path as the project key.
*/
private getBaseProjectMcpServers(sessionId: string): { mcpServers: Record<string, unknown>; mcpJsonPath?: string } {
const result: { mcpServers: Record<string, unknown>; mcpJsonPath?: string } = { mcpServers: {} };
try {
// Get the session to find the project
const dbSession = this.sessionManager.getDbSession(sessionId);
if (!dbSession?.project_id) {
return result;
}
const project = this.sessionManager.getProjectById(dbSession.project_id);
if (!project?.path) {
return result;
}
const baseProjectPath = project.path;
this.logger?.verbose(`[MCP] Looking for base project MCP servers at: ${baseProjectPath}`);
// Check for .mcp.json in the base project directory
const mcpJsonPath = path.join(baseProjectPath, '.mcp.json');
if (fs.existsSync(mcpJsonPath)) {
this.logger?.verbose(`[MCP] Found .mcp.json at: ${mcpJsonPath}`);
result.mcpJsonPath = mcpJsonPath;
// Also parse it to merge with other servers
try {
const mcpJsonContent = fs.readFileSync(mcpJsonPath, 'utf8');
const mcpJson = JSON.parse(mcpJsonContent) as { mcpServers?: Record<string, unknown> };
if (mcpJson.mcpServers) {
Object.assign(result.mcpServers, mcpJson.mcpServers);
}
} catch (parseError) {
this.logger?.warn(`[MCP] Failed to parse .mcp.json: ${parseError}`);
}
}
// Read ~/.claude.json to get project-specific MCP servers
const claudeConfigPath = path.join(os.homedir(), '.claude.json');
if (fs.existsSync(claudeConfigPath)) {
try {
const claudeConfig = fs.readFileSync(claudeConfigPath, 'utf8');
const config = JSON.parse(claudeConfig) as {
projects?: Record<string, { mcpServers?: Record<string, unknown> }>;
mcpServers?: Record<string, unknown>;
};
// Get project-specific MCP servers
const projectConfig = config.projects?.[baseProjectPath];
if (projectConfig?.mcpServers && Object.keys(projectConfig.mcpServers).length > 0) {
this.logger?.verbose(`[MCP] Found ${Object.keys(projectConfig.mcpServers).length} project-specific MCP servers in ~/.claude.json`);
Object.assign(result.mcpServers, projectConfig.mcpServers);
}
// Also include global MCP servers (these apply to all projects)
if (config.mcpServers && Object.keys(config.mcpServers).length > 0) {
this.logger?.verbose(`[MCP] Found ${Object.keys(config.mcpServers).length} global MCP servers in ~/.claude.json`);
// Global servers have lower priority, so only add if not already present
for (const [name, serverConfig] of Object.entries(config.mcpServers)) {
if (!result.mcpServers[name]) {
result.mcpServers[name] = serverConfig;
}
}
}
} catch (parseError) {
this.logger?.warn(`[MCP] Failed to parse ~/.claude.json: ${parseError}`);
}
}
const serverCount = Object.keys(result.mcpServers).length;
if (serverCount > 0) {
this.logger?.info(`[MCP] Found ${serverCount} MCP servers from base project: ${Object.keys(result.mcpServers).join(', ')}`);
}
} catch (error) {
this.logger?.warn(`[MCP] Error getting base project MCP servers: ${error}`);
}
return result;
}
private buildSystemPromptAppend(dbSession: { project_id?: number; [key: string]: unknown }): string | undefined {
const systemPromptParts: string[] = [];
@ -679,8 +796,13 @@ export class ClaudeCodeManager extends AbstractCliManager {
}
}
const mcpConfig = {
// Start with base project MCP servers
const baseProjectMcp = this.getBaseProjectMcpServers(sessionId);
const mcpConfig: { mcpServers: Record<string, unknown> } = {
"mcpServers": {
// Include base project MCP servers first
...baseProjectMcp.mcpServers,
// Crystal's permission server takes precedence (added last)
"crystal-permissions": {
"command": mcpCommand,
"args": mcpArgs
@ -688,6 +810,10 @@ export class ClaudeCodeManager extends AbstractCliManager {
}
};
if (Object.keys(baseProjectMcp.mcpServers).length > 0) {
this.logger?.info(`[MCP] Merged ${Object.keys(baseProjectMcp.mcpServers).length} base project MCP servers into config`);
}
this.logger?.verbose(`[MCP] Creating MCP config at: ${mcpConfigPath}`);
try {
@ -738,4 +864,46 @@ export class ClaudeCodeManager extends AbstractCliManager {
// Just set up the basic environment variables here
return;
}
/**
* Set up MCP configuration for base project servers only (without Crystal permission server).
* Used when permission mode is not 'approve' but we still need to pass base project MCP.
*/
private async setupBaseProjectMcpConfig(sessionId: string): Promise<string | null> {
const baseProjectMcp = this.getBaseProjectMcpServers(sessionId);
// If there's a .mcp.json file in the base project, we can pass it directly
// This is the most reliable way since Claude will parse it correctly
if (baseProjectMcp.mcpJsonPath) {
this.logger?.info(`[MCP] Passing base project .mcp.json: ${baseProjectMcp.mcpJsonPath}`);
return baseProjectMcp.mcpJsonPath;
}
// If there are servers from ~/.claude.json, create a temp config file
if (Object.keys(baseProjectMcp.mcpServers).length > 0) {
const tempDir = path.join(os.homedir(), '.crystal');
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true });
}
const mcpConfigPath = path.join(tempDir, `crystal-base-mcp-${sessionId}.json`);
const mcpConfig = { mcpServers: baseProjectMcp.mcpServers };
try {
fs.writeFileSync(mcpConfigPath, JSON.stringify(mcpConfig, null, 2));
fs.chmodSync(mcpConfigPath, 0o644);
this.logger?.info(`[MCP] Created base project MCP config with ${Object.keys(baseProjectMcp.mcpServers).length} servers: ${mcpConfigPath}`);
// Store for cleanup
globalThis[`mcp_base_config_${sessionId}`] = mcpConfigPath;
return mcpConfigPath;
} catch (error) {
this.logger?.error(`[MCP] Failed to create base project MCP config: ${error}`);
return null;
}
}
return null;
}
}

View File

@ -2,6 +2,7 @@ import { AbstractAIPanelManager } from '../ai/AbstractAIPanelManager';
import { AbstractCliManager } from '../cli/AbstractCliManager';
import type { Logger } from '../../../utils/logger';
import type { ConfigManager } from '../../configManager';
import type { AnalyticsManager } from '../../analyticsManager';
import type { ConversationMessage } from '../../../database/models';
import { AIPanelConfig, StartPanelConfig, ContinuePanelConfig } from '../../../../../shared/types/aiPanelConfig';
import { ClaudePanelState } from '../../../../../shared/types/panels';
@ -16,9 +17,10 @@ export class ClaudePanelManager extends AbstractAIPanelManager {
claudeCodeManager: AbstractCliManager,
sessionManager: import('../../sessionManager').SessionManager,
logger?: Logger,
configManager?: ConfigManager
configManager?: ConfigManager,
analyticsManager?: AnalyticsManager
) {
super(claudeCodeManager, sessionManager, logger, configManager);
super(claudeCodeManager, sessionManager, logger, configManager, analyticsManager);
}
/**
@ -115,15 +117,19 @@ export class ClaudePanelManager extends AbstractAIPanelManager {
/**
* Register panel with Claude-specific state handling
* @param panelId - The panel ID to register
* @param sessionId - The session ID this panel belongs to
* @param initialState - Optional Claude-specific initial state
* @param isUserInitiated - If true, track analytics event (default: true). Set to false during app startup/restoration.
*/
registerPanel(panelId: string, sessionId: string, initialState?: ClaudePanelState): void {
registerPanel(panelId: string, sessionId: string, initialState?: ClaudePanelState, isUserInitiated = true): void {
// Transform Claude-specific state to base state if needed
const baseInitialState = initialState ? {
...initialState,
resumeId: initialState.claudeResumeId // Map claudeResumeId to resumeId for base class
} : undefined;
super.registerPanel(panelId, sessionId, baseInitialState);
super.registerPanel(panelId, sessionId, baseInitialState, isUserInitiated);
}
/**

View File

@ -3,6 +3,7 @@ import { AbstractAIPanelManager } from '../ai/AbstractAIPanelManager';
import { CodexManager } from './codexManager';
import type { Logger } from '../../../utils/logger';
import type { ConfigManager } from '../../configManager';
import type { AnalyticsManager } from '../../analyticsManager';
import type { ConversationMessage } from '../../../database/models';
import { AIPanelConfig, StartPanelConfig, ContinuePanelConfig } from '../../../../../shared/types/aiPanelConfig';
import { DEFAULT_CODEX_MODEL } from '../../../../../shared/types/models';
@ -34,9 +35,10 @@ export class CodexPanelManager extends AbstractAIPanelManager {
codexManager: CodexManager,
sessionManager: import('../../sessionManager').SessionManager,
logger?: Logger,
configManager?: ConfigManager
configManager?: ConfigManager,
analyticsManager?: AnalyticsManager
) {
super(codexManager, sessionManager, logger, configManager);
super(codexManager, sessionManager, logger, configManager, analyticsManager);
this.logger?.verbose('CodexPanelManager initialized');
this.setupCodexSpecificHandlers();
}
@ -265,8 +267,12 @@ export class CodexPanelManager extends AbstractAIPanelManager {
/**
* Register panel with Codex-specific state handling
* @param panelId - The panel ID to register
* @param sessionId - The session ID this panel belongs to
* @param initialState - Optional Codex-specific initial state
* @param isUserInitiated - If true, track analytics event (default: true). Set to false during app startup/restoration.
*/
registerPanel(panelId: string, sessionId: string, initialState?: CodexPanelState): void {
registerPanel(panelId: string, sessionId: string, initialState?: CodexPanelState, isUserInitiated = true): void {
// Transform Codex-specific state to base state if needed
const baseInitialState = initialState ? {
isInitialized: initialState.isInitialized,
@ -282,7 +288,7 @@ export class CodexPanelManager extends AbstractAIPanelManager {
}
} : undefined;
super.registerPanel(panelId, sessionId, baseInitialState);
super.registerPanel(panelId, sessionId, baseInitialState, isUserInitiated);
}
/**

View File

@ -5,10 +5,13 @@ import { panelManager } from '../../panelManager';
import { addSessionLog, cleanupSessionLogs } from '../../../ipc/logs';
import { mainWindow } from '../../../index';
import { getShellPath } from '../../../utils/shellPath';
import type { AnalyticsManager } from '../../analyticsManager';
export class LogsManager {
private static instance: LogsManager;
private activeProcesses = new Map<string, ChildProcess>(); // panelId -> process
private scriptStartTimes = new Map<string, number>(); // panelId -> start timestamp
private analyticsManager: AnalyticsManager | null = null;
static getInstance(): LogsManager {
if (!LogsManager.instance) {
@ -17,6 +20,13 @@ export class LogsManager {
return LogsManager.instance;
}
/**
* Set the analytics manager for tracking script executions
*/
setAnalyticsManager(analyticsManager: AnalyticsManager): void {
this.analyticsManager = analyticsManager;
}
/**
* Get or create singleton logs panel for session
*/
@ -94,6 +104,10 @@ export class LogsManager {
// Update panel state to running
const startTime = new Date().toISOString();
// Record start time for analytics tracking
this.scriptStartTimes.set(panel.id, Date.now());
await panelManager.updatePanel(panel.id, {
state: {
...panel.state,
@ -412,7 +426,22 @@ export class LogsManager {
private async handleProcessExit(panelId: string, sessionId: string, code: number | null): Promise<void> {
// Remove from active processes
this.activeProcesses.delete(panelId);
// Track script execution analytics
const startTime = this.scriptStartTimes.get(panelId);
if (startTime && this.analyticsManager) {
const duration = (Date.now() - startTime) / 1000; // Convert to seconds
const success = code === 0;
this.analyticsManager.track('run_script_executed', {
success,
duration_seconds: this.analyticsManager.categorizeDuration(duration),
});
// Clean up start time
this.scriptStartTimes.delete(panelId);
}
// Update panel state
const panel = await panelManager.getPanel(panelId);
if (panel) {
@ -429,7 +458,7 @@ export class LogsManager {
}
});
}
// Emit process ended event
if (mainWindow) {
mainWindow.webContents.send('panel:event', {
@ -442,16 +471,16 @@ export class LogsManager {
data: { exitCode: code },
timestamp: new Date().toISOString()
});
// Also send specific event for the panel
mainWindow.webContents.send('process:ended', {
panelId,
exitCode: code
});
}
// Add final log entry
const message = code === 0
const message = code === 0
? 'Process completed successfully'
: `Process exited with code ${code}`;
addSessionLog(sessionId, code === 0 ? 'info' : 'error', message, 'Script');

View File

@ -44,6 +44,7 @@ import { addSessionLog, cleanupSessionLogs } from '../ipc/logs';
import { withLock } from '../utils/mutex';
import * as os from 'os';
import { panelManager } from './panelManager';
import type { AnalyticsManager } from './analyticsManager';
export class SessionManager extends EventEmitter {
private activeSessions: Map<string, Session> = new Map();
@ -52,12 +53,14 @@ export class SessionManager extends EventEmitter {
private activeProject: Project | null = null;
private terminalSessionManager: TerminalSessionManager;
private autoContextBuffers: Map<string, SessionOutput[]> = new Map();
private analyticsManager: AnalyticsManager | null = null;
constructor(public db: DatabaseService) {
constructor(public db: DatabaseService, analyticsManager?: AnalyticsManager) {
super();
// Increase max listeners to prevent warnings when many components listen to events
// This is expected since multiple SessionListItem components and project tree views listen to events
this.setMaxListeners(100);
this.analyticsManager = analyticsManager || null;
this.terminalSessionManager = new TerminalSessionManager();
// Forward terminal output events to the terminal display
@ -390,7 +393,49 @@ export class SessionManager extends EventEmitter {
this.activeSessions.set(session.id, session);
// Don't emit the event here - let the caller decide when to emit it
// this.emit('session-created', session);
// Track session creation with analytics
if (this.analyticsManager) {
// Get session statistics for analytics
const allSessions = this.db.getAllSessions();
const activeSessions = allSessions.filter(s => !s.archived);
const archivedSessions = allSessions.filter(s => s.archived);
// Count sessions by status
const statusCounts: Record<string, number> = {};
activeSessions.forEach(s => {
const status = s.status || 'unknown';
statusCounts[status] = (statusCounts[status] || 0) + 1;
});
// Count unique projects
const allProjects = this.db.getAllProjects();
const projectCount = allProjects.length;
this.analyticsManager.track('session_created', {
tool_type: toolType || 'none',
template_type: worktreeName.startsWith('main') ? 'main' : 'worktree',
session_count: 1, // This is for a single session creation
has_folder: !!folderId,
used_claude_code: toolType === 'claude',
used_codex: toolType === 'codex',
used_auto_name: false, // Will be updated by caller if auto-name was used
auto_name_available: true, // Auto-naming is always available
git_mode: isMainRepo ? 'main_repo' : commitMode || 'disabled',
existing_active_sessions_count: activeSessions.length,
existing_total_sessions_count: allSessions.length,
existing_archived_sessions_count: archivedSessions.length,
existing_sessions_initializing: statusCounts['initializing'] || 0,
existing_sessions_running: statusCounts['running'] || 0,
existing_sessions_waiting: statusCounts['waiting'] || 0,
existing_sessions_stopped: statusCounts['stopped'] || 0,
existing_sessions_error: statusCounts['error'] || 0,
existing_sessions_completed: statusCounts['completed'] || 0,
existing_sessions_completed_unviewed: statusCounts['completed_unviewed'] || 0,
existing_projects_count: projectCount
});
}
return session;
}
@ -497,6 +542,21 @@ export class SessionManager extends EventEmitter {
updateSessionStatus(id: string, status: Session['status'], statusMessage?: string): void {
this.updateSession(id, { status, statusMessage });
// Track session start when status changes to running
if (status === 'running' && this.analyticsManager) {
const session = this.getSession(id);
if (session) {
// Check if this is a continuation based on conversation history
const conversationMessages = this.getConversationMessages(id);
const isContinuation = conversationMessages.length > 0;
this.analyticsManager.track('session_started', {
tool_type: session.toolType || 'none',
is_continuation: isContinuation
});
}
}
}
addSessionError(id: string, error: string, details?: string): void {
@ -548,12 +608,33 @@ export class SessionManager extends EventEmitter {
// Update the completion timestamp for the most recent prompt
const completionTimestamp = output.timestamp instanceof Date ? output.timestamp.toISOString() : output.timestamp;
this.db.updatePromptMarkerCompletion(id, completionTimestamp);
// Mark the session as completed (this will trigger the completed_unviewed logic if not viewed)
const dbSession = this.db.getSession(id);
if (dbSession && dbSession.status === 'running') {
// Track session completion with analytics
if (this.analyticsManager) {
// Calculate duration
let durationSeconds = 0;
if (dbSession.run_started_at) {
const startTime = new Date(dbSession.run_started_at).getTime();
const endTime = Date.now();
durationSeconds = Math.floor((endTime - startTime) / 1000);
}
// Get prompt count
const promptMarkers = this.db.getPromptMarkers(id);
const promptCount = promptMarkers.length;
this.analyticsManager.track('session_completed', {
duration_seconds: durationSeconds,
duration_category: this.analyticsManager.categorizeDuration(durationSeconds),
prompt_count: promptCount
});
}
this.db.updateSession(id, { status: 'completed' });
// Re-convert to get the proper status (completed_unviewed if not viewed)
const updatedDbSession = this.db.getSession(id);
if (updatedDbSession) {
@ -656,6 +737,21 @@ export class SessionManager extends EventEmitter {
}
async archiveSession(id: string): Promise<void> {
// Track session archival with analytics before archiving
if (this.analyticsManager) {
const dbSession = this.db.getSession(id);
if (dbSession) {
// Calculate session age in days
const createdTime = new Date(dbSession.created_at).getTime();
const currentTime = Date.now();
const sessionAgeDays = Math.floor((currentTime - createdTime) / (1000 * 60 * 60 * 24));
this.analyticsManager.track('session_archived', {
session_age_days: sessionAgeDays
});
}
}
const success = this.db.archiveSession(id);
if (!success) {
throw new Error(`Session ${id} not found`);
@ -704,6 +800,31 @@ export class SessionManager extends EventEmitter {
}
stopSession(id: string): void {
// Track session stop with analytics
if (this.analyticsManager) {
const session = this.getSession(id);
if (session) {
const dbSession = this.db.getSession(id);
// Calculate duration
let durationSeconds = 0;
if (dbSession?.run_started_at) {
const startTime = new Date(dbSession.run_started_at).getTime();
const endTime = Date.now();
durationSeconds = Math.floor((endTime - startTime) / 1000);
}
// Check if session had errors
const hadErrors = !!session.error || dbSession?.exit_code !== 0;
this.analyticsManager.track('session_stopped', {
duration_seconds: durationSeconds,
duration_category: this.analyticsManager.categorizeDuration(durationSeconds),
had_errors: hadErrors
});
}
}
this.updateSession(id, { status: 'stopped' });
}
@ -917,6 +1038,26 @@ export class SessionManager extends EventEmitter {
async continueConversation(id: string, userMessage: string): Promise<void> {
return await withLock(`session-input-${id}`, async () => {
// Track conversation continuation with analytics
if (this.analyticsManager) {
const conversationMessages = this.getConversationMessages(id);
const messageCount = conversationMessages.length;
// Calculate time since last message
let timeSinceLastMessageHours = 0;
if (conversationMessages.length > 0) {
const lastMessage = conversationMessages[conversationMessages.length - 1];
const lastMessageTime = new Date(lastMessage.timestamp).getTime();
const currentTime = Date.now();
timeSinceLastMessageHours = (currentTime - lastMessageTime) / (1000 * 60 * 60);
}
this.analyticsManager.track('session_continued', {
time_since_last_message_hours: Math.round(timeSinceLastMessageHours * 10) / 10, // Round to 1 decimal
message_count: messageCount
});
}
// Store the user's message
this.addConversationMessage(id, 'user', userMessage);

View File

@ -6,6 +6,7 @@ import * as os from 'os';
import * as path from 'path';
import { getShellPath } from '../utils/shellPath';
import { ShellDetector } from '../utils/shellDetector';
import type { AnalyticsManager } from './analyticsManager';
interface TerminalProcess {
pty: pty.IPty;
@ -20,7 +21,12 @@ interface TerminalProcess {
export class TerminalPanelManager {
private terminals = new Map<string, TerminalProcess>();
private readonly MAX_SCROLLBACK_LINES = 10000;
private analyticsManager: AnalyticsManager | null = null;
setAnalyticsManager(analyticsManager: AnalyticsManager): void {
this.analyticsManager = analyticsManager;
}
async initializeTerminal(panel: ToolPanel, cwd: string): Promise<void> {
if (this.terminals.has(panel.id)) {
return;
@ -79,7 +85,11 @@ export class TerminalPanelManager {
} as TerminalPanelState;
await panelManager.updatePanel(panel.id, { state });
// NOTE: terminal_panel_created analytics tracking has been moved to panelManager.createPanel()
// to ensure it only fires when users explicitly create new panels, not during app restoration
// or when panels are initialized for viewing.
}
private setupTerminalHandlers(terminal: TerminalProcess): void {

View File

@ -5,6 +5,7 @@ import { mkdir } from 'fs/promises';
import { getShellPath } from '../utils/shellPath';
import { withLock } from '../utils/mutex';
import type { ConfigManager } from './configManager';
import type { AnalyticsManager } from './analyticsManager';
// Interface for raw commit data
interface RawCommitData {
@ -34,7 +35,10 @@ async function execWithShellPath(command: string, options?: { cwd?: string }): P
export class WorktreeManager {
private projectsCache: Map<string, { baseDir: string }> = new Map();
constructor(private configManager?: ConfigManager) {
constructor(
private configManager?: ConfigManager,
private analyticsManager?: AnalyticsManager
) {
// No longer initialized with a single repo path
}
@ -155,7 +159,14 @@ export class WorktreeManager {
}
console.log(`[WorktreeManager] Worktree created successfully at: ${worktreePath}`);
// Track worktree creation
if (this.analyticsManager) {
this.analyticsManager.track('git_worktree_created', {
branch_existed: branchExists
});
}
return { worktreePath, baseCommit, baseBranch: actualBaseBranch };
} catch (error) {
console.error(`[WorktreeManager] Failed to create worktree:`, error);
@ -164,25 +175,33 @@ export class WorktreeManager {
});
}
async removeWorktree(projectPath: string, name: string, worktreeFolder?: string): Promise<void> {
async removeWorktree(projectPath: string, name: string, worktreeFolder?: string, sessionCreatedAt?: Date): Promise<void> {
return await withLock(`worktree-remove-${projectPath}-${name}`, async () => {
const { baseDir } = this.getProjectPaths(projectPath, worktreeFolder);
const worktreePath = join(baseDir, name);
try {
await execWithShellPath(`git worktree remove "${worktreePath}" --force`, { cwd: projectPath });
// Track worktree cleanup
if (this.analyticsManager && sessionCreatedAt) {
const sessionAgeDays = Math.floor((Date.now() - sessionCreatedAt.getTime()) / (1000 * 60 * 60 * 24));
this.analyticsManager.track('git_worktree_cleaned', {
session_age_days: sessionAgeDays
});
}
} catch (error: unknown) {
const err = error as Error & { stderr?: string; stdout?: string };
const errorMessage = err.stderr || err.stdout || err.message || String(err);
// If the worktree is not found, that's okay - it might have been manually deleted
if (errorMessage.includes('is not a working tree') ||
if (errorMessage.includes('is not a working tree') ||
errorMessage.includes('does not exist') ||
errorMessage.includes('No such file or directory')) {
console.log(`Worktree ${worktreePath} already removed or doesn't exist, skipping...`);
return;
}
// For other errors, still throw
throw new Error(`Failed to remove worktree: ${errorMessage}`);
}
@ -454,18 +473,50 @@ export class WorktreeManager {
return await withLock(`git-rebase-${worktreePath}`, async () => {
const executedCommands: string[] = [];
let lastOutput = '';
const startTime = Date.now();
let conflictOccurred = false;
try {
// Rebase the current worktree branch onto local main branch
const command = `git rebase ${mainBranch}`;
executedCommands.push(`${command} (in ${worktreePath})`);
const rebaseResult = await execWithShellPath(command, { cwd: worktreePath });
lastOutput = rebaseResult.stdout || rebaseResult.stderr || '';
// Track successful rebase
if (this.analyticsManager) {
const durationSeconds = Math.floor((Date.now() - startTime) / 1000);
this.analyticsManager.track('git_rebase_executed', {
success: true,
duration_seconds: durationSeconds,
conflict_occurred: false
});
}
} catch (error: unknown) {
const err = error as Error & { stderr?: string; stdout?: string };
console.error(`[WorktreeManager] Failed to rebase ${mainBranch} into worktree:`, err);
// Check if conflict occurred
const errorOutput = err.stderr || err.stdout || err.message || '';
conflictOccurred = errorOutput.includes('CONFLICT');
// Track failed rebase
if (this.analyticsManager) {
const durationSeconds = Math.floor((Date.now() - startTime) / 1000);
this.analyticsManager.track('git_rebase_executed', {
success: false,
duration_seconds: durationSeconds,
conflict_occurred: conflictOccurred
});
// Track operation failure
const errorCategory = conflictOccurred ? 'conflict' : 'unknown';
this.analyticsManager.track('git_operation_failed', {
operation_type: 'rebase_from_main',
error_category: errorCategory
});
}
// Create detailed error with git command output
const gitError = new Error(`Failed to rebase ${mainBranch} into worktree`) as Error & {
gitCommand?: string;
@ -477,7 +528,7 @@ export class WorktreeManager {
gitError.gitOutput = err.stderr || err.stdout || lastOutput || err.message || '';
gitError.workingDirectory = worktreePath;
gitError.originalError = err;
throw gitError;
}
});
@ -507,6 +558,7 @@ export class WorktreeManager {
return await withLock(`git-squash-merge-${worktreePath}`, async () => {
const executedCommands: string[] = [];
let lastOutput = '';
const startTime = Date.now();
try {
console.log(`[WorktreeManager] Squashing and merging worktree to ${mainBranch}: ${worktreePath}`);
@ -604,10 +656,44 @@ Co-Authored-By: Crystal <crystal@stravu.com>` : commitMessage;
}
console.log(`[WorktreeManager] Successfully squashed and merged worktree to ${mainBranch}`);
// Track successful squash and merge
if (this.analyticsManager) {
const durationSeconds = Math.floor((Date.now() - startTime) / 1000);
// Get commit count from the commits variable (already fetched earlier)
const commitCount = commits.trim().split('\n').filter(Boolean).length;
const commitCountCategory = this.analyticsManager.categorizeNumber(commitCount, [1, 3, 5, 10, 25]);
this.analyticsManager.track('git_squash_executed', {
success: true,
duration_seconds: durationSeconds,
commit_count_category: commitCountCategory
});
}
} catch (error: unknown) {
const err = error as Error & { stderr?: string; stdout?: string };
console.error(`[WorktreeManager] Failed to squash and merge worktree to ${mainBranch}:`, err);
// Track failed squash
if (this.analyticsManager) {
const durationSeconds = Math.floor((Date.now() - startTime) / 1000);
const errorOutput = err.stderr || err.stdout || err.message || '';
const errorCategory = errorOutput.includes('CONFLICT') ? 'conflict' :
errorOutput.includes('merge') ? 'merge_failed' :
errorOutput.includes('rebase') ? 'rebase_failed' : 'unknown';
this.analyticsManager.track('git_squash_executed', {
success: false,
duration_seconds: durationSeconds,
commit_count_category: '0-1' // Unknown on failure
});
this.analyticsManager.track('git_operation_failed', {
operation_type: 'squash_and_merge',
error_category: errorCategory
});
}
// Create detailed error with git command output
const gitError = new Error(`Failed to squash and merge worktree to ${mainBranch}`) as Error & {
gitCommands?: string[];

View File

@ -62,6 +62,13 @@ export interface AppConfig {
};
// Crystal commit footer setting (enabled by default)
enableCrystalFooter?: boolean;
// PostHog analytics settings
analytics?: {
enabled: boolean;
posthogApiKey?: string;
posthogHost?: string;
distinctId?: string; // Random UUID for anonymous user identification
};
}
export interface UpdateConfigRequest {
@ -113,4 +120,11 @@ export interface UpdateConfigRequest {
};
};
disableCrystalFooter?: boolean;
// PostHog analytics settings
analytics?: {
enabled: boolean;
posthogApiKey?: string;
posthogHost?: string;
distinctId?: string; // Random UUID for anonymous user identification
};
}

View File

@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest';
import * as path from 'path';
import { isSafeSessionId, getSafeImageExtension } from '../artifactPathSafety';
describe('isSafeSessionId', () => {
it('accepts a real session id (crypto.randomUUID format)', () => {
expect(isSafeSessionId('3fa85f64-5717-4562-b3fc-2c963f66afa6')).toBe(true);
});
it('accepts a pending session id generated by the renderer', () => {
expect(isSafeSessionId('pending_1700000000000_abc1234')).toBe(true);
});
it('rejects a session id containing a path traversal sequence', () => {
expect(isSafeSessionId('pending_../../../../../../tmp/evilsession')).toBe(false);
});
it('rejects a session id containing a path separator', () => {
expect(isSafeSessionId('foo/bar')).toBe(false);
expect(isSafeSessionId('foo\\bar')).toBe(false);
});
it('rejects empty or non-string input', () => {
expect(isSafeSessionId('')).toBe(false);
// @ts-expect-error intentionally testing bad input
expect(isSafeSessionId(undefined)).toBe(false);
});
it('never allows the resulting joined path to escape the parent directory', () => {
const base = path.join('/tmp', 'crystal-artifacts-test');
const maliciousId = '../../../../../../etc';
expect(isSafeSessionId(maliciousId)).toBe(false);
// Demonstrate why: if it were allowed, join would escape `base`.
const joined = path.join(base, 'artifacts', maliciousId);
expect(joined.startsWith(base)).toBe(false);
});
});
describe('getSafeImageExtension', () => {
it('maps known mime types to their expected extension', () => {
expect(getSafeImageExtension('image/png')).toBe('png');
expect(getSafeImageExtension('image/jpeg')).toBe('jpg');
expect(getSafeImageExtension('image/gif')).toBe('gif');
expect(getSafeImageExtension('image/webp')).toBe('webp');
});
it('falls back to png for an unknown mime type', () => {
expect(getSafeImageExtension('image/x-made-up')).toBe('png');
});
it('falls back to png for a mime type crafted for path traversal', () => {
const malicious = 'image/../../../../../../tmp/pwned.sh';
expect(getSafeImageExtension(malicious)).toBe('png');
});
it('falls back to png for missing/undefined mime type', () => {
expect(getSafeImageExtension(undefined)).toBe('png');
expect(getSafeImageExtension(null)).toBe('png');
expect(getSafeImageExtension('')).toBe('png');
});
});

View File

@ -0,0 +1,49 @@
/**
* Safety helpers for building file-system paths from IPC input when saving
* session artifacts (pasted images / large text blobs).
*
* `sessions:save-images` and `sessions:save-large-text` build a directory
* from the caller-supplied `sessionId` and (for images) a file extension
* derived from a caller-supplied MIME `type`. Neither value is guaranteed to
* come from a trusted source once it crosses the IPC boundary, so both must
* be validated before being used in `path.join(...)`.
*/
// Real sessions use crypto.randomUUID(); pending (not-yet-created) sessions
// use `pending_<timestamp>_<randomBase36>` generated by the renderer.
const SAFE_SESSION_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
/**
* Returns true only if `sessionId` is a plain identifier containing no path
* separators, `..` traversal segments, or other characters that could
* escape the intended artifacts directory when joined with a base path.
*/
export function isSafeSessionId(sessionId: string): boolean {
if (!sessionId || typeof sessionId !== 'string') {
return false;
}
return SAFE_SESSION_ID_PATTERN.test(sessionId);
}
const ALLOWED_IMAGE_EXTENSIONS: Record<string, string> = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
'image/gif': 'gif',
'image/webp': 'webp',
'image/bmp': 'bmp',
'image/svg+xml': 'svg',
};
/**
* Derives a safe file extension for a saved image from its MIME `type`.
* Falls back to `png` for anything not on the allow-list, which also
* neutralizes attempts to smuggle path separators or traversal sequences
* in via a crafted `type` value (e.g. `image/../../../../etc/cron.d/x`).
*/
export function getSafeImageExtension(mimeType: string | undefined | null): string {
if (!mimeType) {
return 'png';
}
return ALLOWED_IMAGE_EXTENSIONS[mimeType.toLowerCase()] ?? 'png';
}

View File

@ -1,6 +1,6 @@
{
"name": "crystal",
"version": "0.3.3",
"version": "0.3.5",
"private": true,
"description": "Crystal - Claude Code Commander for managing multiple Claude Code instances",
"author": {
@ -37,6 +37,8 @@
"build:linux": "pnpm run build:frontend && pnpm run build:main && pnpm run inject-build-info && pnpm run generate-notices && electron-builder --linux --publish never",
"build:linux:ci": "pnpm run build:frontend && pnpm run build:main && pnpm run inject-build-info && pnpm run generate-notices && electron-builder --linux --publish never",
"build:mac:ci": "pnpm run build:frontend && pnpm run build:main && pnpm run inject-build-info && pnpm run generate-notices && node scripts/configure-build.js && electron-builder --mac --publish never",
"build:win": "pnpm run build:frontend && pnpm run build:main && pnpm run inject-build-info && pnpm run generate-notices && electron-builder --win --publish never",
"build:win:x64": "pnpm run build:frontend && pnpm run build:main && pnpm run inject-build-info && pnpm run generate-notices && electron-builder --win --x64 --publish never",
"inject-build-info": "node scripts/inject-build-info.js",
"release:mac": "pnpm run build:frontend && pnpm run build:main && pnpm run inject-build-info && pnpm run generate-notices && node scripts/configure-build.js && electron-builder --mac --publish always",
"release:mac:universal": "pnpm run build:frontend && pnpm run build:main && pnpm run inject-build-info && pnpm run generate-notices && node scripts/configure-build.js && electron-builder --mac --universal --publish always",
@ -67,6 +69,7 @@
"electron-updater": "^6.6.8",
"glob": "^11.0.0",
"openai": "^5.1.1",
"posthog-node": "^5.11.2",
"web-streams-polyfill": "^3.3.3"
},
"devDependencies": {
@ -89,6 +92,7 @@
},
"files": [
"main/dist/**/*",
"main/assets/**/*",
"frontend/dist/**/*",
"package.json",
"node_modules/**/*",
@ -152,6 +156,25 @@
}
}
},
"win": {
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
}
],
"icon": "main/assets/icon.ico",
"artifactName": "${productName}-${version}-Windows-${arch}.${ext}"
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"createDesktopShortcut": true,
"createStartMenuShortcut": true,
"shortcutName": "Crystal"
},
"deb": {
"depends": [
"libgtk-3-0",

21
pnpm-lock.yaml generated
View File

@ -38,6 +38,9 @@ importers:
openai:
specifier: ^5.1.1
version: 5.10.1(zod@3.25.76)
posthog-node:
specifier: ^5.11.2
version: 5.11.2
web-streams-polyfill:
specifier: ^3.3.3
version: 3.3.3
@ -265,6 +268,9 @@ importers:
glob:
specifier: ^11.0.0
version: 11.0.3
posthog-node:
specifier: ^5.11.2
version: 5.11.2
web-streams-polyfill:
specifier: ^3.3.3
version: 3.3.3
@ -1115,6 +1121,9 @@ packages:
engines: {node: '>=18'}
hasBin: true
'@posthog/core@1.5.2':
resolution: {integrity: sha512-iedUP3EnOPPxTA2VaIrsrd29lSZnUV+ZrMnvY56timRVeZAXoYCkmjfIs3KBAsF8OUT5h1GXLSkoQdrV0r31OQ==}
'@radix-ui/number@1.1.1':
resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==}
@ -4119,6 +4128,10 @@ packages:
resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}
engines: {node: ^10 || ^12 || >=14}
posthog-node@5.11.2:
resolution: {integrity: sha512-z+XekcBUmGePMsjPlGaEF2bJFiDHKHYPQjS4OEw4YPDQz8s7Owuim/L7xNX+6UJkyIRniBza9iC7bW8yrGTv1g==}
engines: {node: '>=20'}
prebuild-install@7.1.3:
resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}
engines: {node: '>=10'}
@ -5910,6 +5923,10 @@ snapshots:
dependencies:
playwright: 1.54.1
'@posthog/core@1.5.2':
dependencies:
cross-spawn: 7.0.6
'@radix-ui/number@1.1.1': {}
'@radix-ui/primitive@1.1.2': {}
@ -9418,6 +9435,10 @@ snapshots:
picocolors: 1.1.1
source-map-js: 1.2.1
posthog-node@5.11.2:
dependencies:
'@posthog/core': 1.5.2
prebuild-install@7.1.3:
dependencies:
detect-libc: 2.0.4

View File

@ -1,6 +1,6 @@
{
"name": "shared",
"version": "0.3.3",
"version": "0.3.5",
"private": true,
"main": "index.js",
"types": "index.d.ts",

View File

@ -50,6 +50,9 @@ export interface DiffPanelState {
commitSha?: string; // Specific commit being viewed
}
// Panel status type - mirrors session status but at panel level
export type PanelStatus = 'idle' | 'running' | 'waiting' | 'stopped' | 'completed_unviewed' | 'error';
// Base interface for AI panel states (Claude, Codex, etc.)
export interface BaseAIPanelState {
// Common state for all AI tools
@ -58,10 +61,14 @@ export interface BaseAIPanelState {
model?: string; // Model being used
lastActivityTime?: string; // For "idle since" indicators
lastInput?: string; // Last input sent to the AI
// Panel-level status tracking (independent per panel)
panelStatus?: PanelStatus; // Current panel execution status
hasUnviewedContent?: boolean; // Whether panel has content not yet viewed
// Generic agent session ID for resume functionality (used by all AI agents)
agentSessionId?: string; // The AI agent's session ID for resuming conversations
// Legacy fields for backward compatibility (will be migrated to agentSessionId)
claudeSessionId?: string; // Deprecated: Use agentSessionId instead
codexSessionId?: string; // Deprecated: Use agentSessionId instead