mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Merge branch 'sessionManager' into 'main'
Use multi-session agent chats See merge request soapbox-pub/act2!4
This commit is contained in:
18 files changed
+1068
-612
No files matched your search
Generated
+15
-203
@@ -230,32 +230,6 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@cspotcode/source-map-support": {
|
||||
"version": "0.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
|
||||
"integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@jridgewell/trace-mapping": "0.3.9"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": {
|
||||
"version": "0.3.9",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
|
||||
"integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@jridgewell/resolve-uri": "^3.0.3",
|
||||
"@jridgewell/sourcemap-codec": "^1.4.10"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/color-helpers": {
|
||||
"version": "5.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.0.2.tgz",
|
||||
@@ -371,33 +345,6 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@edge-runtime/primitives": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@edge-runtime/primitives/-/primitives-4.1.0.tgz",
|
||||
"integrity": "sha512-Vw0lbJ2lvRUqc7/soqygUX216Xb8T3WBZ987oywz6aJqRxcwSVWwr9e+Nqo2m9bxobA9mdbWNNoRY6S9eko1EQ==",
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/@edge-runtime/vm": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@edge-runtime/vm/-/vm-3.2.0.tgz",
|
||||
"integrity": "sha512-0dEVyRLM/lG4gp1R/Ik5bfPl/1wX00xFwd5KcNH602tzBa09oF7pbTKETEhR1GjZ75K6OJnYFu8II2dyMhONMw==",
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@edge-runtime/primitives": "4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.5",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz",
|
||||
@@ -3270,7 +3217,7 @@
|
||||
"version": "1.11.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
|
||||
"integrity": "sha512-MaQEIpfcEMzx3VWWopbofKJvaraqmL6HbLlw2bFZ7qYqYw3rkhM0cQVEgyzbHtTWwCwPMFZSC2DUbhlZgrMfLg==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
@@ -3312,6 +3259,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3328,6 +3276,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3344,6 +3293,7 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3360,6 +3310,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3376,6 +3327,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3392,6 +3344,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3408,6 +3361,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3424,6 +3378,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3440,6 +3395,7 @@
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3456,6 +3412,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3469,14 +3426,14 @@
|
||||
"version": "0.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
|
||||
"integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@swc/types": {
|
||||
"version": "0.1.21",
|
||||
"resolved": "https://registry.npmjs.org/@swc/types/-/types-0.1.21.tgz",
|
||||
"integrity": "sha512-2YEtj5HJVbKivud9N4bpPBAyZhj4S2Ipe5LkUG94alTpr7in/GU/EARgPAd3BwU+YOmFVJC2+kjqhGRi3r0ZpQ==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@swc/counter": "^0.1.3"
|
||||
@@ -3629,38 +3586,6 @@
|
||||
"@testing-library/dom": ">=7.21.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@tsconfig/node10": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz",
|
||||
"integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@tsconfig/node12": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz",
|
||||
"integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@tsconfig/node14": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz",
|
||||
"integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@tsconfig/node16": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz",
|
||||
"integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@types/aria-query": {
|
||||
"version": "5.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
|
||||
@@ -3807,7 +3732,7 @@
|
||||
"version": "22.15.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.3.tgz",
|
||||
"integrity": "sha512-lX7HFZeHf4QG/J7tBZqrCAXwz9J5RD56Y6MpP0eJkka8p+K0RY/yBTW7CYFJ4VGCclxqOLKmiGP5juQc6MKgcw==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
@@ -4268,20 +4193,6 @@
|
||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn-walk": {
|
||||
"version": "8.3.4",
|
||||
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz",
|
||||
"integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"acorn": "^8.11.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-base": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz",
|
||||
@@ -4941,14 +4852,6 @@
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/create-require": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
|
||||
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
@@ -5284,17 +5187,6 @@
|
||||
"integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/diff": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
|
||||
"integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==",
|
||||
"license": "BSD-3-Clause",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/diff3": {
|
||||
"version": "0.0.3",
|
||||
"resolved": "https://registry.npmjs.org/diff3/-/diff3-0.0.3.tgz",
|
||||
@@ -7438,14 +7330,6 @@
|
||||
"url": "https://github.com/sponsors/sxzz"
|
||||
}
|
||||
},
|
||||
"node_modules/make-error": {
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
|
||||
"integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",
|
||||
"license": "ISC",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/markdown-table": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",
|
||||
@@ -10738,59 +10622,6 @@
|
||||
"integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/ts-node": {
|
||||
"version": "10.9.1",
|
||||
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz",
|
||||
"integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@cspotcode/source-map-support": "^0.8.0",
|
||||
"@tsconfig/node10": "^1.0.7",
|
||||
"@tsconfig/node12": "^1.0.7",
|
||||
"@tsconfig/node14": "^1.0.0",
|
||||
"@tsconfig/node16": "^1.0.2",
|
||||
"acorn": "^8.4.1",
|
||||
"acorn-walk": "^8.1.1",
|
||||
"arg": "^4.1.0",
|
||||
"create-require": "^1.1.0",
|
||||
"diff": "^4.0.1",
|
||||
"make-error": "^1.1.1",
|
||||
"v8-compile-cache-lib": "^3.0.1",
|
||||
"yn": "3.1.1"
|
||||
},
|
||||
"bin": {
|
||||
"ts-node": "dist/bin.js",
|
||||
"ts-node-cwd": "dist/bin-cwd.js",
|
||||
"ts-node-esm": "dist/bin-esm.js",
|
||||
"ts-node-script": "dist/bin-script.js",
|
||||
"ts-node-transpile-only": "dist/bin-transpile.js",
|
||||
"ts-script": "dist/bin-script-deprecated.js"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@swc/core": ">=1.2.50",
|
||||
"@swc/wasm": ">=1.2.50",
|
||||
"@types/node": "*",
|
||||
"typescript": ">=2.7"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@swc/core": {
|
||||
"optional": true
|
||||
},
|
||||
"@swc/wasm": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/ts-node/node_modules/arg": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
|
||||
"integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
@@ -10880,7 +10711,7 @@
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/unhead": {
|
||||
@@ -11210,14 +11041,6 @@
|
||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/v8-compile-cache-lib": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
|
||||
"integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/vaul": {
|
||||
"version": "0.9.9",
|
||||
"resolved": "https://registry.npmjs.org/vaul/-/vaul-0.9.9.tgz",
|
||||
@@ -11809,17 +11632,6 @@
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/yn": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
|
||||
"integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/yocto-queue": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||
|
||||
+10
-7
@@ -14,6 +14,7 @@ import { NostrLoginProvider } from '@nostrify/react/login';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { JSRuntimeProvider } from '@/components/JSRuntimeProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
@@ -65,13 +66,15 @@ export function App() {
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Sonner />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Sonner />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { SessionMonitor } from "./components/SessionMonitor";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
@@ -11,6 +12,7 @@ export function AppRouter() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<ScrollToTop />
|
||||
<SessionMonitor />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus } from 'lucide-react';
|
||||
import { AIMessage } from '@/hooks/useAIChat';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import OpenAI from 'openai';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, memo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Plus, Folder, Download, GitBranch, MoreVertical, Settings } from 'lucide-react';
|
||||
import { Plus, Folder, Download, GitBranch, MoreVertical, Settings, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
@@ -8,6 +8,7 @@ import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
import { AISettingsDialog } from '@/components/ai/AISettingsDialog';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
@@ -15,6 +16,66 @@ import type { Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface ProjectItemProps {
|
||||
project: Project;
|
||||
isSelected: boolean;
|
||||
onSelect: (project: Project) => void;
|
||||
}
|
||||
|
||||
const ProjectItem = memo(({ project, isSelected, onSelect }: ProjectItemProps) => {
|
||||
const navigate = useNavigate();
|
||||
const { hasRunningSessions } = useProjectSessionStatus(project.id);
|
||||
|
||||
const handleClick = () => {
|
||||
onSelect(project);
|
||||
navigate(`/project/${project.id}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group relative rounded-lg transition-all duration-200 hover:bg-gradient-to-r hover:from-primary/10 hover:to-accent/10",
|
||||
isSelected && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
|
||||
)}
|
||||
>
|
||||
<div className="w-full p-3 text-left text-sidebar-foreground">
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className="absolute inset-0"
|
||||
/>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex-shrink-0">
|
||||
{hasRunningSessions ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
) : (
|
||||
<Folder className="h-4 w-4 text-primary" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-start justify-between gap-2 flex-1 min-w-0">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="font-medium text-sm truncate mb-1">
|
||||
{project.name}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Star Button */}
|
||||
<div className="flex-shrink-0 -mt-1 -mr-1 relative">
|
||||
<StarButton
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
showToast={false}
|
||||
className="h-6 w-6 hover:bg-primary/20"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
ProjectItem.displayName = 'ProjectItem';
|
||||
|
||||
interface ProjectSidebarProps {
|
||||
selectedProject: Project | null;
|
||||
onSelectProject: (project: Project | null) => void;
|
||||
@@ -161,7 +222,8 @@ export function ProjectSidebar({
|
||||
Shakespeare
|
||||
</h1>
|
||||
</button>
|
||||
<DropdownMenu>
|
||||
<div className="flex items-center gap-1">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 hover:bg-primary/10">
|
||||
<MoreVertical className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
@@ -192,7 +254,8 @@ export function ProjectSidebar({
|
||||
AI Settings
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -229,45 +292,12 @@ export function ProjectSidebar({
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{sortedProjects.map((project) => (
|
||||
<div
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
className={cn(
|
||||
"group relative rounded-lg transition-all duration-200 hover:bg-gradient-to-r hover:from-primary/10 hover:to-accent/10",
|
||||
selectedProject?.id === project.id && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
|
||||
)}
|
||||
>
|
||||
<div className="w-full p-3 text-left text-sidebar-foreground">
|
||||
<button
|
||||
onClick={() => {
|
||||
onSelectProject(project);
|
||||
navigate(`/project/${project.id}`);
|
||||
}}
|
||||
className="absolute inset-0"
|
||||
/>
|
||||
<div className="flex items-center gap-3">
|
||||
<Folder className="h-4 w-4 text-primary flex-shrink-0" />
|
||||
<div className="flex items-start justify-between gap-2 flex-1 min-w-0">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="font-medium text-sm truncate">
|
||||
{project.name}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Star Button */}
|
||||
<div className="flex-shrink-0 -mt-1 -mr-1 relative">
|
||||
<StarButton
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
showToast={false}
|
||||
className="h-6 w-6 hover:bg-primary/20"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
project={project}
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ReactNode, useMemo, useEffect } from 'react';
|
||||
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
|
||||
import { SessionManager } from '@/lib/SessionManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
|
||||
interface SessionManagerProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider that creates and manages the global session manager instance
|
||||
*/
|
||||
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { settings } = useAISettings();
|
||||
|
||||
const sessionManager = useMemo(() => {
|
||||
return new SessionManager(fs, settings);
|
||||
}, [fs, settings]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
// Fire and forget cleanup - we don't need to await in useEffect cleanup
|
||||
sessionManager.cleanup().catch(error => {
|
||||
console.warn('Failed to cleanup session manager:', error);
|
||||
});
|
||||
};
|
||||
}, [sessionManager]);
|
||||
|
||||
return (
|
||||
<SessionManagerContext.Provider value={sessionManager}>
|
||||
{children}
|
||||
</SessionManagerContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
|
||||
/**
|
||||
* Global component that monitors AI sessions and shows notifications
|
||||
* when sessions complete in the background
|
||||
*/
|
||||
export function SessionMonitor() {
|
||||
const sessionManager = useSessionManager();
|
||||
const { toast } = useToast();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const previousLoadingStates = useRef<Map<string, boolean>>(new Map());
|
||||
|
||||
useEffect(() => {
|
||||
const handleLoadingChanged = (sessionId: string, isLoading: boolean) => {
|
||||
const wasLoading = previousLoadingStates.current.get(sessionId);
|
||||
previousLoadingStates.current.set(sessionId, isLoading);
|
||||
|
||||
// If session just finished loading (was loading, now not loading)
|
||||
if (wasLoading && !isLoading) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (!session) return;
|
||||
|
||||
// Check if user is currently viewing this project
|
||||
const currentProjectId = location.pathname.split('/')[2]; // /project/{projectId}
|
||||
const isCurrentProject = session.projectId === currentProjectId;
|
||||
|
||||
// Only show notification if user is not currently viewing this project
|
||||
if (!isCurrentProject) {
|
||||
toast({
|
||||
title: "AI Session Complete",
|
||||
description: `Finished working on ${session.projectName}`,
|
||||
action: (
|
||||
<button
|
||||
onClick={() => navigate(`/project/${session.projectId}`)}
|
||||
className="inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus-visible:ring-destructive"
|
||||
>
|
||||
View
|
||||
</button>
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSessionCreated = (sessionId: string) => {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
previousLoadingStates.current.set(sessionId, session.isLoading);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSessionDeleted = (sessionId: string) => {
|
||||
previousLoadingStates.current.delete(sessionId);
|
||||
};
|
||||
|
||||
// Initialize with current sessions
|
||||
sessionManager.getAllSessions().forEach(session => {
|
||||
previousLoadingStates.current.set(session.id, session.isLoading);
|
||||
});
|
||||
|
||||
// Subscribe to events
|
||||
sessionManager.on('loadingChanged', handleLoadingChanged);
|
||||
sessionManager.on('sessionCreated', handleSessionCreated);
|
||||
sessionManager.on('sessionDeleted', handleSessionDeleted);
|
||||
|
||||
return () => {
|
||||
sessionManager.off('loadingChanged', handleLoadingChanged);
|
||||
sessionManager.off('sessionCreated', handleSessionCreated);
|
||||
sessionManager.off('sessionDeleted', handleSessionDeleted);
|
||||
};
|
||||
}, [sessionManager, toast, navigate, location.pathname]);
|
||||
|
||||
// This component doesn't render anything
|
||||
return null;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { useFS } from '@/hooks/useFS';
|
||||
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { useAIChat } from '@/hooks/useAIChat';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
|
||||
|
||||
@@ -310,7 +311,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
streamingMessage.content ? (
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage}
|
||||
message={streamingMessage as AIMessage}
|
||||
isCurrentlyLoading
|
||||
/>
|
||||
) : (
|
||||
@@ -329,7 +330,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
<div className="flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin flex-shrink-0" />
|
||||
<span className="font-medium">
|
||||
Running {streamingMessage.tool_calls[0].function.name}...
|
||||
Running {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createContext } from 'react';
|
||||
import type { SessionManager } from '@/lib/SessionManager';
|
||||
|
||||
export const SessionManagerContext = createContext<SessionManager | null>(null);
|
||||
+160
-349
@@ -1,392 +1,202 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import OpenAI from 'openai';
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import type { SessionState, SessionConfig, AIMessage } from '@/lib/SessionManager';
|
||||
import type OpenAI from 'openai';
|
||||
import type { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
// Use OpenAI's native message type
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
|
||||
export interface StreamingMessage {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
}
|
||||
|
||||
interface UseAIChatOptions {
|
||||
interface UseAIChatSessionOptions {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools?: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
maxSteps?: number;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
}
|
||||
|
||||
interface StreamingMessage {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook that provides AI chat functionality using the global session manager.
|
||||
* Sessions persist and can run in the background when switching between projects.
|
||||
*/
|
||||
export function useAIChat({
|
||||
projectId,
|
||||
projectName,
|
||||
tools = {},
|
||||
customTools = {},
|
||||
systemPrompt,
|
||||
onUpdateMetadata,
|
||||
maxSteps = 50
|
||||
}: UseAIChatOptions) {
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [sessionName, setSessionName] = useState<string>('');
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const { settings, isConfigured, addRecentlyUsedModel } = useAISettings();
|
||||
const { fs } = useFS();
|
||||
maxSteps = 50,
|
||||
onUpdateMetadata
|
||||
}: UseAIChatSessionOptions) {
|
||||
const sessionManager = useSessionManager();
|
||||
const { isConfigured } = useAISettings();
|
||||
const [sessionId, setSessionId] = useState<string>('');
|
||||
const [sessionState, setSessionState] = useState<SessionState | null>(null);
|
||||
|
||||
// Save all messages to history
|
||||
const saveMessagesToHistory = useCallback(async (allMessages: AIMessage[]) => {
|
||||
if (!sessionName) return;
|
||||
// Generate consistent session ID for this project
|
||||
const generatedSessionId = useMemo(() => {
|
||||
return `session-${projectId}`;
|
||||
}, [projectId]);
|
||||
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
await dotAI.setHistory(sessionName, allMessages);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save messages to history:', error);
|
||||
// Initialize session
|
||||
useEffect(() => {
|
||||
const initSession = async () => {
|
||||
// Check if there's already an active session for this project
|
||||
const existingSessions = sessionManager.getProjectSessions(projectId);
|
||||
|
||||
if (existingSessions.length > 0) {
|
||||
// Use the most recent session for this project
|
||||
const mostRecent = existingSessions.sort((a, b) =>
|
||||
b.lastActivity.getTime() - a.lastActivity.getTime()
|
||||
)[0];
|
||||
|
||||
setSessionId(mostRecent.id);
|
||||
setSessionState(mostRecent);
|
||||
|
||||
// Get the latest session state immediately
|
||||
const currentSession = sessionManager.getSession(mostRecent.id);
|
||||
if (currentSession) {
|
||||
setSessionState(currentSession);
|
||||
}
|
||||
} else {
|
||||
// Create new session
|
||||
const config: SessionConfig = {
|
||||
id: generatedSessionId,
|
||||
projectId,
|
||||
projectName,
|
||||
tools,
|
||||
customTools,
|
||||
systemPrompt,
|
||||
maxSteps
|
||||
};
|
||||
|
||||
const newSessionId = await sessionManager.createSession(config);
|
||||
setSessionId(newSessionId);
|
||||
|
||||
const newSession = sessionManager.getSession(newSessionId);
|
||||
if (newSession) {
|
||||
setSessionState(newSession);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
initSession();
|
||||
}, [sessionManager, projectId, projectName, tools, customTools, systemPrompt, maxSteps, generatedSessionId]);
|
||||
|
||||
|
||||
|
||||
// Subscribe to session events using shared hook
|
||||
useSessionSubscription('sessionUpdated', (updatedSessionId: string, state: SessionState) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Directly update state with the provided state object
|
||||
setSessionState({
|
||||
...state,
|
||||
messages: [...state.messages],
|
||||
streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
}, [fs, projectId, sessionName]);
|
||||
}, [sessionId]);
|
||||
|
||||
const addMessage = useCallback((message: AIMessage) => {
|
||||
setMessages(prev => {
|
||||
const newMessages = [...prev, message];
|
||||
// Save to history asynchronously with all messages
|
||||
saveMessagesToHistory(newMessages);
|
||||
return newMessages;
|
||||
});
|
||||
}, [saveMessagesToHistory]);
|
||||
useSessionSubscription('messageAdded', (updatedSessionId: string, _message: AIMessage) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => {
|
||||
const currentMessages = messagesToUse || messages;
|
||||
useSessionSubscription('streamingUpdate', (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
if (!isConfigured || isLoading || currentMessages.length === 0) return;
|
||||
|
||||
// Get the last message - it should be a user message
|
||||
const lastMessage = currentMessages[currentMessages.length - 1];
|
||||
if (lastMessage.role !== 'user') return;
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Create abort controller for this request
|
||||
abortControllerRef.current = new AbortController();
|
||||
|
||||
// Use all existing messages
|
||||
const modelMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [...currentMessages];
|
||||
|
||||
// Add system message if provided
|
||||
if (systemPrompt) {
|
||||
modelMessages.unshift({
|
||||
role: 'system',
|
||||
content: systemPrompt
|
||||
useSessionSubscription('loadingChanged', (updatedSessionId: string, isLoading: boolean) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
|
||||
// Parse provider and model
|
||||
const parsed = parseProviderModel(providerModel, settings.providers);
|
||||
const connectionConfig = parsed.connection;
|
||||
const modelName = parsed.model;
|
||||
|
||||
// Initialize OpenAI client with parsed connection
|
||||
const openai = new OpenAI({
|
||||
baseURL: connectionConfig.baseURL,
|
||||
apiKey: connectionConfig.apiKey,
|
||||
dangerouslyAllowBrowser: true
|
||||
});
|
||||
|
||||
// Update metadata
|
||||
if (onUpdateMetadata) {
|
||||
if (onUpdateMetadata && isLoading) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
|
||||
// Keep track of current messages for this conversation
|
||||
const conversationMessages = [...modelMessages];
|
||||
let stepCount = 0;
|
||||
|
||||
// Main loop for handling multiple steps with tool calls
|
||||
while (stepCount < maxSteps) {
|
||||
stepCount++;
|
||||
console.log(`AI Chat Step ${stepCount}/${maxSteps}`);
|
||||
|
||||
// Initialize streaming message
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: undefined
|
||||
});
|
||||
|
||||
// Prepare chat completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: modelName,
|
||||
messages: conversationMessages,
|
||||
tools: tools && Object.keys(tools).length > 0 ? Object.values(tools) : undefined,
|
||||
tool_choice: tools && Object.keys(tools).length > 0 ? 'auto' : undefined,
|
||||
stream: true
|
||||
};
|
||||
|
||||
// Generate streaming response
|
||||
const stream = await openai.chat.completions.create(completionOptions, {
|
||||
signal: abortControllerRef.current.signal
|
||||
});
|
||||
|
||||
let accumulatedContent = '';
|
||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||
let finishReason: string | null = null;
|
||||
let hasRecordedModel = false;
|
||||
|
||||
// Process the stream
|
||||
for await (const chunk of stream) {
|
||||
const delta = chunk.choices[0]?.delta;
|
||||
|
||||
// Track recently used model on first chunk
|
||||
if (!hasRecordedModel && providerModel) {
|
||||
addRecentlyUsedModel(providerModel);
|
||||
hasRecordedModel = true;
|
||||
}
|
||||
|
||||
if (delta?.content) {
|
||||
accumulatedContent += delta.content;
|
||||
setStreamingMessage(prev => prev ? {
|
||||
...prev,
|
||||
content: prev.content + delta.content
|
||||
} : {
|
||||
role: 'assistant',
|
||||
content: delta.content,
|
||||
tool_calls: undefined
|
||||
});
|
||||
}
|
||||
|
||||
if (delta?.tool_calls) {
|
||||
for (const toolCallDelta of delta.tool_calls) {
|
||||
const index = toolCallDelta.index;
|
||||
if (index !== undefined) {
|
||||
// Initialize tool call if it doesn't exist
|
||||
if (!accumulatedToolCalls[index]) {
|
||||
accumulatedToolCalls[index] = {
|
||||
id: toolCallDelta.id || '',
|
||||
type: 'function',
|
||||
function: {
|
||||
name: '',
|
||||
arguments: ''
|
||||
}
|
||||
} as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
}
|
||||
|
||||
// Update tool call properties
|
||||
if (toolCallDelta.id) {
|
||||
accumulatedToolCalls[index].id = toolCallDelta.id;
|
||||
}
|
||||
if (toolCallDelta.function?.name && accumulatedToolCalls[index].type === 'function') {
|
||||
(accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.name = toolCallDelta.function.name;
|
||||
}
|
||||
if (toolCallDelta.function?.arguments && accumulatedToolCalls[index].type === 'function') {
|
||||
(accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.arguments += toolCallDelta.function.arguments;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update streaming message with current tool calls
|
||||
setStreamingMessage(prev => prev ? {
|
||||
...prev,
|
||||
tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined
|
||||
} : {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined
|
||||
});
|
||||
}
|
||||
|
||||
if (chunk.choices[0]?.finish_reason) {
|
||||
finishReason = chunk.choices[0].finish_reason;
|
||||
}
|
||||
}
|
||||
|
||||
// Create final assistant message
|
||||
const assistantMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
};
|
||||
|
||||
// Clear streaming message and add final message
|
||||
setStreamingMessage(undefined);
|
||||
addMessage(assistantMessage);
|
||||
conversationMessages.push(assistantMessage);
|
||||
|
||||
// Check if we should stop (no tool calls or finish reason is "stop")
|
||||
if (finishReason === 'stop' || !accumulatedToolCalls || accumulatedToolCalls.length === 0) {
|
||||
console.log(`AI Chat completed after ${stepCount} steps. Finish reason: ${finishReason}`);
|
||||
break;
|
||||
}
|
||||
|
||||
// Handle tool calls if present
|
||||
if (accumulatedToolCalls && accumulatedToolCalls.length > 0) {
|
||||
console.log(`Processing ${accumulatedToolCalls.length} tool calls in step ${stepCount}`);
|
||||
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (toolCall.type !== 'function') continue;
|
||||
|
||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
const toolName = functionToolCall.function.name;
|
||||
const tool = customTools[toolName];
|
||||
|
||||
if (!tool) {
|
||||
// Tool not found
|
||||
const toolNotFoundMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Tool ${toolName} not found`,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolNotFoundMessage);
|
||||
conversationMessages.push(toolNotFoundMessage);
|
||||
continue;
|
||||
}
|
||||
|
||||
let toolArgs: unknown;
|
||||
try {
|
||||
const json = JSON.parse(functionToolCall.function.arguments);
|
||||
toolArgs = tool.inputSchema.parse(json);
|
||||
} catch (parseError) {
|
||||
console.error(`Failed to parse tool arguments for ${toolName}:`, parseError);
|
||||
|
||||
const toolErrorMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Error parsing arguments for tool ${toolName}: ${parseError instanceof Error ? parseError.message : 'Unknown error'}`,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolErrorMessage);
|
||||
conversationMessages.push(toolErrorMessage);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Executing tool: ${toolName}`, toolArgs);
|
||||
|
||||
// Execute the custom tool
|
||||
const content = await tool.execute(toolArgs);
|
||||
|
||||
// Add tool result message
|
||||
const toolResultMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolResultMessage);
|
||||
conversationMessages.push(toolResultMessage);
|
||||
} catch (toolError) {
|
||||
console.error(`Tool execution error for ${toolName}:`, toolError);
|
||||
|
||||
const toolErrorMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Error executing tool ${toolName}: ${toolError instanceof Error ? toolError.message : 'Unknown error'}`,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolErrorMessage);
|
||||
conversationMessages.push(toolErrorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we reached maxSteps, log a warning
|
||||
if (stepCount >= maxSteps) {
|
||||
console.warn(`AI Chat reached maximum steps (${maxSteps}). Conversation may be incomplete.`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
|
||||
// Clear any streaming message on error
|
||||
setStreamingMessage(undefined);
|
||||
|
||||
// Add error message
|
||||
const errorMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.'
|
||||
};
|
||||
|
||||
addMessage(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
}, [isConfigured, isLoading, addMessage, messages, settings.providers, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps, addRecentlyUsedModel]);
|
||||
}, [sessionId, sessionManager, onUpdateMetadata, projectName]);
|
||||
|
||||
// Load message history when component mounts or projectId changes
|
||||
useEffect(() => {
|
||||
const loadMessageHistory = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
|
||||
if (lastSession) {
|
||||
setMessages(lastSession.messages);
|
||||
setSessionName(lastSession.sessionName);
|
||||
} else {
|
||||
// No history to load, start fresh
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load message history:', error);
|
||||
// Start fresh on any error
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
};
|
||||
|
||||
loadMessageHistory();
|
||||
}, [projectId, fs]);
|
||||
// Derived state
|
||||
const messages = sessionState?.messages || [];
|
||||
const streamingMessage: StreamingMessage | undefined = sessionState?.streamingMessage;
|
||||
const isLoading = sessionState?.isLoading || false;
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (content: string, providerModel: string) => {
|
||||
if (!isConfigured || isLoading) return;
|
||||
if (!sessionId) return;
|
||||
await sessionManager.sendMessage(sessionId, content, providerModel);
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
// Add user message
|
||||
const userMessage: AIMessage = {
|
||||
role: 'user',
|
||||
content
|
||||
};
|
||||
const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => {
|
||||
if (!sessionId) return;
|
||||
|
||||
// Calculate the new messages array that will exist after the state update
|
||||
const newMessages = [...messages, userMessage];
|
||||
// If specific messages are provided, we need to update the session first
|
||||
if (messagesToUse) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
// Replace session messages with provided messages
|
||||
session.messages = [...messagesToUse];
|
||||
|
||||
// Add the message to state
|
||||
addMessage(userMessage);
|
||||
// Manually trigger session update
|
||||
sessionManager.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
}
|
||||
|
||||
// Start generation with the new messages array directly
|
||||
startGeneration(providerModel, newMessages);
|
||||
}, [isConfigured, isLoading, messages, addMessage, startGeneration]);
|
||||
await sessionManager.startGeneration(sessionId, providerModel);
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
}
|
||||
setStreamingMessage(undefined);
|
||||
}, []);
|
||||
if (!sessionId) return;
|
||||
sessionManager.stopGeneration(sessionId);
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
// Start a new session when clearing messages
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}, []);
|
||||
const addMessage = useCallback(async (message: AIMessage) => {
|
||||
if (!sessionId) return;
|
||||
await sessionManager.addMessage(sessionId, message);
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
const startNewSession = useCallback(() => {
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}, []);
|
||||
const startNewSession = useCallback(async () => {
|
||||
if (!sessionId) return;
|
||||
await sessionManager.startNewSession(sessionId);
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
const clearMessages = useCallback(async () => {
|
||||
// Alias for startNewSession for backward compatibility
|
||||
await startNewSession();
|
||||
}, [startNewSession]);
|
||||
|
||||
return {
|
||||
messages,
|
||||
@@ -398,6 +208,7 @@ export function useAIChat({
|
||||
clearMessages,
|
||||
startNewSession,
|
||||
addMessage,
|
||||
isConfigured
|
||||
isConfigured,
|
||||
sessionId
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
|
||||
/**
|
||||
* Hook to get session status for a specific project
|
||||
*/
|
||||
export function useProjectSessionStatus(projectId: string) {
|
||||
const sessionManager = useSessionManager();
|
||||
const [hasActiveSessions, setHasActiveSessions] = useState(false);
|
||||
const [hasRunningSessions, setHasRunningSessions] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const updateStatus = () => {
|
||||
const projectSessions = sessionManager.getProjectSessions(projectId);
|
||||
const runningSessions = projectSessions.filter(session => session.isLoading);
|
||||
|
||||
setHasActiveSessions(projectSessions.length > 0);
|
||||
setHasRunningSessions(runningSessions.length > 0);
|
||||
};
|
||||
|
||||
// Initial update
|
||||
updateStatus();
|
||||
|
||||
// Subscribe to session changes
|
||||
sessionManager.on('sessionCreated', updateStatus);
|
||||
sessionManager.on('sessionUpdated', updateStatus);
|
||||
sessionManager.on('sessionDeleted', updateStatus);
|
||||
sessionManager.on('loadingChanged', updateStatus);
|
||||
|
||||
return () => {
|
||||
sessionManager.off('sessionCreated', updateStatus);
|
||||
sessionManager.off('sessionUpdated', updateStatus);
|
||||
sessionManager.off('sessionDeleted', updateStatus);
|
||||
sessionManager.off('loadingChanged', updateStatus);
|
||||
};
|
||||
}, [sessionManager, projectId]);
|
||||
|
||||
return {
|
||||
hasActiveSessions,
|
||||
hasRunningSessions
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useContext } from 'react';
|
||||
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
|
||||
|
||||
/**
|
||||
* Hook to access the global session manager
|
||||
*/
|
||||
export function useSessionManager() {
|
||||
const sessionManager = useContext(SessionManagerContext);
|
||||
|
||||
if (!sessionManager) {
|
||||
throw new Error('useSessionManager must be used within a SessionManagerProvider');
|
||||
}
|
||||
|
||||
return sessionManager;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useSessionManager } from './useSessionManager';
|
||||
import type { SessionManagerEvents } from '@/lib/SessionManager';
|
||||
|
||||
/**
|
||||
* Custom hook for subscribing to SessionManager events with automatic cleanup
|
||||
*/
|
||||
export function useSessionSubscription<K extends keyof SessionManagerEvents>(
|
||||
event: K,
|
||||
handler: SessionManagerEvents[K],
|
||||
deps: React.DependencyList = []
|
||||
): void {
|
||||
const sessionManager = useSessionManager();
|
||||
|
||||
// Use a ref to track the current handler and deps
|
||||
const handlerRef = useRef(handler);
|
||||
const depsRef = useRef(deps);
|
||||
|
||||
// Update refs when handler or deps change
|
||||
useEffect(() => {
|
||||
handlerRef.current = handler;
|
||||
depsRef.current = deps;
|
||||
}, [handler, deps]);
|
||||
|
||||
useEffect(() => {
|
||||
const currentHandler = handlerRef.current;
|
||||
sessionManager.on(event, currentHandler);
|
||||
|
||||
return () => {
|
||||
sessionManager.off(event, currentHandler);
|
||||
};
|
||||
}, [sessionManager, event, deps]);
|
||||
}
|
||||
+3
-3
@@ -4,9 +4,9 @@ import type { JSRuntimeFS } from "./JSRuntime";
|
||||
|
||||
/** AI message history manager and .ai directory utilities */
|
||||
export class DotAI {
|
||||
private readonly fs: JSRuntimeFS;
|
||||
private readonly historyDir: string;
|
||||
private readonly workingDir: string;
|
||||
readonly fs: JSRuntimeFS;
|
||||
readonly historyDir: string;
|
||||
readonly workingDir: string;
|
||||
|
||||
constructor(fs: JSRuntimeFS, workingDir: string = "/") {
|
||||
this.fs = fs;
|
||||
|
||||
@@ -0,0 +1,583 @@
|
||||
import OpenAI from 'openai';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import { DotAI } from './DotAI';
|
||||
import { parseProviderModel } from './parseProviderModel';
|
||||
import type { Tool } from './tools/Tool';
|
||||
import { join } from '@std/path';
|
||||
|
||||
// Simple debounce utility
|
||||
const debounce = <T extends (...args: unknown[]) => void>(
|
||||
func: T,
|
||||
wait: number
|
||||
): ((...args: Parameters<T>) => void) => {
|
||||
let timeout: NodeJS.Timeout;
|
||||
return (...args: Parameters<T>) => {
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => func(...args), wait);
|
||||
};
|
||||
};
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
|
||||
export interface SessionConfig {
|
||||
id: string;
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
maxSteps?: number;
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
id: string;
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
messages: AIMessage[];
|
||||
streamingMessage?: {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
};
|
||||
isLoading: boolean;
|
||||
sessionName: string;
|
||||
lastActivity: Date;
|
||||
abortController?: AbortController;
|
||||
}
|
||||
|
||||
export interface SessionManagerEvents {
|
||||
sessionCreated: (sessionId: string) => void;
|
||||
sessionUpdated: (sessionId: string, state: SessionState) => void;
|
||||
sessionDeleted: (sessionId: string) => void;
|
||||
messageAdded: (sessionId: string, message: AIMessage) => void;
|
||||
streamingUpdate: (sessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||
loadingChanged: (sessionId: string, isLoading: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Global session manager that handles multiple AI chat sessions running concurrently.
|
||||
* Sessions can run in the background without interruption when switching between projects.
|
||||
*/
|
||||
export class SessionManager {
|
||||
private sessions = new Map<string, SessionState>();
|
||||
private sessionConfigs = new Map<string, SessionConfig>();
|
||||
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
|
||||
private fs: JSRuntimeFS;
|
||||
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> };
|
||||
|
||||
// Performance constants
|
||||
private readonly MAX_SESSIONS = 50;
|
||||
private readonly MAX_SESSION_AGE = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
private debouncedPersist = debounce(() => this.persistSessions(), 1000);
|
||||
private dotAI: DotAI;
|
||||
|
||||
constructor(fs: JSRuntimeFS, aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> }) {
|
||||
this.fs = fs;
|
||||
this.aiSettings = aiSettings;
|
||||
this.dotAI = new DotAI(fs, '/');
|
||||
|
||||
// Load persisted sessions on initialization
|
||||
this.loadPersistedSessions().catch(error => {
|
||||
console.warn('Failed to load sessions during initialization:', error);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new session for a project
|
||||
*/
|
||||
async createSession(config: SessionConfig): Promise<string> {
|
||||
const sessionState: SessionState = {
|
||||
id: config.id,
|
||||
projectId: config.projectId,
|
||||
projectName: config.projectName,
|
||||
messages: [],
|
||||
isLoading: false,
|
||||
sessionName: DotAI.generateSessionName(),
|
||||
lastActivity: new Date(),
|
||||
};
|
||||
|
||||
// Try to load existing history
|
||||
try {
|
||||
const dotAI = new DotAI(this.fs, `/projects/${config.projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
if (lastSession) {
|
||||
sessionState.messages = lastSession.messages;
|
||||
sessionState.sessionName = lastSession.sessionName;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load session history:', error);
|
||||
}
|
||||
|
||||
this.sessions.set(config.id, sessionState);
|
||||
this.sessionConfigs.set(config.id, config);
|
||||
|
||||
this.persistSessions();
|
||||
this.emit('sessionCreated', config.id);
|
||||
this.emit('sessionUpdated', config.id, sessionState);
|
||||
|
||||
return config.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a session by ID
|
||||
*/
|
||||
getSession(sessionId: string): SessionState | undefined {
|
||||
return this.sessions.get(sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all active sessions
|
||||
*/
|
||||
getAllSessions(): SessionState[] {
|
||||
return Array.from(this.sessions.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get sessions for a specific project
|
||||
*/
|
||||
getProjectSessions(projectId: string): SessionState[] {
|
||||
return Array.from(this.sessions.values()).filter(
|
||||
session => session.projectId === projectId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a session
|
||||
*/
|
||||
async deleteSession(sessionId: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
session?.abortController?.abort();
|
||||
|
||||
this.sessions.delete(sessionId);
|
||||
this.sessionConfigs.delete(sessionId);
|
||||
|
||||
await this.persistSessions();
|
||||
this.emit('sessionDeleted', sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all sessions for a project
|
||||
*/
|
||||
async deleteProjectSessions(projectId: string): Promise<void> {
|
||||
await Promise.all(
|
||||
this.getProjectSessions(projectId).map(session => this.deleteSession(session.id))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a message to a session
|
||||
*/
|
||||
async addMessage(sessionId: string, message: AIMessage): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
|
||||
session.messages.push(message);
|
||||
session.lastActivity = new Date();
|
||||
|
||||
await this.saveSessionHistory(sessionId);
|
||||
this.debouncedPersist();
|
||||
this.cleanupOldSessions();
|
||||
|
||||
this.emit('messageAdded', sessionId, message);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message and start AI generation
|
||||
*/
|
||||
async sendMessage(sessionId: string, content: string, providerModel: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
const config = this.sessionConfigs.get(sessionId);
|
||||
|
||||
if (!session || !config || session.isLoading) return;
|
||||
|
||||
await this.addMessage(sessionId, { role: 'user', content });
|
||||
await this.startGeneration(sessionId, providerModel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start AI generation for a session
|
||||
*/
|
||||
async startGeneration(sessionId: string, providerModel: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
const config = this.sessionConfigs.get(sessionId);
|
||||
|
||||
if (!session || !config || session.isLoading || session.messages.length === 0) return;
|
||||
|
||||
// Check if last message is from user
|
||||
const lastMessage = session.messages[session.messages.length - 1];
|
||||
if (lastMessage.role !== 'user') return;
|
||||
|
||||
session.isLoading = true;
|
||||
session.abortController = new AbortController();
|
||||
session.lastActivity = new Date();
|
||||
|
||||
this.emit('loadingChanged', sessionId, true);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
|
||||
try {
|
||||
// Parse provider and model
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const connectionConfig = parsed.connection;
|
||||
const modelName = parsed.model;
|
||||
|
||||
// Initialize OpenAI client
|
||||
const openai = new OpenAI({
|
||||
baseURL: connectionConfig.baseURL,
|
||||
apiKey: connectionConfig.apiKey,
|
||||
dangerouslyAllowBrowser: true
|
||||
});
|
||||
|
||||
// Prepare messages for AI
|
||||
const modelMessages: AIMessage[] = [...session.messages];
|
||||
if (config.systemPrompt) {
|
||||
modelMessages.unshift({
|
||||
role: 'system',
|
||||
content: config.systemPrompt
|
||||
});
|
||||
}
|
||||
|
||||
const conversationMessages = [...modelMessages];
|
||||
let stepCount = 0;
|
||||
const maxSteps = config.maxSteps || 50;
|
||||
|
||||
// Main AI generation loop
|
||||
while (stepCount < maxSteps && session.isLoading) {
|
||||
stepCount++;
|
||||
|
||||
// Initialize streaming message
|
||||
session.streamingMessage = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
|
||||
// Prepare completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: modelName,
|
||||
messages: conversationMessages,
|
||||
tools: config.tools && Object.keys(config.tools).length > 0 ? Object.values(config.tools) : undefined,
|
||||
tool_choice: config.tools && Object.keys(config.tools).length > 0 ? 'auto' : undefined,
|
||||
stream: true
|
||||
};
|
||||
|
||||
// Generate streaming response
|
||||
const stream = await openai.chat.completions.create(completionOptions, {
|
||||
signal: session.abortController?.signal
|
||||
});
|
||||
|
||||
let accumulatedContent = '';
|
||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||
let finishReason: string | null = null;
|
||||
|
||||
// Process the stream
|
||||
for await (const chunk of stream) {
|
||||
// Check if session was cancelled
|
||||
if (!session.isLoading) break;
|
||||
|
||||
const delta = chunk.choices[0]?.delta;
|
||||
|
||||
if (delta?.content) {
|
||||
accumulatedContent += delta.content;
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.content += delta.content;
|
||||
this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
}
|
||||
|
||||
if (delta?.tool_calls) {
|
||||
for (const toolCallDelta of delta.tool_calls) {
|
||||
const index = toolCallDelta.index;
|
||||
if (index === undefined) continue;
|
||||
|
||||
accumulatedToolCalls[index] ??= {
|
||||
id: '',
|
||||
type: 'function',
|
||||
function: { name: '', arguments: '' }
|
||||
};
|
||||
|
||||
const toolCall = accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
if (toolCallDelta.id) toolCall.id = toolCallDelta.id;
|
||||
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
|
||||
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
|
||||
}
|
||||
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
|
||||
this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.choices[0]?.finish_reason) {
|
||||
finishReason = chunk.choices[0].finish_reason;
|
||||
}
|
||||
}
|
||||
|
||||
// Create final assistant message
|
||||
const assistantMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
};
|
||||
|
||||
// Clear streaming message and add final message
|
||||
session.streamingMessage = undefined;
|
||||
await this.addMessage(sessionId, assistantMessage);
|
||||
conversationMessages.push(assistantMessage);
|
||||
|
||||
// Check if we should stop
|
||||
if (finishReason === 'stop' || !accumulatedToolCalls || accumulatedToolCalls.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Handle tool calls
|
||||
if (accumulatedToolCalls?.length) {
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (toolCall.type !== 'function') continue;
|
||||
|
||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
const toolName = functionToolCall.function.name;
|
||||
const tool = config.customTools[toolName];
|
||||
|
||||
if (!tool) {
|
||||
await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, `Tool ${toolName} not found`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const toolArgs = tool.inputSchema.parse(JSON.parse(functionToolCall.function.arguments));
|
||||
const content = await tool.execute(toolArgs);
|
||||
await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, content);
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
|
||||
await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, `Error with tool ${toolName}: ${errorMsg}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('AI generation error:', error);
|
||||
|
||||
// Handle different error types
|
||||
if (error?.name === 'AbortError') return; // User cancelled
|
||||
|
||||
let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
|
||||
const errorMsg = error?.message || '';
|
||||
|
||||
if (error?.name === 'TypeError' && errorMsg.includes('fetch')) {
|
||||
errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
|
||||
} else if (errorMsg.includes('API key')) {
|
||||
errorMessage = 'Authentication error: Please check your API key in AI settings.';
|
||||
} else if (errorMsg.includes('rate limit')) {
|
||||
errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
|
||||
} else if (errorMsg) {
|
||||
errorMessage = `AI service error: ${errorMsg}`;
|
||||
}
|
||||
|
||||
await this.addMessage(sessionId, { role: 'assistant', content: errorMessage });
|
||||
} finally {
|
||||
session.isLoading = false;
|
||||
session.streamingMessage = undefined;
|
||||
session.abortController = undefined;
|
||||
|
||||
this.emit('loadingChanged', sessionId, false);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop AI generation for a session
|
||||
*/
|
||||
stopGeneration(sessionId: string): void {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
|
||||
session.abortController?.abort();
|
||||
session.isLoading = false;
|
||||
session.streamingMessage = undefined;
|
||||
session.abortController = undefined;
|
||||
|
||||
this.emit('loadingChanged', sessionId, false);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old sessions to prevent memory bloat
|
||||
*/
|
||||
private cleanupOldSessions(): void {
|
||||
const now = Date.now();
|
||||
|
||||
// Delete old sessions
|
||||
for (const [id, session] of this.sessions) {
|
||||
if (now - session.lastActivity.getTime() > this.MAX_SESSION_AGE) {
|
||||
this.deleteSession(id);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete oldest sessions if we have too many
|
||||
if (this.sessions.size > this.MAX_SESSIONS) {
|
||||
Array.from(this.sessions.entries())
|
||||
.sort(([, a], [, b]) => a.lastActivity.getTime() - b.lastActivity.getTime())
|
||||
.slice(0, this.sessions.size - this.MAX_SESSIONS)
|
||||
.forEach(([id]) => this.deleteSession(id));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new session (clear messages but keep configuration)
|
||||
*/
|
||||
async startNewSession(sessionId: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
|
||||
this.stopGeneration(sessionId);
|
||||
|
||||
session.messages = [];
|
||||
session.streamingMessage = undefined;
|
||||
session.sessionName = DotAI.generateSessionName();
|
||||
session.lastActivity = new Date();
|
||||
|
||||
this.debouncedPersist();
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to add tool messages and update conversation
|
||||
*/
|
||||
private async addToolMessage(sessionId: string, conversationMessages: AIMessage[], toolCallId: string, content: string): Promise<void> {
|
||||
const toolMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content,
|
||||
tool_call_id: toolCallId
|
||||
};
|
||||
|
||||
await this.addMessage(sessionId, toolMessage);
|
||||
conversationMessages.push(toolMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save session history to file
|
||||
*/
|
||||
private async saveSessionHistory(sessionId: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
|
||||
try {
|
||||
const dotAI = new DotAI(this.fs, `/projects/${session.projectId}`);
|
||||
await dotAI.setHistory(session.sessionName, session.messages);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save session history:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simplified event system
|
||||
*/
|
||||
on<K extends keyof SessionManagerEvents>(event: K, listener: SessionManagerEvents[K]): void {
|
||||
if (!this.listeners[event]) this.listeners[event] = new Set();
|
||||
this.listeners[event]!.add(listener as (...args: unknown[]) => void);
|
||||
}
|
||||
|
||||
off<K extends keyof SessionManagerEvents>(event: K, listener: SessionManagerEvents[K]): void {
|
||||
this.listeners[event]?.delete(listener as (...args: unknown[]) => void);
|
||||
}
|
||||
|
||||
emit<K extends keyof SessionManagerEvents>(event: K, ...args: Parameters<SessionManagerEvents[K]>): void {
|
||||
this.listeners[event]?.forEach(listener => {
|
||||
try {
|
||||
listener(...args);
|
||||
} catch (error) {
|
||||
console.error('Event listener error:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save session states using DotAI for persistence
|
||||
*/
|
||||
private async persistSessions(): Promise<void> {
|
||||
try {
|
||||
if (!this.dotAI.fs?.writeFile) return;
|
||||
|
||||
const sessionData = {
|
||||
sessions: Array.from(this.sessions.entries()).map(([id, session]) => ({
|
||||
id,
|
||||
session: {
|
||||
...session,
|
||||
isLoading: false,
|
||||
streamingMessage: undefined,
|
||||
abortController: undefined
|
||||
}
|
||||
})),
|
||||
configs: Array.from(this.sessionConfigs.entries()),
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
|
||||
// Ensure .ai directory exists before writing
|
||||
const aiDir = join(this.dotAI.workingDir, '.ai');
|
||||
try {
|
||||
await this.dotAI.fs.mkdir(aiDir, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist, continue
|
||||
}
|
||||
|
||||
await this.dotAI.fs.writeFile(
|
||||
join(aiDir, 'sessions.json'),
|
||||
JSON.stringify(sessionData)
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn('Failed to persist sessions:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load persisted sessions using DotAI
|
||||
*/
|
||||
private async loadPersistedSessions(): Promise<void> {
|
||||
try {
|
||||
if (!this.dotAI.fs?.readFile) return;
|
||||
|
||||
const sessionsPath = join(this.dotAI.workingDir, '.ai', 'sessions.json');
|
||||
|
||||
try {
|
||||
const sessionsJson = await this.dotAI.fs.readFile(sessionsPath, 'utf8');
|
||||
const sessionData = JSON.parse(sessionsJson);
|
||||
|
||||
// Restore sessions
|
||||
sessionData.sessions?.forEach(({ id, session }: { id: string; session: Omit<SessionState, 'lastActivity'> & { lastActivity: string } }) => {
|
||||
this.sessions.set(id, {
|
||||
...session,
|
||||
lastActivity: new Date(session.lastActivity)
|
||||
});
|
||||
});
|
||||
|
||||
// Restore configs
|
||||
sessionData.configs?.forEach(([id, config]: [string, SessionConfig]) => {
|
||||
this.sessionConfigs.set(id, config);
|
||||
});
|
||||
} catch {
|
||||
// File doesn't exist or is invalid - start fresh
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load sessions:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup - stop all sessions and clear data
|
||||
*/
|
||||
async cleanup(): Promise<void> {
|
||||
await this.persistSessions();
|
||||
|
||||
this.sessions.forEach((_, sessionId) => this.stopGeneration(sessionId));
|
||||
|
||||
this.sessions.clear();
|
||||
this.sessionConfigs.clear();
|
||||
this.listeners = {};
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -9,7 +9,7 @@ import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import type { AIMessage } from '@/hooks/useAIChat';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
|
||||
@@ -18,6 +18,7 @@ import { useJSRuntime } from '@/hooks/useJSRuntime';
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
|
||||
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
|
||||
import { bytesToHex } from 'nostr-tools/utils';
|
||||
import { buildProject } from "@/lib/build";
|
||||
@@ -189,7 +190,7 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
// when isAILoading becomes true after user interaction
|
||||
};
|
||||
|
||||
const handleProjectDeleted = () => {
|
||||
const handleProjectDeleted = async () => {
|
||||
setProject(null);
|
||||
navigate('/');
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ import { AppConfig } from '@/contexts/AppContext';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
|
||||
interface TestAppProps {
|
||||
children: React.ReactNode;
|
||||
@@ -41,9 +42,11 @@ export function TestApp({ children }: TestAppProps) {
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<NostrLoginProvider storageKey='test-login'>
|
||||
<NostrProvider>
|
||||
<BrowserRouter>
|
||||
{children}
|
||||
</BrowserRouter>
|
||||
<SessionManagerProvider>
|
||||
<BrowserRouter>
|
||||
{children}
|
||||
</BrowserRouter>
|
||||
</SessionManagerProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
Reference in new issue
Block a user