YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
Meeting 022125 screenpipe (#1448)
Matthew Diakonov178215cb6151
diff --git a/pipes/meeting/next.config.ts b/pipes/meeting/next.config.tsindex 3f33dd91c..0c88b0d1d 100644--- a/pipes/meeting/next.config.ts+++ b/pipes/meeting/next.config.ts@@ -18,8 +18,8 @@ const nextConfig: NextConfig = {key: 'Content-Security-Policy',value: ["default-src 'self'",- "connect-src 'self' wss://api.deepgram.com https://*.posthog.com http://localhost:* ipc:* https://ai-proxy.i-f9f.workers.dev https://api.openai.com",- "script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'",+ "connect-src 'self' ws://localhost:* wss://api.deepgram.com https://*.posthog.com http://localhost:* ipc:* https://ai-proxy.i-f9f.workers.dev https://api.openai.com wss://*.ngrok.app",+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' https://*.posthog.com","style-src 'self' 'unsafe-inline'","img-src 'self' data: blob:","font-src 'self' data:"diff --git a/pipes/meeting/package-lock.json b/pipes/meeting/package-lock.jsonindex 42ac632e5..0c948f612 100644--- a/pipes/meeting/package-lock.json+++ b/pipes/meeting/package-lock.json@@ -1,13 +1,15 @@{"name": "meeting",- "version": "0.1.1",+ "version": "0.1.3","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "meeting",- "version": "0.1.1",+ "version": "0.1.3","dependencies": {+ "@discordjs/rest": "^2.4.3",+ "@discordjs/voice": "^0.18.0","@radix-ui/react-accordion": "^1.2.2","@radix-ui/react-checkbox": "^1.1.3","@radix-ui/react-collapsible": "^1.1.2",@@ -24,7 +26,7 @@"@radix-ui/react-tabs": "^1.1.2","@radix-ui/react-toast": "^1.2.5","@radix-ui/react-tooltip": "^1.1.5",- "@screenpipe/browser": "0.1.24",+ "@screenpipe/browser": "^0.1.31","@screenpipe/js": "1.0.7","@tauri-apps/api": "^2.2.0","@tiptap/extension-color": "^2.2.4",@@ -36,28 +38,38 @@"@types/lodash": "^4.17.13","@types/react-syntax-highlighter": "^15.5.13","@vercel/analytics": "^1.4.1",+ "bufferutil": "^4.0.9","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "1.0.0","date-fns": "^3.3.1",+ "diff": "^7.0.0",+ "discord.js": "^14.18.0",+ "erlpack": "^0.1.4","framer-motion": "^12.0.11","localforage": "^1.10.0","lodash": "^4.17.21","lucide-react": "^0.468.0","next": "15.1.0","openai": "^4.76.3",- "posthog-js": "^1.215.1",+ "p-throttle": "^7.0.0",+ "posthog-js": "^1.217.1","react": "^18.2.0","react-day-picker": "8.10.1","react-dom": "^18.2.0",+ "react-error-boundary": "^5.0.0","react-markdown": "^9.0.1","react-split": "^2.0.14","react-syntax-highlighter": "^15.6.1","tailwind-merge": "^2.5.5",- "tailwindcss-animate": "^1.0.7"+ "tailwindcss-animate": "^1.0.7",+ "use-sound": "^4.0.3",+ "utf-8-validate": "^6.0.5",+ "zlib-sync": "^0.1.9"},"devDependencies": {"@eslint/eslintrc": "^3",+ "@types/diff": "^7.0.1","@types/next": "^9.0.0","@types/node": "^22.10.2","@types/react": "^18",@@ -92,6 +104,124 @@"node": ">=6.9.0"}},+ "node_modules/@discordjs/builders": {+ "version": "1.10.1",+ "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.10.1.tgz",+ "integrity": "sha512-OWo1fY4ztL1/M/DUyRPShB4d/EzVfuUvPTRRHRIt/YxBrUYSz0a+JicD5F5zHFoNs2oTuWavxCOVFV1UljHTng==",+ "dependencies": {+ "@discordjs/formatters": "^0.6.0",+ "@discordjs/util": "^1.1.1",+ "@sapphire/shapeshift": "^4.0.0",+ "discord-api-types": "^0.37.119",+ "fast-deep-equal": "^3.1.3",+ "ts-mixer": "^6.0.4",+ "tslib": "^2.6.3"+ },+ "engines": {+ "node": ">=16.11.0"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/collection": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",+ "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/formatters": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.0.tgz",+ "integrity": "sha512-YIruKw4UILt/ivO4uISmrGq2GdMY6EkoTtD0oS0GvkJFRZbTSdPhzYiUILbJ/QslsvC9H9nTgGgnarnIl4jMfw==",+ "dependencies": {+ "discord-api-types": "^0.37.114"+ },+ "engines": {+ "node": ">=16.11.0"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/rest": {+ "version": "2.4.3",+ "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.4.3.tgz",+ "integrity": "sha512-+SO4RKvWsM+y8uFHgYQrcTl/3+cY02uQOH7/7bKbVZsTfrfpoE62o5p+mmV+s7FVhTX82/kQUGGbu4YlV60RtA==",+ "dependencies": {+ "@discordjs/collection": "^2.1.1",+ "@discordjs/util": "^1.1.1",+ "@sapphire/async-queue": "^1.5.3",+ "@sapphire/snowflake": "^3.5.3",+ "@vladfrangu/async_event_emitter": "^2.4.6",+ "discord-api-types": "^0.37.119",+ "magic-bytes.js": "^1.10.0",+ "tslib": "^2.6.3",+ "undici": "6.21.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/util": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.1.1.tgz",+ "integrity": "sha512-eddz6UnOBEB1oITPinyrB2Pttej49M9FZQY8NxgEvc3tq6ZICZ19m70RsmzRdDHk80O9NoYN/25AqJl8vPVf/g==",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/voice": {+ "version": "0.18.0",+ "resolved": "https://registry.npmjs.org/@discordjs/voice/-/voice-0.18.0.tgz",+ "integrity": "sha512-BvX6+VJE5/vhD9azV9vrZEt9hL1G+GlOdsQaVl5iv9n87fkXjf3cSwllhR3GdaUC8m6dqT8umXIWtn3yCu4afg==",+ "dependencies": {+ "@types/ws": "^8.5.12",+ "discord-api-types": "^0.37.103",+ "prism-media": "^1.3.5",+ "tslib": "^2.6.3",+ "ws": "^8.18.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/ws": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.1.tgz",+ "integrity": "sha512-PBvenhZG56a6tMWF/f4P6f4GxZKJTBG95n7aiGSPTnodmz4N5g60t79rSIAq7ywMbv8A4jFtexMruH+oe51aQQ==",+ "dependencies": {+ "@discordjs/collection": "^2.1.0",+ "@discordjs/rest": "^2.4.3",+ "@discordjs/util": "^1.1.0",+ "@sapphire/async-queue": "^1.5.2",+ "@types/ws": "^8.5.10",+ "@vladfrangu/async_event_emitter": "^2.2.4",+ "discord-api-types": "^0.37.119",+ "tslib": "^2.6.2",+ "ws": "^8.17.0"+ },+ "engines": {+ "node": ">=16.11.0"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },"node_modules/@emnapi/runtime": {"version": "1.3.1","resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.3.1.tgz",@@ -1854,6 +1984,36 @@"integrity": "sha512-kkKUDVlII2DQiKy7UstOR1ErJP8kUKAQ4oa+SQtM0K+lPdmmjj0YnnxBgtTVYH7mUKtbsxeFC9y0AmK7Yb78/A==","dev": true},+ "node_modules/@sapphire/async-queue": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz",+ "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },+ "node_modules/@sapphire/shapeshift": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz",+ "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "lodash": "^4.17.21"+ },+ "engines": {+ "node": ">=v16"+ }+ },+ "node_modules/@sapphire/snowflake": {+ "version": "3.5.5",+ "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz",+ "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },"node_modules/@scarf/scarf": {"version": "1.4.0","resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz",@@ -1861,9 +2021,9 @@"hasInstallScript": true},"node_modules/@screenpipe/browser": {- "version": "0.1.24",- "resolved": "https://registry.npmjs.org/@screenpipe/browser/-/browser-0.1.24.tgz",- "integrity": "sha512-20jHIxNqoa+fGbWgdyTangHr135IPgBmg6NQ7JOlEtR8oMHj0d4OwWu2ie6JeX0phaDBWSskF5//RDz21X517g==",+ "version": "0.1.31",+ "resolved": "https://registry.npmjs.org/@screenpipe/browser/-/browser-0.1.31.tgz",+ "integrity": "sha512-mA3fh1TFWuHDkm87WD9oCOWybjWRVMpGTpbR/kHq9TRHQruWUHHzlXb/5QLS6koVxOy61a/y3n5sMrUTkhZc5w==","dependencies": {"@scarf/scarf": "^1.4.0","@types/express": "^5.0.0",@@ -2316,6 +2476,12 @@"@types/ms": "*"}},+ "node_modules/@types/diff": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/@types/diff/-/diff-7.0.1.tgz",+ "integrity": "sha512-R/BHQFripuhW6XPXy05hIvXJQdQ4540KnTvEFHSLjXfHYM41liOLKgIJEyYYiQe796xpaMHfe4Uj/p7Uvng2vA==",+ "dev": true+ },"node_modules/@types/estree": {"version": "1.0.6","resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz",@@ -2429,9 +2595,9 @@}},"node_modules/@types/node": {- "version": "22.13.1",- "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.1.tgz",- "integrity": "sha512-jK8uzQlrvXqEU91UxiK5J7pKHyzgnI1Qnl0QDHIgVGuolJhRb9EEl28Cj9b3rGR8B2lhFCtvIm5os8lFnO/1Ew==",+ "version": "22.13.4",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.4.tgz",+ "integrity": "sha512-ywP2X0DYtX3y08eFVx5fNIw7/uIv8hYUKgXoK8oayJlLnKcRfEYCxWMVE1XagUdVtCJlZT1AU4LXEABW+L1Peg==","dependencies": {"undici-types": "~6.20.0"}@@ -2525,17 +2691,25 @@"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz","integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ=="},+ "node_modules/@types/ws": {+ "version": "8.5.14",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.14.tgz",+ "integrity": "sha512-bd/YFLW+URhBzMXurx7lWByOu+xzU9+kb3RboOteXYDfW+tr+JZa99OyNmPINEGB/ahzKrEuc8rcv4gnpJmxTw==",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@typescript-eslint/eslint-plugin": {- "version": "8.23.0",- "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.23.0.tgz",- "integrity": "sha512-vBz65tJgRrA1Q5gWlRfvoH+w943dq9K1p1yDBY2pc+a1nbBLZp7fB9+Hk8DaALUbzjqlMfgaqlVPT1REJdkt/w==",+ "version": "8.24.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.24.0.tgz",+ "integrity": "sha512-aFcXEJJCI4gUdXgoo/j9udUYIHgF23MFkg09LFz2dzEmU0+1Plk4rQWv/IYKvPHAtlkkGoB3m5e6oUp+JPsNaQ==","dev": true,"dependencies": {"@eslint-community/regexpp": "^4.10.0",- "@typescript-eslint/scope-manager": "8.23.0",- "@typescript-eslint/type-utils": "8.23.0",- "@typescript-eslint/utils": "8.23.0",- "@typescript-eslint/visitor-keys": "8.23.0",+ "@typescript-eslint/scope-manager": "8.24.0",+ "@typescript-eslint/type-utils": "8.24.0",+ "@typescript-eslint/utils": "8.24.0",+ "@typescript-eslint/visitor-keys": "8.24.0","graphemer": "^1.4.0","ignore": "^5.3.1","natural-compare": "^1.4.0",@@ -2555,15 +2729,15 @@}},"node_modules/@typescript-eslint/parser": {- "version": "8.23.0",- "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.23.0.tgz",- "integrity": "sha512-h2lUByouOXFAlMec2mILeELUbME5SZRN/7R9Cw2RD2lRQQY08MWMM+PmVVKKJNK1aIwqTo9t/0CvOxwPbRIE2Q==",+ "version": "8.24.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.24.0.tgz",+ "integrity": "sha512-MFDaO9CYiard9j9VepMNa9MTcqVvSny2N4hkY6roquzj8pdCBRENhErrteaQuu7Yjn1ppk0v1/ZF9CG3KIlrTA==","dev": true,"dependencies": {- "@typescript-eslint/scope-manager": "8.23.0",- "@typescript-eslint/types": "8.23.0",- "@typescript-eslint/typescript-estree": "8.23.0",- "@typescript-eslint/visitor-keys": "8.23.0",+ "@typescript-eslint/scope-manager": "8.24.0",+ "@typescript-eslint/types": "8.24.0",+ "@typescript-eslint/typescript-estree": "8.24.0",+ "@typescript-eslint/visitor-keys": "8.24.0","debug": "^4.3.4"},"engines": {@@ -2579,13 +2753,13 @@}},"node_modules/@typescript-eslint/scope-manager": {- "version": "8.23.0",- "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.23.0.tgz",- "integrity": "sha512-OGqo7+dXHqI7Hfm+WqkZjKjsiRtFUQHPdGMXzk5mYXhJUedO7e/Y7i8AK3MyLMgZR93TX4bIzYrfyVjLC+0VSw==",+ "version": "8.24.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.24.0.tgz",+ "integrity": "sha512-HZIX0UByphEtdVBKaQBgTDdn9z16l4aTUz8e8zPQnyxwHBtf5vtl1L+OhH+m1FGV9DrRmoDuYKqzVrvWDcDozw==","dev": true,"dependencies": {- "@typescript-eslint/types": "8.23.0",- "@typescript-eslint/visitor-keys": "8.23.0"+ "@typescript-eslint/types": "8.24.0",+ "@typescript-eslint/visitor-keys": "8.24.0"},"engines": {"node": "^18.18.0 || ^20.9.0 || >=21.1.0"@@ -2596,13 +2770,13 @@}},"node_modules/@typescript-eslint/type-utils": {- "version": "8.23.0",- "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.23.0.tgz",- "integrity": "sha512-iIuLdYpQWZKbiH+RkCGc6iu+VwscP5rCtQ1lyQ7TYuKLrcZoeJVpcLiG8DliXVkUxirW/PWlmS+d6yD51L9jvA==",+ "version": "8.24.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.24.0.tgz",+ "integrity": "sha512-8fitJudrnY8aq0F1wMiPM1UUgiXQRJ5i8tFjq9kGfRajU+dbPyOuHbl0qRopLEidy0MwqgTHDt6CnSeXanNIwA==","dev": true,"dependencies": {- "@typescript-eslint/typescript-estree": "8.23.0",- "@typescript-eslint/utils": "8.23.0",+ "@typescript-eslint/typescript-estree": "8.24.0",+ "@typescript-eslint/utils": "8.24.0","debug": "^4.3.4","ts-api-utils": "^2.0.1"},@@ -2619,9 +2793,9 @@}},"node_modules/@typescript-eslint/types": {- "version": "8.23.0",- "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.23.0.tgz",- "integrity": "sha512-1sK4ILJbCmZOTt9k4vkoulT6/y5CHJ1qUYxqpF1K/DBAd8+ZUL4LlSCxOssuH5m4rUaaN0uS0HlVPvd45zjduQ==",+ "version": "8.24.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.24.0.tgz",+ "integrity": "sha512-VacJCBTyje7HGAw7xp11q439A+zeGG0p0/p2zsZwpnMzjPB5WteaWqt4g2iysgGFafrqvyLWqq6ZPZAOCoefCw==","dev": true,"engines": {"node": "^18.18.0 || ^20.9.0 || >=21.1.0"@@ -2632,13 +2806,13 @@}},"node_modules/@typescript-eslint/typescript-estree": {- "version": "8.23.0",- "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.23.0.tgz",- "integrity": "sha512-LcqzfipsB8RTvH8FX24W4UUFk1bl+0yTOf9ZA08XngFwMg4Kj8A+9hwz8Cr/ZS4KwHrmo9PJiLZkOt49vPnuvQ==",+ "version": "8.24.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.24.0.tgz",+ "integrity": "sha512-ITjYcP0+8kbsvT9bysygfIfb+hBj6koDsu37JZG7xrCiy3fPJyNmfVtaGsgTUSEuTzcvME5YI5uyL5LD1EV5ZQ==","dev": true,"dependencies": {- "@typescript-eslint/types": "8.23.0",- "@typescript-eslint/visitor-keys": "8.23.0",+ "@typescript-eslint/types": "8.24.0",+ "@typescript-eslint/visitor-keys": "8.24.0","debug": "^4.3.4","fast-glob": "^3.3.2","is-glob": "^4.0.3",@@ -2710,15 +2884,15 @@}},"node_modules/@typescript-eslint/utils": {- "version": "8.23.0",- "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.23.0.tgz",- "integrity": "sha512-uB/+PSo6Exu02b5ZEiVtmY6RVYO7YU5xqgzTIVZwTHvvK3HsL8tZZHFaTLFtRG3CsV4A5mhOv+NZx5BlhXPyIA==",+ "version": "8.24.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.24.0.tgz",+ "integrity": "sha512-07rLuUBElvvEb1ICnafYWr4hk8/U7X9RDCOqd9JcAMtjh/9oRmcfN4yGzbPVirgMR0+HLVHehmu19CWeh7fsmQ==","dev": true,"dependencies": {"@eslint-community/eslint-utils": "^4.4.0",- "@typescript-eslint/scope-manager": "8.23.0",- "@typescript-eslint/types": "8.23.0",- "@typescript-eslint/typescript-estree": "8.23.0"+ "@typescript-eslint/scope-manager": "8.24.0",+ "@typescript-eslint/types": "8.24.0",+ "@typescript-eslint/typescript-estree": "8.24.0"},"engines": {"node": "^18.18.0 || ^20.9.0 || >=21.1.0"@@ -2733,12 +2907,12 @@}},"node_modules/@typescript-eslint/visitor-keys": {- "version": "8.23.0",- "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.23.0.tgz",- "integrity": "sha512-oWWhcWDLwDfu++BGTZcmXWqpwtkwb5o7fxUIGksMQQDSdPW9prsSnfIOZMlsj4vBOSrcnjIUZMiIjODgGosFhQ==",+ "version": "8.24.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.24.0.tgz",+ "integrity": "sha512-kArLq83QxGLbuHrTMoOEWO+l2MwsNS2TGISEdx8xgqpkbytB07XmlQyQdNDrCc1ecSqx0cnmhGvpX+VBwqqSkg==","dev": true,"dependencies": {- "@typescript-eslint/types": "8.23.0",+ "@typescript-eslint/types": "8.24.0","eslint-visitor-keys": "^4.2.0"},"engines": {@@ -2755,9 +2929,9 @@"integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="},"node_modules/@vercel/analytics": {- "version": "1.4.1",- "resolved": "https://registry.npmjs.org/@vercel/analytics/-/analytics-1.4.1.tgz",- "integrity": "sha512-ekpL4ReX2TH3LnrRZTUKjHHNpNy9S1I7QmS+g/RQXoSUQ8ienzosuX7T9djZ/s8zPhBx1mpHP/Rw5875N+zQIQ==",+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/@vercel/analytics/-/analytics-1.5.0.tgz",+ "integrity": "sha512-MYsBzfPki4gthY5HnYN7jgInhAZ7Ac1cYDoRWFomwGHWEX7odTEzbtg9kf/QSo7XEsEAqlQugA6gJ2WS2DEa3g==","peerDependencies": {"@remix-run/react": "^2","@sveltejs/kit": "^1 || ^2",@@ -2791,6 +2965,15 @@}}},+ "node_modules/@vladfrangu/async_event_emitter": {+ "version": "2.4.6",+ "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.6.tgz",+ "integrity": "sha512-RaI5qZo6D2CVS6sTHFKg1v5Ohq/+Bo2LZ5gzUEwZ/WkHhwtGTCB/sVLw8ijOkAUxasZ+WshN/Rzj4ywsABJ5ZA==",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },"node_modules/abort-controller": {"version": "3.0.0","resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",@@ -3203,6 +3386,14 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/bindings": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",+ "dependencies": {+ "file-uri-to-path": "1.0.0"+ }+ },"node_modules/body-parser": {"version": "1.20.3","resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",@@ -3292,6 +3483,18 @@"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"}},+ "node_modules/bufferutil": {+ "version": "4.0.9",+ "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.9.tgz",+ "integrity": "sha512-WDtdLmJvAuNNPzByAYpRo2rF1Mmradw6gvWsQKf63476DDXmomT9zUiGypLcG4ibIM67vhAj8jJRdbmEws2Aqw==",+ "hasInstallScript": true,+ "dependencies": {+ "node-gyp-build": "^4.3.0"+ },+ "engines": {+ "node": ">=6.14.2"+ }+ },"node_modules/busboy": {"version": "1.6.0","resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",@@ -3330,9 +3533,9 @@}},"node_modules/call-bind-apply-helpers": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz",- "integrity": "sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==",+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==","dependencies": {"es-errors": "^1.3.0","function-bind": "^1.1.2"@@ -3374,9 +3577,9 @@}},"node_modules/caniuse-lite": {- "version": "1.0.30001698",- "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001698.tgz",- "integrity": "sha512-xJ3km2oiG/MbNU8G6zIq6XRZ6HtAOVXsbOrP/blGazi52kc5Yy7b6sDA5O+FbROzRrV7BSTllLHuNvmawYUJjw==",+ "version": "1.0.30001699",+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001699.tgz",+ "integrity": "sha512-b+uH5BakXZ9Do9iK+CkDmctUSEqZl+SP056vc5usa0PL+ev5OHw003rZXcnjNDv3L8P5j6rwT6C0BPKSikW08w==","funding": [{"type": "opencollective",@@ -4269,6 +4472,61 @@"resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz","integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw=="},+ "node_modules/diff": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz",+ "integrity": "sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==",+ "engines": {+ "node": ">=0.3.1"+ }+ },+ "node_modules/discord-api-types": {+ "version": "0.37.119",+ "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.119.tgz",+ "integrity": "sha512-WasbGFXEB+VQWXlo6IpW3oUv73Yuau1Ig4AZF/m13tXcTKnMpc/mHjpztIlz4+BM9FG9BHQkEXiPto3bKduQUg=="+ },+ "node_modules/discord.js": {+ "version": "14.18.0",+ "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.18.0.tgz",+ "integrity": "sha512-SvU5kVUvwunQhN2/+0t55QW/1EHfB1lp0TtLZUSXVHDmyHTrdOj5LRKdR0zLcybaA15F+NtdWuWmGOX9lE+CAw==",+ "dependencies": {+ "@discordjs/builders": "^1.10.1",+ "@discordjs/collection": "1.5.3",+ "@discordjs/formatters": "^0.6.0",+ "@discordjs/rest": "^2.4.3",+ "@discordjs/util": "^1.1.1",+ "@discordjs/ws": "^1.2.1",+ "@sapphire/snowflake": "3.5.3",+ "discord-api-types": "^0.37.119",+ "fast-deep-equal": "3.1.3",+ "lodash.snakecase": "4.1.1",+ "tslib": "^2.6.3",+ "undici": "6.21.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/discord.js/node_modules/@discordjs/collection": {+ "version": "1.5.3",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",+ "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==",+ "engines": {+ "node": ">=16.11.0"+ }+ },+ "node_modules/discord.js/node_modules/@sapphire/snowflake": {+ "version": "3.5.3",+ "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.3.tgz",+ "integrity": "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ==",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },"node_modules/dlv": {"version": "1.1.3","resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",@@ -4310,9 +4568,9 @@"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="},"node_modules/electron-to-chromium": {- "version": "1.5.96",- "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.96.tgz",- "integrity": "sha512-8AJUW6dh75Fm/ny8+kZKJzI1pgoE8bKLZlzDU2W1ENd+DXKJrx7I7l9hb8UWR4ojlnb5OlixMt00QWiYJoVw1w==",+ "version": "1.5.99",+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.99.tgz",+ "integrity": "sha512-77c/+fCyL2U+aOyqfIFi89wYLBeSTCs55xCZL0oFH0KjqsvSvyh6AdQ+UIl1vgpnQQE6g+/KK8hOIupH6VwPtg==","dev": true},"node_modules/emoji-regex": {@@ -4352,6 +4610,16 @@"url": "https://github.com/fb55/entities?sponsor=1"}},+ "node_modules/erlpack": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/erlpack/-/erlpack-0.1.4.tgz",+ "integrity": "sha512-CJYbkEvsB5FqCCu2tLxF1eYKi28PvemC12oqzJ9oO6mDFrFO9G9G7nNJUHhiAyyL9zfXTOJx/tOcrQk+ncD65w==",+ "hasInstallScript": true,+ "dependencies": {+ "bindings": "^1.5.0",+ "nan": "^2.15.0"+ }+ },"node_modules/es-abstract": {"version": "1.23.9","resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.9.tgz",@@ -4487,12 +4755,15 @@}},"node_modules/es-shim-unscopables": {- "version": "1.0.2",- "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz",- "integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==",+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz",+ "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==","dev": true,"dependencies": {- "hasown": "^2.0.0"+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"}},"node_modules/es-to-primitive": {@@ -4538,9 +4809,9 @@}},"node_modules/eslint": {- "version": "9.20.0",- "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.20.0.tgz",- "integrity": "sha512-aL4F8167Hg4IvsW89ejnpTwx+B/UQRzJPGgbIOl+4XqffWsahVVsLEWoZvnrVuwpWmnRd7XeXmQI1zlKcFDteA==",+ "version": "9.20.1",+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.20.1.tgz",+ "integrity": "sha512-m1mM33o6dBUjxl2qb6wv6nGNwCAsns1eKtaQ4l/NPHeTvhiUPbtdfMyktxN4B3fgHIgsYh1VT3V9txblpQHq+g==","dev": true,"dependencies": {"@eslint-community/eslint-utils": "^4.2.0",@@ -5158,6 +5429,11 @@"node": ">=16.0.0"}},+ "node_modules/file-uri-to-path": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="+ },"node_modules/fill-range": {"version": "7.1.1","resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",@@ -5235,9 +5511,9 @@"dev": true},"node_modules/for-each": {- "version": "0.3.4",- "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.4.tgz",- "integrity": "sha512-kKaIINnFpzW6ffJNDjjyjrk21BkDx38c0xa/klsT8VzLCaMEefv4ZTacrcVR4DmgTeBra++jMDAfS/tS799YDw==",+ "version": "0.3.5",+ "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz",+ "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==","dev": true,"dependencies": {"is-callable": "^1.2.7"@@ -5324,9 +5600,9 @@}},"node_modules/framer-motion": {- "version": "12.4.1",- "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.4.1.tgz",- "integrity": "sha512-5Ijbea3topSZjadQ0hgc/TcWj2ldMZmNREM7RvAhvsThYOA1HHOA8TT1yKvMu1YXP3jWaFwoZ6Vo9Nw+DUZrzA==",+ "version": "12.4.2",+ "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.4.2.tgz",+ "integrity": "sha512-pW307cQKjDqEuO1flEoIFf6TkuJRfKr+c7qsHAJhDo4368N/5U8/7WU8J+xhd9+gjmOgJfgp+46evxRRFM39dA==","dependencies": {"motion-dom": "^12.0.0","motion-utils": "^12.0.0",@@ -5786,6 +6062,11 @@"resolved": "https://registry.npmjs.org/highlightjs-vue/-/highlightjs-vue-1.0.0.tgz","integrity": "sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA=="},+ "node_modules/howler": {+ "version": "2.2.4",+ "resolved": "https://registry.npmjs.org/howler/-/howler-2.2.4.tgz",+ "integrity": "sha512-iARIBPgcQrwtEr+tALF+rapJ8qSc+Set2GJQl7xT1MQzWaVkFebdJhR3alVlSiUf5U7nAANKuj3aWpwerocD5w=="+ },"node_modules/html-url-attributes": {"version": "3.0.1","resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",@@ -6553,6 +6834,11 @@"integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==","dev": true},+ "node_modules/lodash.snakecase": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",+ "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw=="+ },"node_modules/longest-streak": {"version": "3.1.0","resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",@@ -6599,6 +6885,11 @@"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc"}},+ "node_modules/magic-bytes.js": {+ "version": "1.10.0",+ "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.10.0.tgz",+ "integrity": "sha512-/k20Lg2q8LE5xiaaSkMXk4sfvI+9EGEykFS4b0CHHGWqDYU0bGUFSwchNOMA56D7TCs9GwVTkqe9als1/ns8UQ=="+ },"node_modules/markdown-it": {"version": "14.1.0","resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz",@@ -7325,6 +7616,11 @@"thenify-all": "^1.0.0"}},+ "node_modules/nan": {+ "version": "2.22.0",+ "resolved": "https://registry.npmjs.org/nan/-/nan-2.22.0.tgz",+ "integrity": "sha512-nbajikzWTMwsW+eSsNm3QwlOs7het9gGJU5dDZzRTQGk03vyBOauxgI4VakDzE0PtsGTmXPsXTbbjVhRwR5mpw=="+ },"node_modules/nanoid": {"version": "3.3.8","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz",@@ -7484,6 +7780,16 @@}}},+ "node_modules/node-gyp-build": {+ "version": "4.8.4",+ "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",+ "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",+ "bin": {+ "node-gyp-build": "bin.js",+ "node-gyp-build-optional": "optional.js",+ "node-gyp-build-test": "build-test.js"+ }+ },"node_modules/node-releases": {"version": "2.0.19","resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz",@@ -7639,9 +7945,9 @@}},"node_modules/openai": {- "version": "4.83.0",- "resolved": "https://registry.npmjs.org/openai/-/openai-4.83.0.tgz",- "integrity": "sha512-fmTsqud0uTtRKsPC7L8Lu55dkaTwYucqncDHzVvO64DKOpNTuiYwjbR/nVgpapXuYy8xSnhQQPUm+3jQaxICgw==",+ "version": "4.85.0",+ "resolved": "https://registry.npmjs.org/openai/-/openai-4.85.0.tgz",+ "integrity": "sha512-HRpbTBViDmccPU3PqPkv95ohkzcnSNQ7ERKNftUgB3kD/rbG45PdTPLPFnaWTS5DsDlGD41OH4BwanNW/tt+Ww==","dependencies": {"@types/node": "^18.11.18","@types/node-fetch": "^2.6.4",@@ -7668,9 +7974,9 @@}},"node_modules/openai/node_modules/@types/node": {- "version": "18.19.75",- "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.75.tgz",- "integrity": "sha512-UIksWtThob6ZVSyxcOqCLOUNg/dyO1Qvx4McgeuhrEtHTLFTf7BBhEazaE4K806FGTPtzd/2sE90qn4fVr7cyw==",+ "version": "18.19.76",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.76.tgz",+ "integrity": "sha512-yvR7Q9LdPz2vGpmpJX5LolrgRdWvB67MJKDPSgIIzpFbaf9a1j/f5DnLp5VDyHGMR0QZHlTr1afsD87QCXFHKw==","dependencies": {"undici-types": "~5.26.4"}@@ -7749,6 +8055,17 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/p-throttle": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/p-throttle/-/p-throttle-7.0.0.tgz",+ "integrity": "sha512-aio0v+S0QVkH1O+9x4dHtD4dgCExACcL+3EtNaGqC01GBudS9ijMuUsmN8OVScyV4OOp0jqdLShZFuSlbL/AsA==",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/package-json-from-dist": {"version": "1.0.1","resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",@@ -7881,9 +8198,9 @@}},"node_modules/postcss": {- "version": "8.5.1",- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.1.tgz",- "integrity": "sha512-6oz2beyjc5VMn/KV1pPw8fliQkhBXrVn1Z3TVyqZxU8kZpzEKhBdmCFqI6ZbmGtamQvQGuU1sgPTk8ZrXDD7jQ==",+ "version": "8.5.2",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.2.tgz",+ "integrity": "sha512-MjOadfU3Ys9KYoX0AdkBlFEF1Vx37uCCeN4ZHnmwm9FfpbsGWMZeBLMmmpY+6Ocqod7mkdZ0DT31OlbsFrLlkA==","funding": [{"type": "opencollective",@@ -8017,9 +8334,9 @@"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="},"node_modules/posthog-js": {- "version": "1.215.6",- "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.215.6.tgz",- "integrity": "sha512-OWfLYXaGNZDfKnNo9h2jifV1rsqhSfZzHw6/W6IOSk8Cq2nidIPUm89mutk7zbzPPmnVTV8eqPCfhFaoHZZKLw==",+ "version": "1.217.4",+ "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.217.4.tgz",+ "integrity": "sha512-ZIOb75F1pdMZl6e7C4mgH2accKArLA2RG3zMEjeils+3J/cylwgcr2Iw0QtzSLqQVvR7AFRRbXMZXUWsiB2zyA==","dependencies": {"core-js": "^3.38.1","fflate": "^0.4.8",@@ -8045,6 +8362,31 @@"node": ">= 0.8.0"}},+ "node_modules/prism-media": {+ "version": "1.3.5",+ "resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz",+ "integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==",+ "peerDependencies": {+ "@discordjs/opus": ">=0.8.0 <1.0.0",+ "ffmpeg-static": "^5.0.2 || ^4.2.7 || ^3.0.0 || ^2.4.0",+ "node-opus": "^0.3.3",+ "opusscript": "^0.0.8"+ },+ "peerDependenciesMeta": {+ "@discordjs/opus": {+ "optional": true+ },+ "ffmpeg-static": {+ "optional": true+ },+ "node-opus": {+ "optional": true+ },+ "opusscript": {+ "optional": true+ }+ }+ },"node_modules/prismjs": {"version": "1.29.0","resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.29.0.tgz",@@ -8240,9 +8582,9 @@}},"node_modules/prosemirror-view": {- "version": "1.37.2",- "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.37.2.tgz",- "integrity": "sha512-ApcyrfV/cRcaL65on7TQcfWElwLyOgIjnIynfAuV+fIdlpbSvSWRwfuPaH7T5mo4AbO/FID29qOtjiDIKGWyog==",+ "version": "1.38.0",+ "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.38.0.tgz",+ "integrity": "sha512-O45kxXQTaP9wPdXhp8TKqCR+/unS/gnfg9Q93svQcB3j0mlp2XSPAmsPefxHADwzC+fbNS404jqRxm3UQaGvgw==","dependencies": {"prosemirror-model": "^1.20.0","prosemirror-state": "^1.0.0",@@ -8369,6 +8711,17 @@"react": "^18.3.1"}},+ "node_modules/react-error-boundary": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-5.0.0.tgz",+ "integrity": "sha512-tnjAxG+IkpLephNcePNA7v6F/QpWLH8He65+DmedchDwg162JZqx4NmbXj0mlAYVVEd81OW7aFhmbsScYfiAFQ==",+ "dependencies": {+ "@babel/runtime": "^7.12.5"+ },+ "peerDependencies": {+ "react": ">=16.13.1"+ }+ },"node_modules/react-is": {"version": "16.13.1","resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",@@ -9641,6 +9994,11 @@"resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz","integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA=="},+ "node_modules/ts-mixer": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",+ "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA=="+ },"node_modules/tsconfig-paths": {"version": "3.15.0","resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz",@@ -9791,6 +10149,14 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/undici": {+ "version": "6.21.1",+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",+ "integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",+ "engines": {+ "node": ">=18.17"+ }+ },"node_modules/undici-types": {"version": "6.20.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",@@ -9965,6 +10331,17 @@}}},+ "node_modules/use-sound": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/use-sound/-/use-sound-4.0.3.tgz",+ "integrity": "sha512-L205pEUFIrLsGYsCUKHQVCt0ajs//YQOFbEQeNwaWaqQj3y3st4SuR+rvpMHLmv8hgTcfUFlvMQawZNI3OE18w==",+ "dependencies": {+ "howler": "^2.1.3"+ },+ "peerDependencies": {+ "react": ">=16.8"+ }+ },"node_modules/use-sync-external-store": {"version": "1.4.0","resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.4.0.tgz",@@ -9973,6 +10350,18 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/utf-8-validate": {+ "version": "6.0.5",+ "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-6.0.5.tgz",+ "integrity": "sha512-EYZR+OpIXp9Y1eG1iueg8KRsY8TuT8VNgnanZ0uA3STqhHQTLwbl+WX76/9X5OY12yQubymBpaBSmMPkSTQcKA==",+ "hasInstallScript": true,+ "dependencies": {+ "node-gyp-build": "^4.3.0"+ },+ "engines": {+ "node": ">=6.14.2"+ }+ },"node_modules/util-deprecate": {"version": "1.0.2","resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",@@ -10248,6 +10637,26 @@"url": "https://github.com/chalk/ansi-styles?sponsor=1"}},+ "node_modules/ws": {+ "version": "8.18.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",+ "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },"node_modules/xtend": {"version": "4.0.2","resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",@@ -10279,6 +10688,15 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/zlib-sync": {+ "version": "0.1.9",+ "resolved": "https://registry.npmjs.org/zlib-sync/-/zlib-sync-0.1.9.tgz",+ "integrity": "sha512-DinB43xCjVwIBDpaIvQqHbmDsnYnSt6HJ/yiB2MZQGTqgPcwBSZqLkimXwK8BvdjQ/MaZysb5uEenImncqvCqQ==",+ "hasInstallScript": true,+ "dependencies": {+ "nan": "^2.18.0"+ }+ },"node_modules/zwitch": {"version": "2.0.4","resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",diff --git a/pipes/meeting/package.json b/pipes/meeting/package.jsonindex ea4846549..e06d4cbaf 100644--- a/pipes/meeting/package.json+++ b/pipes/meeting/package.json@@ -1,6 +1,6 @@{"name": "meeting",- "version": "0.1.3",+ "version": "0.1.4","private": true,"repository": {"type": "git",@@ -13,6 +13,8 @@"lint": "next lint"},"dependencies": {+ "@discordjs/rest": "^2.4.3",+ "@discordjs/voice": "^0.18.0","@radix-ui/react-accordion": "^1.2.2","@radix-ui/react-checkbox": "^1.1.3","@radix-ui/react-collapsible": "^1.1.2",@@ -29,7 +31,7 @@"@radix-ui/react-tabs": "^1.1.2","@radix-ui/react-toast": "^1.2.5","@radix-ui/react-tooltip": "^1.1.5",- "@screenpipe/browser": "0.1.24",+ "@screenpipe/browser": "^0.1.31","@screenpipe/js": "1.0.7","@tauri-apps/api": "^2.2.0","@tiptap/extension-color": "^2.2.4",@@ -41,28 +43,38 @@"@types/lodash": "^4.17.13","@types/react-syntax-highlighter": "^15.5.13","@vercel/analytics": "^1.4.1",+ "bufferutil": "^4.0.9","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "1.0.0","date-fns": "^3.3.1",+ "diff": "^7.0.0",+ "discord.js": "^14.18.0",+ "erlpack": "^0.1.4","framer-motion": "^12.0.11","localforage": "^1.10.0","lodash": "^4.17.21","lucide-react": "^0.468.0","next": "15.1.0","openai": "^4.76.3",- "posthog-js": "^1.215.1",+ "p-throttle": "^7.0.0",+ "posthog-js": "^1.217.1","react": "^18.2.0","react-day-picker": "8.10.1","react-dom": "^18.2.0",+ "react-error-boundary": "^5.0.0","react-markdown": "^9.0.1","react-split": "^2.0.14","react-syntax-highlighter": "^15.6.1","tailwind-merge": "^2.5.5",- "tailwindcss-animate": "^1.0.7"+ "tailwindcss-animate": "^1.0.7",+ "use-sound": "^4.0.3",+ "utf-8-validate": "^6.0.5",+ "zlib-sync": "^0.1.9"},"devDependencies": {"@eslint/eslintrc": "^3",+ "@types/diff": "^7.0.1","@types/next": "^9.0.0","@types/node": "^22.10.2","@types/react": "^18",diff --git a/pipes/meeting/src/app/api/messages/route.ts b/pipes/meeting/src/app/api/messages/route.tsnew file mode 100644index 000000000..963cc6393--- /dev/null+++ b/pipes/meeting/src/app/api/messages/route.ts@@ -0,0 +1,292 @@+// Force Node.js runtime for this route+export const runtime = 'nodejs'+// Force dynamic behavior since Discord client needs to maintain state+export const dynamic = 'force-dynamic'++import { NextResponse } from 'next/server'+import { createChatSession, getChatSession, updateChatSession } from '@/lib/storage/chat-storage'++// Store active chat sessions+const sessions: Record<string, {+ threadId: string+ lastMessageId?: string+}> = {}++const DISCORD_API = 'https://discord.com/api/v10'++// Add token validation helper+function validateToken(token: string | undefined): string {+ if (!token) {+ throw new Error('DISCORD_BOT_TOKEN is not set')+ }++ // Token should start with Bot prefix if not already present+ if (!token.startsWith('Bot ')) {+ token = `Bot ${token}`+ }++ // Basic format validation+ if (!/^Bot [A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token)) {+ throw new Error('DISCORD_BOT_TOKEN format is invalid')+ }++ return token+}++async function discordRequest(endpoint: string, options: RequestInit = {}) {+ const url = `${DISCORD_API}${endpoint}`+ console.log('discord request:', {+ url,+ method: options.method,+ hasToken: !!process.env.DISCORD_BOT_TOKEN,+ tokenLength: process.env.DISCORD_BOT_TOKEN?.length+ })++ try {+ const token = validateToken(process.env.DISCORD_BOT_TOKEN)++ const res = await fetch(url, {+ ...options,+ headers: {+ 'Authorization': token,+ 'Content-Type': 'application/json',+ ...options.headers,+ },+ })++ const text = await res.text()+ console.log('discord response:', {+ status: res.status,+ text,+ headers: Object.fromEntries(res.headers)+ })++ if (!res.ok) {+ throw new Error(`Discord API error: ${res.status} - ${text}`)+ }++ return JSON.parse(text)+ } catch (error) {+ console.error('discord request failed:', {+ error,+ token: process.env.DISCORD_BOT_TOKEN?.slice(0, 10) + '...',+ endpoint+ })+ throw error+ }+}++// Add interface for transformed message+interface TransformedMessage {+ id: string+ content: string+ fromUser: boolean+ timestamp: string+ author?: {+ id: string+ username: string+ }+}++export async function POST(req: Request) {+ try {+ const { message, sessionId, userAgent, type } = await req.json()+ console.log('received message request:', { sessionId, messageLength: message.length, type })++ // Get or create chat session+ let session = await getChatSession(sessionId)+ if (!session) {+ console.log('creating new thread for session:', sessionId)+ const thread = await discordRequest(`/channels/${process.env.DISCORD_CHANNEL_ID}/threads`, {+ method: 'POST',+ body: JSON.stringify({+ name: `Chat ${sessionId.slice(0,8)}`,+ type: 11,+ auto_archive_duration: 1440+ })+ })++ session = await createChatSession(sessionId, thread.id)+ console.log('created thread and session:', { threadId: thread.id, sessionId })+ }++ // Format message based on type+ const messageContent = type === 'system'+ ? `System: ${message}\n\nContext: ${userAgent}`+ : `User: ${message}\n\nContext: ${userAgent}`++ // Send message to thread+ console.log('sending message to thread:', session.threadId)+ const discordMsg = await discordRequest(`/channels/${session.threadId}/messages`, {+ method: 'POST',+ body: JSON.stringify({+ content: messageContent+ })+ })++ // Don't store system messages in chat history+ if (type !== 'system') {+ await updateChatSession(sessionId, {+ messages: [...session.messages, {+ id: discordMsg.id,+ content: message,+ fromUser: true,+ timestamp: new Date().toISOString()+ }]+ })+ }++ return NextResponse.json({ success: true })+ } catch (error) {+ console.error('discord error:', error)+ return NextResponse.json(+ { error: error instanceof Error ? error.message : 'Failed to send message' },+ { status: 500 }+ )+ }+}++export async function GET(req: Request) {+ const url = new URL(req.url)+ const sessionId = url.searchParams.get('sessionId')++ if (!sessionId) {+ return NextResponse.json({ messages: [] })+ }++ try {+ // Get session from local storage+ const session = await getChatSession(sessionId)+ if (!session) {+ return NextResponse.json({ messages: [] })+ }++ // Initialize session tracking if needed+ if (!sessions[sessionId]) {+ sessions[sessionId] = {+ threadId: session.threadId+ }+ }++ // Fetch latest messages from Discord+ const messages = await discordRequest(+ `/channels/${session.threadId}/messages?limit=50`+ )++ // Store last message ID for future reference+ if (messages.length > 0) {+ sessions[sessionId].lastMessageId = messages[0].id+ }++ // Add detailed message logging+ console.log('raw discord messages details:', messages.map((msg: any) => ({+ id: msg.id,+ content: msg.content,+ type: msg.type,+ author: msg.author?.username,+ timestamp: msg.timestamp,+ hasEmbeds: !!msg.embeds?.length,+ hasAttachments: !!msg.attachments?.length,+ flags: msg.flags,+ components: msg.components,+ // Full message for debugging+ fullMessage: msg+ })))++ // Transform each message to determine its origin and content.+ const transformedMessages = messages.map((msg: any) => {+ // Default to user message if from your Discord user ID+ let fromUser = msg.author?.id === '974812370868868269'++ // Initialize content array to collect all content parts+ let contentParts: string[] = []++ // Add main content if present, removing the Context part+ if (msg.content) {+ const content = msg.content.split('\n\nContext:')[0] // Only take content before Context+ // Skip messages that start with "User:" if they're from the bot+ if (!fromUser && content.startsWith('User:')) {+ return null+ }+ contentParts.push(content)+ }++ // Add embed content if present+ if (msg.embeds?.length > 0) {+ msg.embeds.forEach((embed: any) => {+ if (embed.title) contentParts.push(embed.title)+ if (embed.description) contentParts.push(embed.description)+ if (embed.fields?.length > 0) {+ embed.fields.forEach((field: any) => {+ contentParts.push(`${field.name}: ${field.value}`)+ })+ }+ })+ }++ // Add attachment URLs if present+ if (msg.attachments?.length > 0) {+ contentParts.push(...msg.attachments.map((a: any) => a.url))+ }++ // Combine all content parts+ let content = contentParts.join('\n').trim()++ // If message is from user but empty, use a placeholder+ if (fromUser && !content) {+ content = '[empty message]'+ console.log('detected empty user message:', { id: msg.id, author: msg.author?.username })+ }++ // Handle User: prefix logic (for bot messages)+ if (content.startsWith('User:')) {+ content = content.slice('User:'.length).trim()+ fromUser = true+ console.log('detected user message via prefix:', { id: msg.id, content })+ } else {+ console.log('detected message:', {+ id: msg.id,+ content,+ fromUser,+ author: msg.author?.username,+ hasEmbeds: msg.embeds?.length > 0,+ hasAttachments: msg.attachments?.length > 0+ })+ }++ return {+ id: msg.id,+ content,+ fromUser,+ timestamp: msg.timestamp,+ author: msg.author,+ }+ })+ .filter(Boolean) as TransformedMessage[] // Type assertion here++ console.log('transformed messages:', transformedMessages)++ // Update session with latest messages+ await updateChatSession(sessionId, {+ messages: transformedMessages.map((msg: TransformedMessage) => ({+ id: msg.id,+ content: msg.content,+ fromUser: msg.fromUser,+ timestamp: msg.timestamp+ }))+ })++ return NextResponse.json({+ messages: transformedMessages.reverse()+ })+ } catch (error) {+ console.error('failed to fetch messages:', {+ error,+ sessionId+ })+ return NextResponse.json(+ { error: 'failed to fetch messages' },+ { status: 500 }+ )+ }+}\ No newline at end of filediff --git a/pipes/meeting/src/app/layout.tsx b/pipes/meeting/src/app/layout.tsxindex 4fbaf0038..e21419146 100644--- a/pipes/meeting/src/app/layout.tsx+++ b/pipes/meeting/src/app/layout.tsx@@ -2,10 +2,9 @@ import type { Metadata } from "next"import { Geist, Geist_Mono } from "next/font/google"import "./globals.css"import { Toaster } from "@/components/ui/toaster"-import PostHogProvider from "@/components/providers/posthog-provider"import { Analytics } from "@vercel/analytics/react"import { ChatButton } from "@/components/chat-button"-import { SettingsProvider } from "@/lib/hooks/use-settings"+import { RootProvider } from "@/components/providers/root-provider"const geistSans = Geist({variable: "--font-geist-sans",@@ -19,7 +18,7 @@ const geistMono = Geist_Mono({export const metadata: Metadata = {title: "Meeting • Screenpipe",- description: "The AI notepad for people in back-to-back meetings",+ description: "The AI notepad for people in back-to-back meetings"}export default function RootLayout({@@ -33,16 +32,15 @@ export default function RootLayout({suppressHydrationWarning={true}className={`${geistSans.variable} ${geistMono.variable} antialiased h-screen`}>- <PostHogProvider>- <SettingsProvider>- <main className="h-full p-4 overflow-hidden">- {children}- </main>- <Toaster />- <ChatButton />- <Analytics mode={process.env.NODE_ENV === "development" ? "development" : "production"} />- </SettingsProvider>- </PostHogProvider>+ <RootProvider>+ <main className="h-full p-4 overflow-hidden">+ {children}+ </main>+ <Toaster />+ <ChatButton />+ {/* Comment this out temporarily for testing */}+ {/* <Analytics mode={process.env.NODE_ENV === "development" ? "development" : "production"} /> */}+ </RootProvider></body></html>)diff --git a/pipes/meeting/src/app/meetings/live/loading.tsx b/pipes/meeting/src/app/meetings/live/loading.tsxindex a198cb546..dcd01070a 100644--- a/pipes/meeting/src/app/meetings/live/loading.tsx+++ b/pipes/meeting/src/app/meetings/live/loading.tsx@@ -1,3 +1,10 @@+import { Loader2 } from "lucide-react"+export default function Loading() {- return <div>loading...</div>+ return (+ <div className="h-full w-full flex items-center justify-center">+ <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />+ <span className="ml-2 text-muted-foreground">loading meeting...</span>+ </div>+ )}\ No newline at end of filediff --git a/pipes/meeting/src/app/meetings/live/page.tsx b/pipes/meeting/src/app/meetings/live/page.tsxindex cde1ad092..278292052 100644--- a/pipes/meeting/src/app/meetings/live/page.tsx+++ b/pipes/meeting/src/app/meetings/live/page.tsx@@ -3,7 +3,6 @@import { useRouter } from 'next/navigation'import { LiveTranscription } from '@/components/live-transcription/new-meeting-wrapper'import { useEffect, useRef } from 'react'-import { MeetingProvider } from '@/components/live-transcription/hooks/storage-for-live-meeting'export default function LiveMeetingPage() {const router = useRouter()@@ -15,22 +14,26 @@ export default function LiveMeetingPage() {console.log('live meeting page mounting, pathname:', window.location.pathname)+ // Add resize listener for debug+ const handleResize = () => {+ console.log('window resized:', {+ width: window.innerWidth,+ height: window.innerHeight,+ isMobile: window.innerWidth < 768+ })+ }+ window.addEventListener('resize', handleResize)+return () => {console.log('live meeting page unmounting')mounted.current = false+ window.removeEventListener('resize', handleResize)}}, [])return (<div className="h-full">- <MeetingProvider>- <LiveTranscription- onBack={() => {- console.log('live meeting back pressed')- router.push('/meetings')- }}- />- </MeetingProvider>+ <LiveTranscription /></div>)}\ No newline at end of filediff --git a/pipes/meeting/src/app/meetings/page.tsx b/pipes/meeting/src/app/meetings/page.tsxindex 3a29d6473..ef7351c2d 100644--- a/pipes/meeting/src/app/meetings/page.tsx+++ b/pipes/meeting/src/app/meetings/page.tsx@@ -1,3 +1,5 @@+'use client'+import { MeetingHistory } from "@/components/meeting-history/meeting-history"export default function MeetingsPage() {diff --git a/pipes/meeting/src/app/page.tsx b/pipes/meeting/src/app/page.tsxindex cbe83ba65..885fe0273 100644--- a/pipes/meeting/src/app/page.tsx+++ b/pipes/meeting/src/app/page.tsx@@ -1,6 +1,13 @@+'use client'++import { useEffect } from "react"import { MeetingHistory } from "@/components/meeting-history/meeting-history"// Instead of redirecting, show meetings directly at rootexport default function HomePage() {+ useEffect(() => {+ console.log('homepage mounted')+ }, [])+return <MeetingHistory />}diff --git a/pipes/meeting/src/components/chat-button.tsx b/pipes/meeting/src/components/chat-button.tsxindex dd07d510b..1033ff56d 100644--- a/pipes/meeting/src/components/chat-button.tsx+++ b/pipes/meeting/src/components/chat-button.tsx@@ -10,13 +10,193 @@ declare global {}import { Button } from "@/components/ui/button"-import { MessageCircle } from "lucide-react"+import { MessageCircle, VideoOff, MicOff } from "lucide-react"import { motion } from "framer-motion"+import React from "react"+import { useSound } from 'use-sound'++type Message = {+ id: string+ content: string+ fromUser: boolean+ timestamp: string+}export function ChatButton() {const supportLink = "https://wa.me/16507961489"+ // Add ref for the image element+ const imgRef = React.useRef<HTMLImageElement>(null)++ // Add state to control webcam visibility+ const [showWebcam, setShowWebcam] = React.useState(false)+ const [messages, setMessages] = React.useState<Message[]>([])+ const [message, setMessage] = React.useState('')+ const [isSending, setIsSending] = React.useState(false)+ const [showChat, setShowChat] = React.useState(false)+ const [sessionId, setSessionId] = React.useState('')++ // Add ref for message container+ const messagesEndRef = React.useRef<HTMLDivElement>(null)++ // Update sound hook with base64 beep+ const [playMessageSound] = useSound('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdH6PhYR0TkZXcoyarKyvoJKYmY+AmH2FmZSHhpGVkZJ/gYGEkIqEhoyNlZmJb4J6c4iFjqCfkH+GhYKJg4OMiYSFjYyLkZSPlI2Oi4mJiouJhIeKi4qFhomA', {+ volume: 0.5,+ onplayerror: (id: number, err: Error) => {+ console.log('failed to play sound:', err)+ }+ })+ const lastMessageCountRef = React.useRef(messages.length)++ // Add state for WebSocket connection status+ const [isWebsocketConnected, setIsWebsocketConnected] = React.useState(false)+ const [wsError, setWsError] = React.useState<string | null>(null)++ // Add loading state+ const [isLoadingWebcam, setIsLoadingWebcam] = React.useState(true)++ // Generate unique session ID when chat opens+ React.useEffect(() => {+ if (showChat) {+ setSessionId(crypto.randomUUID())+ }+ }, [showChat])++ // Poll for new messages+ React.useEffect(() => {+ if (!showChat || !sessionId) return++ const seenMessageIds = new Set<string>()+ const M13V_ID = '974812370868269098' // Your actual Discord ID from the response++ const pollInterval = setInterval(async () => {+ try {+ const response = await fetch(`/api/messages?sessionId=${sessionId}`)+ const data = await response.json()+ console.log('received raw data:', data)++ if (data.messages) {+ const transformedMessages = data.messages.map((msg: any) => {+ if (!msg) {+ console.log('skipping null message')+ return null+ }++ console.log('processing message:', msg)++ // Skip already seen messages+ if (seenMessageIds.has(msg.id)) {+ console.log('skipping duplicate message:', msg.id)+ return null+ }++ seenMessageIds.add(msg.id)++ return {+ id: msg.id,+ content: msg.content || '[empty message]',+ // Messages from m13v_ (974812370868269098) are not fromUser+ fromUser: msg.author?.id !== M13V_ID,+ timestamp: msg.timestamp+ }+ }).filter(Boolean)++ console.log('transformed messages:', transformedMessages)++ if (transformedMessages.length > 0) {+ setMessages(prev => [...prev, ...transformedMessages])+ }+ }+ } catch (error) {+ console.error('failed to fetch messages:', error)+ }+ }, 3000)++ return () => clearInterval(pollInterval)+ }, [showChat, sessionId])++ React.useEffect(() => {+ if (!showWebcam) return++ const wsHost = process.env.NEXT_PUBLIC_FOUNDER_WEBSOCKET_URL+ if (!wsHost) {+ setShowWebcam(false)+ return+ }++ let ws: WebSocket | null = null+ setIsLoadingWebcam(true) // Reset loading state when connecting++ try {+ ws = new WebSocket(`wss://${wsHost}`)+ let processingFrame = false++ ws.onmessage = async (event) => {+ if (processingFrame || !event.data || !imgRef.current) return+ processingFrame = true++ try {+ const blob = new Blob([event.data], { type: 'image/jpeg' })+ const url = URL.createObjectURL(blob)++ await new Promise((resolve) => {+ if (!imgRef.current) return resolve(null)+ imgRef.current.onload = () => {+ URL.revokeObjectURL(url)+ setIsLoadingWebcam(false) // Disable loading once first frame arrives+ resolve(null)+ }+ imgRef.current.src = url+ })+ } finally {+ processingFrame = false+ }+ }++ ws.onopen = () => setIsWebsocketConnected(true)+ ws.onclose = () => {+ setIsWebsocketConnected(false)+ setShowWebcam(false)+ }+ ws.onerror = () => {+ setIsWebsocketConnected(false)+ setShowWebcam(false)+ }+ } catch {+ setShowWebcam(false)+ }++ return () => {+ if (ws) {+ ws.close()+ }+ }+ }, [showWebcam])++ // Play sound when new messages arrive+ React.useEffect(() => {+ if (messages.length > lastMessageCountRef.current) {+ // Only play for messages from Matt (not from user)+ const lastMessage = messages[messages.length - 1]+ if (!lastMessage.fromUser) {+ playMessageSound()+ }+ }+ lastMessageCountRef.current = messages.length+ }, [messages, playMessageSound])++ // Add scroll to bottom function+ const scrollToBottom = () => {+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })+ }++ // Scroll when messages update+ React.useEffect(() => {+ scrollToBottom()+ }, [messages])+const openLink = async () => {+ setShowWebcam(true) // Show webcam on clicktry {console.log('opening link:', supportLink)@@ -40,20 +220,101 @@ export function ChatButton() {console.error('failed to open link:', error)}}++ const closeChat = async () => {+ setShowWebcam(false)+ console.log('closing founder chat webcam')++ try {+ await fetch('/api/messages', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ message: '👋 User closed founder chat webcam',+ sessionId: crypto.randomUUID(),+ userAgent: window.navigator.userAgent,+ isSystem: true+ })+ })+ } catch (error) {+ console.error('failed to notify about webcam close:', error)+ }+ }- // Don't render button in Tauri environment- const isTauri = typeof window !== 'undefined' && (- window.__TAURI__ ||- window.location.protocol === 'tauri:' ||- window.location.protocol === 'asset:' ||- window.location.hostname === 'localhost' ||- window.location.hostname === '127.0.0.1'- )+ const sendMessage = async (text: string) => {+ if (!text.trim() || !sessionId) return++ setIsSending(true)+ try {+ const response = await fetch('/api/messages', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ message: text,+ sessionId,+ userAgent: window.navigator.userAgent,+ })+ })++ const data = await response.json()+ console.log('message response:', data)++ if (!response.ok) {+ throw new Error(data.error || 'Failed to send message')+ }++ setMessages(prev => [...prev, {+ id: crypto.randomUUID(),+ content: text,+ fromUser: true,+ timestamp: new Date().toISOString()+ }])+ setMessage('')+ } catch (error) {+ console.error('failed to send message:', error)+ } finally {+ setIsSending(false)+ }+ }- if (isTauri) {- return null+ const openChat = async () => {+ try {+ // Send notification first+ await fetch('/api/messages', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ message: '👋 User opened founder chat',+ sessionId: crypto.randomUUID(),+ userAgent: window.navigator.userAgent,+ isSystem: true+ })+ })++ // Then show chat and webcam+ setShowChat(true)+ setShowWebcam(true)+ } catch (error) {+ console.error('failed to notify about chat open:', error)+ // Still open chat even if notification fails+ setShowChat(true)+ setShowWebcam(true)+ }}+ // Don't render button in Tauri environment+ // const isTauri = typeof window !== 'undefined' && (+ // window.__TAURI__ ||+ // window.location.protocol === 'tauri:' ||+ // window.location.protocol === 'asset:' ||+ // window.location.hostname === 'localhost' ||+ // window.location.hostname === '127.0.0.1'+ // )++ // if (isTauri) {+ // return null+ // }+return (<motion.divclassName="fixed bottom-2 right-2 z-50"@@ -61,14 +322,158 @@ export function ChatButton() {animate={{ opacity: 1, scale: 1 }}whileHover={{ scale: 1.05 }}>- <Button- onClick={openLink}- size="sm"- className="rounded-full shadow-lg"- >- <MessageCircle className="mr-1 h-4 w-4" />- talk to founder- </Button>+ <div className="flex flex-col items-end gap-2">+ {showWebcam && isWebsocketConnected && (+ <motion.div+ initial={{ opacity: 0, y: 20 }}+ animate={{ opacity: 1, y: 0 }}+ transition={{ duration: 0.3 }}+ className="relative"+ >+ <Button+ onClick={closeChat}+ size="sm"+ variant="outline"+ className="absolute top-2 right-2 h-6 w-6 rounded-full p-0 bg-black/80 text-white hover:bg-black/90 z-10"+ >+ ×+ </Button>++ {isLoadingWebcam && (+ <div className="absolute inset-0 flex items-center justify-center bg-black/90 rounded-lg z-0">+ <div className="flex flex-col items-center gap-2">+ <div className="w-8 h-8 border-2 border-white/20 border-t-white rounded-full animate-spin" />+ <span className="text-xs text-white/80">connecting...</span>+ </div>+ </div>+ )}++ <img+ ref={imgRef}+ className="w-48 h-36 rounded-lg shadow-lg object-cover"+ alt="founder webcam"+ />+ <div className="absolute top-2 left-2 flex items-center gap-2 bg-black/80 rounded-full px-2 py-1 group cursor-help z-10">+ <VideoOff className="h-3 w-3 text-white" />+ <MicOff className="h-3 w-3 text-white" />+ <span className="absolute left-0 -bottom-8 hidden group-hover:block text-xs text-white bg-black/80 px-2 py-1 rounded-full whitespace-nowrap">+ viewing only - your camera is off+ </span>+ </div>+ </motion.div>+ )}+ {!showChat && (+ <div className="relative">+ <motion.div+ whileHover={{ scale: 1.05 }}+ whileTap={{ scale: 0.95 }}+ >+ <Button+ onClick={openChat}+ size="sm"+ variant="outline"+ className="rounded-full shadow-lg bg-black text-white hover:bg-black/90 hover:text-white"+ >+ <MessageCircle className="mr-1 h-4 w-4" />+ talk to founder+ </Button>+ </motion.div>+ <motion.div+ animate={{+ scale: [1, 1.2, 1],+ opacity: [1, 0.7, 1]+ }}+ transition={{+ duration: 2,+ repeat: Infinity,+ ease: "easeInOut"+ }}+ className="absolute -top-2 -right-2 flex items-center gap-1 bg-black/80 rounded-full px-2 py-0.5"+ >+ <div className="w-2 h-2 rounded-full bg-green-500" />+ <span className="text-xs text-white font-medium">online</span>+ </motion.div>+ </div>+ )}+ {showChat && (+ <motion.div+ initial={{ opacity: 0, y: 20 }}+ animate={{ opacity: 1, y: 0 }}+ className="bg-black/90 p-4 rounded-lg shadow-lg w-80 max-h-[500px] flex flex-col"+ >+ <div className="flex justify-between items-center mb-3">+ <span className="text-white text-sm">Chat with Matt</span>+ <Button+ onClick={() => {+ setShowChat(false)+ // Send notification when closing chat+ fetch('/api/messages', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ message: '👋 User closed founder chat',+ sessionId: crypto.randomUUID(),+ userAgent: window.navigator.userAgent,+ isSystem: true+ })+ }).catch(error => {+ console.error('failed to notify about chat close:', error)+ })+ }}+ size="sm"+ variant="ghost"+ className="h-6 w-6 rounded-full p-0 text-white hover:bg-white/20"+ >+ ×+ </Button>+ </div>++ <div className="flex-1 overflow-y-auto mb-3 space-y-2">+ {messages.map(msg => (+ <div+ key={msg.id}+ className={`flex ${msg.fromUser ? 'justify-end' : 'justify-start'}`}+ >+ <div className={`+ max-w-[80%] rounded-lg px-3 py-2 text-sm+ ${msg.fromUser+ ? 'bg-blue-500 text-white'+ : 'bg-white/10 text-white'}+ `}>+ {msg.content}+ </div>+ </div>+ ))}+ {/* Add div ref for scrolling */}+ <div ref={messagesEndRef} />+ </div>++ <div className="flex gap-2">+ <textarea+ value={message}+ onChange={(e) => setMessage(e.target.value)}+ className="flex-1 bg-white/10 text-white rounded p-2 text-sm"+ placeholder="Type your message..."+ rows={1}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault()+ sendMessage(message)+ }+ }}+ />+ <Button+ onClick={() => sendMessage(message)}+ disabled={isSending || !message.trim()}+ size="sm"+ className="bg-white text-black hover:bg-white/90"+ >+ Send+ </Button>+ </div>+ </motion.div>+ )}+ </div></motion.div>)}\ No newline at end of filediff --git a/pipes/meeting/src/components/live-transcription/hooks/ai-client.ts b/pipes/meeting/src/components/live-transcription/hooks/ai-client.tsnew file mode 100644index 000000000..0ccc8360a--- /dev/null+++ b/pipes/meeting/src/components/live-transcription/hooks/ai-client.ts@@ -0,0 +1,79 @@+import { OpenAI } from "openai"+import type { Settings } from "@screenpipe/browser"+import pThrottle from "p-throttle"++interface RetryOptions {+ maxRetries?: number+ initialDelay?: number+}++// Add rate limit tracking+const rateLimitState = {+ isLimited: false,+ resetTime: 0,+ backoffUntil: 0+}++// Update throttle to be more conservative+const throttle = pThrottle({+ limit: 2, // reduced from 3+ interval: 2000, // increased from 1000+})++export function createAiClient(settings: Settings) {+ return new OpenAI({+ apiKey: settings.aiProviderType === "screenpipe-cloud"+ ? settings.user.token+ : settings.openaiApiKey,+ baseURL: settings.aiUrl,+ dangerouslyAllowBrowser: true,+ })+}++// Throttled wrapper for OpenAI calls with retry logic+export const callOpenAI = throttle(async (+ openai: OpenAI,+ params: Parameters<typeof openai.chat.completions.create>[0],+ options: RetryOptions = {}+) => {+ const { maxRetries = 3, initialDelay = 1000 } = options+ let lastError: Error | null = null++ // Check if we're in backoff period+ if (Date.now() < rateLimitState.backoffUntil) {+ throw new Error('rate limit backoff in progress')+ }++ for (let attempt = 0; attempt < maxRetries; attempt++) {+ try {+ return await openai.chat.completions.create(params)+ } catch (error: any) {+ lastError = error+ console.warn(`ai call failed (attempt ${attempt + 1}/${maxRetries}):`, {+ error: error.message,+ status: error.status,+ type: error.type+ })++ if (error.status === 429) { // Rate limit+ rateLimitState.isLimited = true+ rateLimitState.backoffUntil = Date.now() + (initialDelay * Math.pow(2, attempt))+ console.log(`rate limit hit, backing off until ${new Date(rateLimitState.backoffUntil).toISOString()}`)+ throw error // Don't retry on rate limit, let caller handle+ }++ if (error.status === 503) { // Service unavailable+ const delay = initialDelay * Math.pow(1.5, attempt)+ await new Promise(resolve => setTimeout(resolve, delay))+ continue+ }++ // Don't retry on auth errors or invalid requests+ if (error.status === 401 || error.status === 400) {+ throw error+ }+ }+ }++ throw lastError || new Error('max retries exceeded')+})\ No newline at end of filediff --git a/pipes/meeting/src/components/live-transcription/hooks/ai-create-all-notes.ts b/pipes/meeting/src/components/live-transcription/hooks/ai-create-all-notes.tsindex 7eb2b9d15..a971c1a49 100644--- a/pipes/meeting/src/components/live-transcription/hooks/ai-create-all-notes.ts+++ b/pipes/meeting/src/components/live-transcription/hooks/ai-create-all-notes.ts@@ -1,6 +1,7 @@import { OpenAI } from "openai"import type { Settings } from "@screenpipe/browser"import { Meeting } from "../../meeting-history/types"+import { callOpenAI, createAiClient } from "./ai-client"export interface MeetingAnalysis {facts: string[]@@ -18,7 +19,8 @@ async function extractFacts(): Promise<string[]> {const systemPrompt = `extract meeting facts if any`console.log("extracting facts from meeting", { systemPrompt })- const response = await openai.chat.completions.create({++ const response = await callOpenAI(openai, {model: settings.aiModel,messages: [{@@ -30,14 +32,18 @@ async function extractFacts(content: `meeting: ${title}\n\ntranscript:\n${transcript}`}],- temperature: 0.1, // very low for factual accuracy+ temperature: 0.1,max_tokens: 500,})-- return response.choices[0]?.message?.content- ?.split('\n')- .filter(fact => fact.trim())- .map(fact => fact.replace(/^[•-]\s*/, '').trim()) || []++ // Handle both streaming and non-streaming responses+ if (response && 'choices' in response && Array.isArray(response.choices)) {+ return response.choices[0]?.message?.content+ ?.split('\n')+ .filter(fact => fact.trim())+ .map(fact => fact.replace(/^[•-]\s*/, '').trim()) || []+ }+ return []}async function extractEvents(@@ -48,7 +54,8 @@ async function extractEvents(): Promise<string[]> {const systemPrompt = `extract events of the meeting if any`console.log("extracting discussed events from meeting", { systemPrompt })- const response = await openai.chat.completions.create({++ const response = await callOpenAI(openai, {model: settings.aiModel,messages: [{@@ -64,10 +71,13 @@ async function extractEvents(max_tokens: 500,})- return response.choices[0]?.message?.content- ?.split('\n')- .filter(event => event.trim())- .map(event => event.replace(/^[•-]\s*/, '').trim()) || []+ if (response && 'choices' in response && Array.isArray(response.choices)) {+ return response.choices[0]?.message?.content+ ?.split('\n')+ .filter(event => event.trim())+ .map(event => event.replace(/^[•-]\s*/, '').trim()) || []+ }+ return []}async function extractFlow(@@ -78,7 +88,8 @@ async function extractFlow(): Promise<string[]> {const systemPrompt = `in a few words what the meeting is`console.log("extracting meeting flow", { systemPrompt })- const response = await openai.chat.completions.create({++ const response = await callOpenAI(openai, {model: settings.aiModel,messages: [{@@ -94,10 +105,13 @@ async function extractFlow(max_tokens: 500,})- return response.choices[0]?.message?.content- ?.split('\n')- .filter(flow => flow.trim())- .map(flow => flow.replace(/^[•-]\s*/, '').trim()) || []+ if (response && 'choices' in response && Array.isArray(response.choices)) {+ return response.choices[0]?.message?.content+ ?.split('\n')+ .filter(flow => flow.trim())+ .map(flow => flow.replace(/^[•-]\s*/, '').trim()) || []+ }+ return []}async function extractDecisions(@@ -108,7 +122,8 @@ async function extractDecisions(): Promise<string[]> {const systemPrompt = `extract decisions from transcript if any`console.log("extracting decisions and next steps", { systemPrompt })- const response = await openai.chat.completions.create({++ const response = await callOpenAI(openai, {model: settings.aiModel,messages: [{@@ -124,23 +139,20 @@ async function extractDecisions(max_tokens: 500,})- return response.choices[0]?.message?.content- ?.split('\n')- .filter(decision => decision.trim())- .map(decision => decision.replace(/^[•-]\s*/, '').trim()) || []+ if (response && 'choices' in response && Array.isArray(response.choices)) {+ return response.choices[0]?.message?.content+ ?.split('\n')+ .filter(decision => decision.trim())+ .map(decision => decision.replace(/^[•-]\s*/, '').trim()) || []+ }+ return []}export async function generateMeetingNotes(meeting: Meeting,settings: Settings): Promise<MeetingAnalysis> {- const openai = new OpenAI({- apiKey: settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,- dangerouslyAllowBrowser: true,- })+ const openai = createAiClient(settings)try {console.log("analyzing meeting:", {@@ -167,17 +179,38 @@ export async function generateMeetingNotes(focus on what's most relevant and important from my perspective.write in a natural, first-person style and return as bullet points.`- // Run all extractions in parallel with enhanced context- const [facts, events, flow, decisions] = await Promise.all([- extractFacts(`transcript:\n${transcript}\n\nexisting notes:\n${existingNotes}`, title, openai, settings),- extractEvents(`transcript:\n${transcript}\n\nexisting notes:\n${existingNotes}`, title, openai, settings),- extractFlow(`transcript:\n${transcript}\n\nexisting notes:\n${existingNotes}`, title, openai, settings),- extractDecisions(`transcript:\n${transcript}\n\nexisting notes:\n${existingNotes}`, title, openai, settings)- ])+ // Run extractions sequentially instead of parallel to avoid rate limits+ const facts = await extractFacts(+ `transcript:\n${transcript}\n\nexisting notes:\n${existingNotes}`,+ title,+ openai,+ settings+ )++ const events = await extractEvents(+ `transcript:\n${transcript}\n\nexisting notes:\n${existingNotes}`,+ title,+ openai,+ settings+ )++ const flow = await extractFlow(+ `transcript:\n${transcript}\n\nexisting notes:\n${existingNotes}`,+ title,+ openai,+ settings+ )++ const decisions = await extractDecisions(+ `transcript:\n${transcript}\n\nexisting notes:\n${existingNotes}`,+ title,+ openai,+ settings+ )- // Generate final combined notes with enhanced context- console.log("generating final combined notes with manual notes context", { systemPrompt })- const response = await openai.chat.completions.create({+ // Generate final combined notes+ console.log("generating final combined notes with manual notes context")+ const response = await callOpenAI(openai, {model: settings.aiModel,messages: [{@@ -207,12 +240,17 @@ export async function generateMeetingNotes(],temperature: 0.3,max_tokens: 1000,+ }, {+ maxRetries: 3,+ initialDelay: 2000})- const notes = response.choices[0]?.message?.content- ?.split('\n')- .filter(note => note.trim())- .map(note => note.replace(/^[•-]\s*/, '').trim()) || []+ const notes = response && 'choices' in response && Array.isArray(response.choices)+ ? response.choices[0]?.message?.content+ ?.split('\n')+ .filter(note => note.trim())+ .map(note => note.replace(/^[•-]\s*/, '').trim()) || []+ : []console.log("completed meeting analysis:", {facts_count: facts.length,@@ -225,8 +263,8 @@ export async function generateMeetingNotes(const summarySystemPrompt = `you are me, summarize these meeting notes in 3-4 key points that i should remember.and return as bullet points.`- console.log("generating concise summary", { summarySystemPrompt })- const summaryResponse = await openai.chat.completions.create({+ console.log("generating concise summary")+ const summaryResponse = await callOpenAI(openai, {model: settings.aiModel,messages: [{@@ -242,10 +280,12 @@ export async function generateMeetingNotes(max_tokens: 300,})- const summary = summaryResponse.choices[0]?.message?.content- ?.split('\n')- .filter(note => note.trim())- .map(note => note.replace(/^[•-]\s*/, '').trim()) || []+ const summary = summaryResponse && 'choices' in summaryResponse && Array.isArray(summaryResponse.choices)+ ? summaryResponse.choices[0]?.message?.content+ ?.split('\n')+ .filter(note => note.trim())+ .map(note => note.replace(/^[•-]\s*/, '').trim()) || []+ : []return {facts,@@ -255,7 +295,11 @@ export async function generateMeetingNotes(summary}} catch (error) {- console.error("error analyzing meeting:", error)+ console.error("error analyzing meeting:", {+ error,+ meeting_id: meeting.id,+ segments_count: meeting.segments?.length || 0+ })return {facts: [],events: [],diff --git a/pipes/meeting/src/components/live-transcription/hooks/ai-create-note-based-on-chunk.ts b/pipes/meeting/src/components/live-transcription/hooks/ai-create-note-based-on-chunk.tsindex c4863dc23..552b5cd64 100644--- a/pipes/meeting/src/components/live-transcription/hooks/ai-create-note-based-on-chunk.ts+++ b/pipes/meeting/src/components/live-transcription/hooks/ai-create-note-based-on-chunk.ts@@ -1,59 +1,74 @@-import { OpenAI } from "openai"import type { Settings } from "@screenpipe/browser"import { TranscriptionChunk } from "../../meeting-history/types"+import { callOpenAI, createAiClient } from "./ai-client"export async function generateMeetingNote(chunks: TranscriptionChunk[],- settings: Settings+ settings: Settings,+ existingNotes: string[] = []): Promise<string> {- const openai = new OpenAI({- apiKey: settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,- dangerouslyAllowBrowser: true,- })+ const openai = createAiClient(settings)+ const transcript = chunks+ .map(c => `[${c.speaker ?? 'unknown'}]: ${c.text}`)+ .join("\n")try {console.log("generating meeting note from chunks:", {- chunks_count: chunks.length+ chunks_count: chunks.length,+ existing_notes_count: existingNotes.length})- const transcript = chunks- .map(c => `[${c.speaker ?? 'unknown'}]: ${c.text}`)- .join("\n")+ const existingNotesContext = existingNotes.length > 0+ ? `existing notes from this meeting:\n${existingNotes.join("\n")}\n\n`+ : ""const messages = [{role: "system" as const,- content: `generate a single, concise first-person note about what happened in this meeting segment.+ content: `generate a single, concise note about what happened in this segment.be factual and specific.- use "i" perspective.+ focus on the key point or action item.keep it a few word sentence.- do not use quotes.`+ do not use quotes.+ do not use wrapping words like "disucssion on", jump straight into note.+ avoid repeating information from existing notes.`},{role: "user" as const,- content: `conversation transcript:+ content: `${existingNotesContext}conversation transcript:${transcript}`}]- console.log("sending request to openai for note generation")- const response = await openai.chat.completions.create({+ // console.log("sending request to openai for note generation")+ const response = await callOpenAI(openai, {model: settings.aiModel,messages,temperature: 0.3,max_tokens: 60,+ }, {+ maxRetries: 3,+ initialDelay: 1000})- const note = response.choices[0]?.message?.content?.trim() || "failed to generate note"+ // Handle both streaming and non-streaming responses+ const note = 'choices' in response+ ? response.choices[0]?.message?.content?.trim() || "failed to generate note"+ : "failed to generate note"- console.log("generated note:", { note })+ // console.log("AI note generated:", { note })return note} catch (error) {- console.error("error generating meeting note:", error)- return "failed to generate note"+ // Log error details for debugging but with lower severity+ console.log("note generation failed:", {+ error,+ chunks_count: chunks.length,+ transcript_length: transcript.length,+ has_existing_notes: existingNotes.length > 0+ })++ // Return empty string instead of error message to avoid showing errors in UI+ return ""}}\ No newline at end of filediff --git a/pipes/meeting/src/components/live-transcription/hooks/ai-create-note.ts b/pipes/meeting/src/components/live-transcription/hooks/ai-create-note.tsindex 4c29e6aa4..d2c4dcab5 100644--- a/pipes/meeting/src/components/live-transcription/hooks/ai-create-note.ts+++ b/pipes/meeting/src/components/live-transcription/hooks/ai-create-note.ts@@ -1,6 +1,6 @@-import { OpenAI } from "openai"import type { Settings } from "@screenpipe/browser"-import { TranscriptionChunk, Note } from "../../meeting-history/types"+import { Note } from "../../meeting-history/types"+import { callOpenAI, createAiClient } from "./ai-client"interface NoteContext {note: Note@@ -20,13 +20,7 @@ export async function improveNote(model: settings.aiModel})- const openai = new OpenAI({- apiKey: settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,- dangerouslyAllowBrowser: true,- })+ const openai = createAiClient(settings)try {console.log("improving note with full context:", {@@ -39,12 +33,6 @@ export async function improveNote(}})- console.log("improving note:", {- note_text: context.note.text,- context: context.context,- title: context.title- })-const messages = [{role: "system" as const,@@ -70,14 +58,19 @@ export async function improveNote(]console.log("sending request to openai for note improvement")- const response = await openai.chat.completions.create({+ const response = await callOpenAI(openai, {model: settings.aiModel,messages,temperature: 0.3,max_tokens: context.note.text.length * 2,+ }, {+ maxRetries: 3,+ initialDelay: 1000})- const improved = response.choices[0]?.message?.content?.trim() || context.note.text+ const improved = 'choices' in response+ ? response.choices[0]?.message?.content?.trim() || context.note.text+ : context.note.textconsole.log("improved note:", {original: context.note.text,@@ -86,9 +79,10 @@ export async function improveNote(return improved} catch (error) {- console.error("error improving note (full):", {+ console.error("error improving note:", {error,- context,+ note_text: context.note.text,+ title: context.title,settings: {provider: settings.aiProviderType,model: settings.aiModeldiff --git a/pipes/meeting/src/components/live-transcription/hooks/ai-improve-chunk-transcription.ts b/pipes/meeting/src/components/live-transcription/hooks/ai-improve-chunk-transcription.tsindex 8d892212a..eedcffa94 100644--- a/pipes/meeting/src/components/live-transcription/hooks/ai-improve-chunk-transcription.ts+++ b/pipes/meeting/src/components/live-transcription/hooks/ai-improve-chunk-transcription.ts@@ -1,4 +1,4 @@-import { OpenAI } from "openai"+import { callOpenAI, createAiClient } from "./ai-client"import type { Settings } from "@screenpipe/browser"import { TranscriptionChunk } from "../../meeting-history/types"import { VocabularyEntry, getVocabularyEntries } from "./storage-vocabulary"@@ -16,25 +16,9 @@ export async function improveTranscription(context: TranscriptionContext,settings: Settings): Promise<string> {- const openai = new OpenAI({- apiKey: settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,- dangerouslyAllowBrowser: true,- })+ const openai = createAiClient(settings)try {- console.log("improving transcription quality:", {- text_length: text.length,- context: {- has_title: !!context.meetingTitle,- chunks_count: context.recentChunks.length,- notes_count: context.notes?.length || 0,- vocab_count: context.vocabulary?.length || 0- }- })-// Build context from recent chunksconst recentTranscript = context.recentChunks.map(c => `[${c.speaker ?? 'unknown'}]: ${c.text}`)@@ -53,7 +37,7 @@ export async function improveTranscription(role: "system" as const,content: `you are an expert at improving speech-to-text transcription quality.focus on fixing common transcription errors while preserving the original meaning.- use provided vocabulary corrections and meeting context to improve accuracy.+ use provided vocabulary corrections only for a very obvious very close match.maintain original capitalization and punctuation style.return only the improved text without any quotation marks or additional commentary.`},@@ -76,32 +60,46 @@ export async function improveTranscription(}]- console.log("sending request to openai for transcription improvement")- const response = await openai.chat.completions.create({+ // console.log("sending request to openai for transcription improvement")+ const response = await callOpenAI(openai, {model: settings.aiModel,messages,- temperature: 0.3, // lower temperature for more consistent corrections- max_tokens: text.length * 2, // allow some expansion+ temperature: 0.3,+ max_tokens: text.length * 2,+ }, {+ maxRetries: 3,+ initialDelay: 1000})- let improved = response.choices[0]?.message?.content?.trim() || text+ let improved = 'choices' in response+ ? response.choices[0]?.message?.content?.trim() || text+ : text// Remove any quotation marks from the responseimproved = improved.replace(/^["']|["']$/g, '').trim()- console.log("improved transcription:", {- original: text,- improved- })+ // console.log("improved transcription:", {+ // original: text,+ // improved+ // })return improved} catch (error) {- console.error("error improving transcription:", error)+ // Log error details but at debug level+ console.debug("[transcription-improve] failed:", {+ error,+ text_length: text.length,+ context: {+ title: context.meetingTitle,+ chunks: context.recentChunks.length+ }+ })+ // Silently fallback to original textreturn text}}-// Helper to improve multiple chunks in parallel+// Update batch processing to use throttlingexport async function improveTranscriptionBatch(chunks: TranscriptionChunk[],meeting: Meeting,@@ -109,9 +107,10 @@ export async function improveTranscriptionBatch(): Promise<Record<number, string>> {const results: Record<number, string> = {}const vocabulary = await getVocabularyEntries()+ const openai = createAiClient(settings)- // Process in parallel with concurrency limit- const concurrencyLimit = 3+ // Process in smaller batches with built-in throttling+ const concurrencyLimit = 2 // Reduced from 3const batches = []for (let i = 0; i < chunks.length; i += concurrencyLimit) {@@ -127,8 +126,17 @@ export async function improveTranscriptionBatch(vocabulary}- const improved = await improveTranscription(chunk.text, context, settings)- results[idx] = improved+ try {+ const improved = await improveTranscription(chunk.text, context, settings)+ results[idx] = improved+ } catch (error) {+ // Log at debug level for troubleshooting+ console.debug("[transcription-batch] chunk failed:", {+ chunk_idx: idx,+ error+ })+ results[idx] = chunk.text // Silently fallback to original+ }})await Promise.all(promises)diff --git a/pipes/meeting/src/components/live-transcription/hooks/ai-meeting-summary.ts b/pipes/meeting/src/components/live-transcription/hooks/ai-meeting-summary.tsnew file mode 100644index 000000000..c2531a37f--- /dev/null+++ b/pipes/meeting/src/components/live-transcription/hooks/ai-meeting-summary.ts@@ -0,0 +1,178 @@+import type { Settings } from "@screenpipe/browser"+import { LiveMeetingData } from "@/components/live-transcription/hooks/storage-for-live-meeting"+import { callOpenAI, createAiClient } from "./ai-client"++export async function generateMeetingSummary(+ meeting: LiveMeetingData,+ settings: Settings+): Promise<string> {+ const openai = createAiClient(settings)++ try {+ console.log(+ "generating ai summary for meeting:",+ {+ startTime: meeting.startTime,+ chunks_count: meeting.chunks.length,+ notes_count: meeting.notes.length,+ total_transcript_length: meeting.mergedChunks.reduce((acc, s) => acc + s.text.length, 0),+ total_notes_length: meeting.notes.reduce((acc, n) => acc + n.text.length, 0)+ }+ )++ // Create prompt from meeting data using mergedChunks+ const transcriptContent = meeting.mergedChunks+ .map(+ (s) =>+ `[${meeting.speakerMappings[s.speaker || 'speaker_0'] || s.speaker || 'speaker_0'}]: ${meeting.editedMergedChunks[s.id] || s.text}`+ )+ .join("\n")++ // Add notes context if available+ const notesContext = meeting.notes.length > 0+ ? `\nMeeting notes:\n${meeting.notes.map(n => n.text).join("\n")}`+ : ""++ const currentSummary = meeting.analysis?.summary+ const summaryContext = currentSummary+ ? `\nCurrent summary: "${currentSummary}"\nPlease generate a new summary that might be more accurate.`+ : ""++ const currentTitle = meeting.title+ const titleContext = currentTitle+ ? `\nMeeting title: "${currentTitle}"`+ : ""++ // First AI call for detailed analysis+ console.log("sending request to openai for meeting analysis")+ const analysisResponse = await callOpenAI(openai, {+ model: settings.aiModel,+ messages: [+ {+ role: "system" as const,+ content: "you are a meeting participant. analyze our discussion to understand: who was there, what we talked about, what we decided, and what our next steps are. be specific but concise.",+ },+ {+ role: "user" as const,+ content: `please analyze our meeting:${titleContext}\n\n${transcriptContent}${notesContext}`,+ },+ ],+ temperature: 0.7,+ max_tokens: 500,+ }, {+ maxRetries: 3,+ initialDelay: 1500+ })++ const analysis = 'choices' in analysisResponse+ ? analysisResponse.choices[0]?.message?.content?.trim() || ""+ : ""+ console.log("generated meeting analysis:", analysis.slice(0, 100) + "...")++ // Second AI call for final concise summary using the analysis+ console.log("sending request to openai for final meeting summary", {+ current_title: currentTitle,+ current_summary: currentSummary ? currentSummary.slice(0, 100) + "..." : null,+ analysis_sample: analysis.slice(0, 100) + "..."+ })++ const response = await callOpenAI(openai, {+ model: settings.aiModel,+ messages: [+ {+ role: "system" as const,+ content: "you are a meeting participant writing a quick summary (max 100 words) of what we just discussed. focus on our key decisions and next steps. use bullet points for clarity. write in first person plural (we/our). do not use markdown formatting.",+ },+ {+ role: "user" as const,+ content: `write a quick summary of our meeting (max 100 words). what did we discuss and decide? what are our next steps? do not use markdown formatting:+meeting title: ${titleContext}+${summaryContext}+our discussion details: ${analysis}++transcript:+${transcriptContent}+${notesContext}`,+ },+ ],+ temperature: 0.7,+ max_tokens: 200,+ }, {+ maxRetries: 3,+ initialDelay: 1500+ })++ const aiSummary = ('choices' in response+ ? response.choices[0]?.message?.content?.trim() || "no summary available"+ : "no summary available")+ .replace(/\*\*/g, '')+ .replace(/^#+\s*/gm, '')+ .replace(/^\s*[-*]\s*/gm, '• ')+ .trim()++ console.log("generated ai summary:", aiSummary.slice(0, 100) + "...")++ // Final AI call to condense the summary+ console.log("sending request to openai for condensed summary")+ const condensedResponse = await callOpenAI(openai, {+ model: settings.aiModel,+ messages: [+ {+ role: "system" as const,+ content: "you are a meeting participant writing a very brief summary (50 words) of what we just discussed. focus on our main points and next actions. use bullet points. write in first person plural (we/our). do not use markdown formatting.",+ },+ {+ role: "user" as const,+ content: `give me the key points from our meeting in 50 words or less:\n\n${aiSummary}`,+ },+ ],+ temperature: 0.7,+ max_tokens: 100,+ }, {+ maxRetries: 3,+ initialDelay: 1000+ })++ const condensedSummary = ('choices' in condensedResponse+ ? condensedResponse.choices[0]?.message?.content?.trim() || aiSummary+ : aiSummary)+ .replace(/\*\*/g, '')+ .replace(/^#+\s*/gm, '')+ .replace(/^\s*[-*]\s*/gm, '• ')+ .trim()++ console.log("generated condensed summary:", condensedSummary.slice(0, 100) + "...")++ return condensedSummary+ } catch (error) {+ console.error("error generating meeting summary:", error)+ return "failed to generate summary"+ }+}++// Helper function to generate summaries for multiple meetings+export async function generateMeetingSummaries(+ meetings: LiveMeetingData[],+ settings: Settings+): Promise<Record<string, string>> {+ const results: Record<string, string> = {}++ // Process meetings in parallel with a concurrency limit+ const concurrencyLimit = 2+ const chunks = []++ for (let i = 0; i < meetings.length; i += concurrencyLimit) {+ chunks.push(meetings.slice(i, i + concurrencyLimit))+ }++ for (const chunk of chunks) {+ const promises = chunk.map(async (meeting) => {+ const summary = await generateMeetingSummary(meeting, settings)+ results[meeting.startTime] = summary+ })++ await Promise.all(promises)+ }++ return results+}\ No newline at end of filediff --git a/pipes/meeting/src/components/live-transcription/hooks/ai-meeting-title.ts b/pipes/meeting/src/components/live-transcription/hooks/ai-meeting-title.tsnew file mode 100644index 000000000..b061b1f20--- /dev/null+++ b/pipes/meeting/src/components/live-transcription/hooks/ai-meeting-title.ts@@ -0,0 +1,110 @@+import type { Settings } from "@screenpipe/browser"+import { LiveMeetingData } from "@/components/live-transcription/hooks/storage-for-live-meeting"+import { callOpenAI, createAiClient } from "./ai-client"++export async function generateMeetingName(+ meeting: LiveMeetingData,+ settings: Settings+): Promise<string> {+ const openai = createAiClient(settings)++ try {+ console.log(+ "generating ai name for meeting:",+ {+ merged_chunks_count: meeting.mergedChunks.length,+ edited_chunks: Object.keys(meeting.editedMergedChunks || {}).length,+ notes_count: meeting.notes.length,+ has_analysis: !!meeting.analysis,+ title: meeting.title+ }+ )++ // Create prompt from chunks with edits and speaker mappings+ const transcriptSample = meeting.mergedChunks+ .map(chunk => {+ const text = meeting.editedMergedChunks[chunk.id] || chunk.text+ const speaker = meeting.speakerMappings[chunk.speaker || 'speaker_?'] || chunk.speaker || 'speaker_?'+ return `[${speaker}]: ${text}`+ })+ .join("\n")++ // Add notes and analysis context+ const notesContext = meeting.notes.length > 0+ ? `\nMeeting notes:\n${meeting.notes.map(n => n.text).join("\n")}`+ : ""++ const analysisContext = meeting.analysis?.summary+ ? `\nMeeting summary:\n${meeting.analysis.summary}`+ : ""++ const currentTitle = meeting.title+ const titleContext = currentTitle+ ? `\nCurrent title: "${currentTitle}"\nPlease generate a new title that might be more accurate.`+ : ""++ const messages = [+ {+ role: "system" as const,+ content: "you are a helpful assistant that generates concise (max 6 words) but informative meeting titles. include key facts like participants, purpose, or project name if available. avoid generic descriptions.",+ },+ {+ role: "user" as const,+ content: `analyze the meeting context and generate a factual title that captures WHO (key participants/teams), WHAT (main topic/project), or WHY (purpose/goal) if these are clear from the context. keep it under 6 words:${titleContext}\n\n${transcriptSample}${notesContext}${analysisContext}`,+ },+ ]++ console.log("sending request to openai for meeting name", {+ current_title: currentTitle,+ segments_sample: transcriptSample.slice(0, 100) + "..."+ })++ const response = await callOpenAI(openai, {+ model: settings.aiModel,+ messages,+ temperature: 0.7,+ max_tokens: 20,+ }, {+ maxRetries: 3,+ initialDelay: 1000+ })++ const aiName = 'choices' in response+ ? response.choices[0]?.message?.content?.trim() || currentTitle || "untitled meeting"+ : currentTitle || "untitled meeting"++ const sanitizedName = aiName.replace(/["']/g, '').replace(/[^\w\s-]/g, ' ').trim()+ console.log("sanitized ai name:", sanitizedName)+ return sanitizedName+ } catch (error) {+ console.error("error generating meeting name:", error)+ return meeting.title || "untitled meeting"+ }+}++// Helper function to generate names for multiple meetings+export async function generateMeetingNames(+ meetings: LiveMeetingData[],+ settings: Settings+): Promise<Record<string, string>> {+ const results: Record<string, string> = {}++ // Process meetings in parallel with a concurrency limit+ const concurrencyLimit = 2 // Reduced from 3 to match other files+ const chunks = []++ for (let i = 0; i < meetings.length; i += concurrencyLimit) {+ chunks.push(meetings.slice(i, i + concurrencyLimit))+ }++ for (const chunk of chunks) {+ const promises = chunk.map(async (meeting) => {+ const name = await generateMeetingName(meeting, settings)+ results[meeting.id] = name+ })++ await Promise.all(promises)+ }++ return results+}\ No newline at end of filediff --git a/pipes/meeting/src/components/live-transcription/hooks/browser-stream-transcription-api.ts b/pipes/meeting/src/components/live-transcription/hooks/browser-stream-transcription-api.tsindex 85f679bfd..8d5a5978b 100644--- a/pipes/meeting/src/components/live-transcription/hooks/browser-stream-transcription-api.ts+++ b/pipes/meeting/src/components/live-transcription/hooks/browser-stream-transcription-api.ts@@ -3,11 +3,13 @@ import { useToast } from "@/hooks/use-toast"import { TranscriptionChunk } from '../../meeting-history/types'export function useBrowserTranscriptionStream(- setChunks: (updater: (prev: TranscriptionChunk[]) => TranscriptionChunk[]) => void+ onNewChunk: (chunk: TranscriptionChunk) => void) {const streamingRef = useRef(false)const socketRef = useRef<WebSocket | null>(null)const audioContextRef = useRef<AudioContext | null>(null)+ const mediaStreamRef = useRef<MediaStream | null>(null)+ const intentionalCloseRef = useRef(false)const { toast } = useToast()const startTranscriptionBrowser = useCallback(async () => {@@ -16,29 +18,31 @@ export function useBrowserTranscriptionStream(return}- // Use env var with fallback to hardcoded key+ intentionalCloseRef.current = false+ // Use env var with fallback to hardcoded key, move to backconst apiKey = process.env.NEXT_PUBLIC_DEEPGRAM_API_KEY || '646b887eceffbf128315d2f419e48a2ff174ab66'- console.log('using deepgram api key:', apiKey ? 'found' : 'not found')+ // console.log('using deepgram api key:', apiKey ? 'found' : 'not found')try {console.log('starting browser transcription stream...')- console.log('requesting user media...')+ // console.log('requesting user media...')const stream = await navigator.mediaDevices.getUserMedia({audio: {channelCount: 1,sampleRate: 16000}})- console.log('got media stream:', { tracks: stream.getTracks().length })+ mediaStreamRef.current = stream+ // console.log('got media stream:', { tracks: stream.getTracks().length })- console.log('initializing websocket connection to deepgram...')+ // console.log('initializing websocket connection to deepgram...')// Setup WebSocket connection with diarization enabledconst ws = new WebSocket('wss://api.deepgram.com/v1/listen?' + new URLSearchParams({encoding: 'linear16',sample_rate: '16000',channels: '1',- model: 'nova-2',+ model: 'nova-3',smart_format: 'true',diarize: 'true',interim_results: 'false',@@ -46,21 +50,21 @@ export function useBrowserTranscriptionStream(}),['token', apiKey])- console.log('websocket created, waiting for open...')+ // console.log('websocket created, waiting for open...')// Setup audio processing- console.log('setting up audio context...')+ // console.log('setting up audio context...')const audioContext = new AudioContext({ sampleRate: 16000 })const source = audioContext.createMediaStreamSource(stream)const processor = audioContext.createScriptProcessor(2048, 1, 1)- console.log('audio context state:', audioContext.state)+ // console.log('audio context state:', audioContext.state)source.connect(processor)processor.connect(audioContext.destination)- console.log('audio processing chain connected')+ // console.log('audio processing chain connected')ws.onopen = () => {- console.log('deepgram websocket opened')+ // console.log('deepgram websocket opened')streamingRef.current = trueprocessor.onaudioprocess = (e) => {@@ -70,42 +74,26 @@ export function useBrowserTranscriptionStream(ws.send(pcmData.buffer)}}- console.log('audio processor handler attached')+ // console.log('audio processor handler attached')}ws.onmessage = (event) => {const data = JSON.parse(event.data)- // console.log('received websocket message:', data.type)+if (data.type === 'Results') {const words = data.channel.alternatives[0].words || []if (data.is_final && words.length > 0) {- const text = data.channel.alternatives[0].transcript- const speaker = `speaker_${words[0].speaker || 0}`-- console.log('new browser transcription:', {- text,- speaker,- words,- timestamp: new Date().toISOString()- })-const chunk: TranscriptionChunk = {id: Date.now(),timestamp: new Date().toISOString(),- text,+ text: data.channel.alternatives[0].transcript,isInput: true,device: 'browser',- speaker+ speaker: `speaker_${words[0].speaker || 0}`}- // Use callback form to ensure we always have latest state- setChunks(prev => {- console.log('updating chunks:', {- prevCount: prev.length,- newChunk: chunk- })- return [...prev, chunk]- })+ // console.log('transcription:', { speaker: chunk.speaker, text: chunk.text })+ onNewChunk(chunk)}}}@@ -127,11 +115,13 @@ export function useBrowserTranscriptionStream(console.log('deepgram websocket closed', {code: event.code,reason: event.reason,- wasClean: event.wasClean+ wasClean: event.wasClean,+ intentional: intentionalCloseRef.current})streamingRef.current = false- // Attempt reconnection if not intentionally closed- if (event.code !== 1000) {++ // Only attempt reconnection if not intentionally closed+ if (!intentionalCloseRef.current && event.code !== 1000) {console.log('attempting to reconnect...')setTimeout(startTranscriptionBrowser, 2000)}@@ -149,18 +139,33 @@ export function useBrowserTranscriptionStream(variant: "destructive"})}- }, [toast, setChunks])+ }, [toast, onNewChunk])const stopTranscriptionBrowser = useCallback(() => {+ console.log('stopping browser transcription...')+ intentionalCloseRef.current = true++ // Close websocketif (socketRef.current) {socketRef.current.send(JSON.stringify({ type: 'CloseStream' }))socketRef.current.close()socketRef.current = null}++ // Stop all media tracks+ if (mediaStreamRef.current) {+ mediaStreamRef.current.getTracks().forEach(track => {+ track.stop()+ })+ mediaStreamRef.current = null+ }++ // Close audio contextif (audioContextRef.current) {audioContextRef.current.close()audioContextRef.current = null}+streamingRef.current = falseconsole.log('browser transcription stopped')}, [])diff --git a/pipes/meeting/src/components/live-transcription/hooks/handle-new-chunk.ts b/pipes/meeting/src/components/live-transcription/hooks/handle-new-chunk.tsnew file mode 100644index 000000000..cac169e3d--- /dev/null+++ b/pipes/meeting/src/components/live-transcription/hooks/handle-new-chunk.ts@@ -0,0 +1,212 @@+import { TranscriptionChunk, Note } from "../../meeting-history/types"+import { LiveMeetingData } from "./storage-for-live-meeting"+import { improveTranscription } from './ai-improve-chunk-transcription'+import { generateMeetingNote } from './ai-create-note-based-on-chunk'+import { diffWords } from 'diff'+import type { Settings } from "@screenpipe/browser"++interface DiffChunk {+ value: string+ added?: boolean+ removed?: boolean+}++export interface ImprovedChunk {+ text: string+ diffs: DiffChunk[] | null+}++interface HandleNewChunkDeps {+ setData: (fn: (currentData: LiveMeetingData | null) => LiveMeetingData | null) => void+ setImprovingChunks: (fn: (prev: Record<number, boolean>) => Record<number, boolean>) => void+ setRecentlyImproved: (fn: (prev: Record<number, boolean>) => Record<number, boolean>) => void+ updateStore: (newData: LiveMeetingData) => Promise<boolean>+ settings: Settings+}++export function createHandleNewChunk(deps: HandleNewChunkDeps) {+ const { setData, setImprovingChunks, setRecentlyImproved, updateStore, settings } = deps+ const processingChunks = new Set<number>()+ let isProcessing = false++ // Add buffer for raw chunks+ const noteBuffer: TranscriptionChunk[] = []++ async function tryGenerateNote() {+ const now = Date.now()+ const totalText = noteBuffer.map(chunk => chunk.text).join(' ')+ const wordCount = totalText.split(/\s+/).length++ // console.log('note generation check:', {+ // bufferedChunks: noteBuffer.length,+ // wordCount,+ // meetsWordThreshold: wordCount >= 50,+ // bufferContent: totalText+ // })++ // Get current data to check if AI notes are enabled+ let shouldGenerate = false+ let existingNotes: string[] = []++ setData(currentData => {+ shouldGenerate = currentData?.isAiNotesEnabled ?? true+ existingNotes = currentData?.notes?.map(n => n.text) || []+ return currentData+ })++ // Early return if AI notes are disabled+ if (!shouldGenerate || wordCount < 50) {+ return+ }++ const note = await generateMeetingNote(+ noteBuffer,+ settings,+ existingNotes+ ).catch(error => {+ console.error('failed to generate note:', error)+ return null+ })++ setData(current => {+ if (note && current) {+ const timestamp = noteBuffer.length > 0+ ? new Date(noteBuffer[0].timestamp)+ : new Date(now)++ const newData = {+ ...current,+ notes: [...current.notes, {+ id: `note-${now}`,+ text: `• ${note}`,+ timestamp,+ type: 'auto'+ }]+ }+ void updateStore(newData)+ return newData+ }+ return current+ })+ // Clear buffer after successful note generation+ noteBuffer.length = 0+ }++ return async function handleNewChunk(chunk: TranscriptionChunk) {+ if (isProcessing) {+ console.log('skipping chunk processing - already processing another chunk')+ return+ }++ isProcessing = true+ try {+ // Add new chunk to note buffer immediately+ noteBuffer.push(chunk)+ void tryGenerateNote()++ setData(currentData => {+ if (!currentData) return null++ const chunks = [...currentData.chunks, chunk]++ const mergedChunks = chunks.reduce<TranscriptionChunk[]>((acc, curr) => {+ const prev = acc[acc.length - 1]++ if (prev && prev.speaker === curr.speaker) {+ prev.text += ' ' + curr.text+ return acc+ }++ acc.push(Object.assign({}, curr))+ return acc+ }, [])++ const previousMerged = mergedChunks.length > 1 ? mergedChunks[mergedChunks.length - 2] : null++ if (previousMerged &&+ settings.aiProviderType === "screenpipe-cloud" &&+ !currentData.editedMergedChunks[previousMerged.id] &&+ !processingChunks.has(previousMerged.id) &&+ currentData.isAiNotesEnabled) {++ console.log('processing chunk:', { id: previousMerged.id, text: previousMerged.text })+ processingChunks.add(previousMerged.id)+ setImprovingChunks((prev: Record<number, boolean>) => ({ ...prev, [previousMerged.id]: true }))++ const context = {+ meetingTitle: currentData.title || '',+ recentChunks: mergedChunks.slice(-3),+ notes: currentData.notes.map(note => note.text)+ }++ void improveTranscription(previousMerged.text, context, settings)+ .then(improved => {+ const diffs = diffWords(previousMerged.text, improved)++ processingChunks.delete(previousMerged.id)+ setImprovingChunks((prev: Record<number, boolean>) => {+ const next = { ...prev }+ delete next[previousMerged.id]+ return next+ })+ setRecentlyImproved((prev: Record<number, boolean>) => ({ ...prev, [previousMerged.id]: true }))++ setData(current => {+ if (!current) return null+ const newData = {+ ...current,+ editedMergedChunks: {+ ...current.editedMergedChunks,+ [previousMerged.id]: {+ text: improved,+ diffs+ }+ }+ }+ void updateStore(newData)+ return newData+ })++ if (improved) {+ const improvedChunk = {+ ...previousMerged,+ text: improved+ }+ noteBuffer.push(improvedChunk)+ void tryGenerateNote()+ }++ setTimeout(() => {+ setRecentlyImproved(prev => {+ const next = { ...prev }+ delete next[previousMerged.id]+ return next+ })+ }, 5000)+ })+ .catch(error => {+ console.error('failed to improve chunk:', error)+ processingChunks.delete(previousMerged.id)+ setImprovingChunks(prev => {+ const next = { ...prev }+ delete next[previousMerged.id]+ return next+ })+ })+ }++ const newData: LiveMeetingData = {+ ...currentData,+ chunks,+ mergedChunks,+ lastProcessedIndex: chunks.length+ }++ void updateStore(newData)+ return newData+ })+ } finally {+ isProcessing = false+ }+ }+}\ No newline at end of filediff --git a/pipes/meeting/src/components/live-transcription/hooks/screenpipe-stream-transcription-api.ts b/pipes/meeting/src/components/live-transcription/hooks/screenpipe-stream-transcription-api.tsindex 3817b862d..411edca6c 100644--- a/pipes/meeting/src/components/live-transcription/hooks/screenpipe-stream-transcription-api.ts+++ b/pipes/meeting/src/components/live-transcription/hooks/screenpipe-stream-transcription-api.ts@@ -1,7 +1,7 @@import { useRef, useCallback } from 'react'import { pipe } from "@screenpipe/browser"import { useToast } from "@/hooks/use-toast"-import { TranscriptionChunk, ServiceStatus } from '../../meeting-history/types'+import { TranscriptionChunk } from '../../meeting-history/types'declare global {interface Window {@@ -10,95 +10,109 @@ declare global {}export function useTranscriptionStream(- setChunks: (updater: (prev: TranscriptionChunk[]) => TranscriptionChunk[]) => void+ onNewChunk: (chunk: TranscriptionChunk) => void) {const streamingRef = useRef(false)+ const abortControllerRef = useRef<AbortController | null>(null)const { toast } = useToast()const stopTranscriptionScreenpipe = useCallback(() => {- if (window._eventSource) {- console.log('stopping screenpipe transcription')- window._eventSource.close()- window._eventSource = undefined- streamingRef.current = false+ console.log('stopping screenpipe transcription', {+ isStreaming: streamingRef.current,+ hasAbortController: !!abortControllerRef.current+ })++ if (abortControllerRef.current) {+ abortControllerRef.current.abort()+ abortControllerRef.current = null}++ // Force disconnect the pipe stream+ pipe.disconnect()+ streamingRef.current = false}, [])const startTranscriptionScreenpipe = useCallback(async () => {if (streamingRef.current) {- console.log('transcription already streaming');- return;+ console.log('transcription already streaming')+ return}-+try {- console.log('starting transcription stream...');- if (window._eventSource) {- console.log('closing existing event source');- window._eventSource.close();- }-- streamingRef.current = true;- const eventSource = new EventSource('http://localhost:3030/sse/transcriptions');- window._eventSource = eventSource;-- eventSource.onopen = () => {- console.log('sse connection opened');- };-- let currentChunk: TranscriptionChunk | null = null-- eventSource.onmessage = (event) => {- if (event.data === 'keep-alive-text') return-- const chunk = JSON.parse(event.data)- console.log('new transcription chunk:', chunk)-- // If same speaker, append text with typing effect- if (currentChunk && currentChunk.speaker === chunk.speaker) {- const words = chunk.transcription.split(' ')- let wordIndex = 0-- const typeWords = () => {- if (wordIndex < words.length) {- currentChunk!.text += (currentChunk!.text ? ' ' : '') + words[wordIndex]- setChunks(prev => [...prev.slice(0, -1), { ...currentChunk! }])- wordIndex++- setTimeout(typeWords, 20)+ console.log('starting transcription stream...')+ streamingRef.current = true+ abortControllerRef.current = new AbortController()+ const signal = abortControllerRef.current.signal++ // Create a separate async function to handle the stream+ const handleStream = async () => {+ const stream = pipe.streamTranscriptions()+ try {+ for await (const chunk of stream) {+ // Check if aborted before processing each chunk+ if (signal.aborted) {+ console.log('stream aborted, breaking loop')+ break}++ console.log('new transcription chunk:', {+ text: chunk.choices[0]?.text,+ speaker: chunk.metadata?.speaker,+ model: chunk.model,+ device: chunk.metadata?.device+ })+ const transcriptionData = chunk.choices[0]?.text+ if (!transcriptionData) continue++ const isInput = chunk.metadata?.device?.toLowerCase().includes('input') ?? false+ const speaker = chunk.metadata?.speaker?.startsWith('speaker_')+ ? chunk.metadata.speaker+ : `speaker_${chunk.metadata?.speaker || '0'}`++ const newChunk: TranscriptionChunk = {+ id: Date.now(),+ timestamp: chunk.metadata?.timestamp || new Date().toISOString(),+ text: transcriptionData,+ isInput,+ device: chunk.metadata?.device || 'unknown',+ speaker+ }++ onNewChunk(newChunk)}-- typeWords()- } else {- // New speaker or first chunk, create new entry- currentChunk = {- id: Date.now(),- timestamp: chunk.timestamp,- text: chunk.transcription,- isInput: chunk.is_input,- device: chunk.device,- speaker: chunk.speaker- }- setChunks(prev => [...prev, currentChunk!])+ } finally {+ // Ensure we clean up if the loop breaks+ console.log('stream loop ended')+ streamingRef.current = false+ pipe.disconnect() // Explicitly disconnect the stream}}- eventSource.onerror = (error) => {- console.error("sse error:", error);- eventSource.close();- streamingRef.current = false;+ // Start the stream handling+ handleStream().catch(error => {+ console.error('stream handler error:', error)+ streamingRef.current = falsetoast({title: "transcription error",description: "failed to stream audio. retrying...",variant: "destructive"- });- console.log('scheduling retry...');- setTimeout(startTranscriptionScreenpipe, 1000);- }+ })+ console.log('scheduling retry...')+ setTimeout(startTranscriptionScreenpipe, 1000)+ })+} catch (error) {- console.error("failed to start transcription:", error);- streamingRef.current = false;+ console.error("failed to start transcription:", error)+ streamingRef.current = false+ toast({+ title: "transcription error",+ description: "failed to stream audio. retrying...",+ variant: "destructive"+ })+ console.log('scheduling retry...')+ setTimeout(startTranscriptionScreenpipe, 1000)}- }, [toast, setChunks])+ }, [onNewChunk, toast])return {startTranscriptionScreenpipe,diff --git a/pipes/meeting/src/components/live-transcription/hooks/storage-for-live-meeting.tsx b/pipes/meeting/src/components/live-transcription/hooks/storage-for-live-meeting.tsxindex 9d8a4964f..64159cbbf 100644--- a/pipes/meeting/src/components/live-transcription/hooks/storage-for-live-meeting.tsx+++ b/pipes/meeting/src/components/live-transcription/hooks/storage-for-live-meeting.tsx@@ -1,20 +1,22 @@-import { createContext, useContext, useState, useEffect, ReactNode, useMemo } from 'react'+import { createContext, useContext, useState, useEffect, ReactNode, useMemo, useCallback, useRef } from 'react'import { TranscriptionChunk, Note, MeetingSegment } from "../../meeting-history/types"import { MeetingAnalysis } from "./ai-create-all-notes"import localforage from "localforage"+import { useSettings } from "@/lib/hooks/use-settings"+import { createHandleNewChunk } from './handle-new-chunk'+import { ImprovedChunk } from './handle-new-chunk'-// Storage setup-export const liveStore = localforage.createInstance({+// Single store for all meetings+export const meetingStore = localforage.createInstance({name: "live-meetings",- storeName: "transcriptions"+ storeName: "meetings" // All meetings live here})-// Export the key-export const LIVE_MEETING_KEY = 'current-live-meeting'-export interface LiveMeetingData {- chunks: TranscriptionChunk[]- editedChunks: Record<number, string>+ id: string // Add explicit ID field+ chunks: TranscriptionChunk[] // Keep raw chunks+ mergedChunks: TranscriptionChunk[] // Add merged chunks+ editedMergedChunks: Record<number, ImprovedChunk> // Change type to include diffsspeakerMappings: Record<string, string>lastProcessedIndex: numberstartTime: string@@ -24,6 +26,34 @@ export interface LiveMeetingData {analysis: MeetingAnalysis | nulldeviceNames: Set<string>selectedDevices: Set<string>+ // New fields+ agenda?: string+ participants_invited?: string[]+ recurrence?: string+ participants?: string[] | null+ guestCount?: number+ confirmedCount?: number+ organizer?: string+ aiPrep?: {+ previousContext: {+ lastInteraction: string+ personContext: Record<string, {+ personality: string+ communicationStyle: string+ pastDecisions: string[]+ strengths: string[]+ challenges: string[]+ }>+ agreedNextSteps: string[]+ }+ suggestedPrep: {+ reviewPoints: string[]+ discussionTopics: string[]+ meetingTips: string[]+ }+ }+ isArchived?: boolean // Add optional flag+ isAiNotesEnabled: boolean // Add this field}// Context type@@ -38,7 +68,13 @@ interface MeetingContextType {setAnalysis: (analysis: MeetingAnalysis | null) => Promise<void>isLoading: booleandata: LiveMeetingData | null- updateStore: (newData: LiveMeetingData) => Promise<void>+ updateStore: (newData: LiveMeetingData) => Promise<boolean>+ reloadData: () => Promise<void>+ onNewChunk: (chunk: TranscriptionChunk) => Promise<void>+ improvingChunks: Record<number, boolean>+ setImprovingChunks: (chunks: Record<number, boolean>) => void+ recentlyImproved: Record<number, boolean>+ setRecentlyImproved: (chunks: Record<number, boolean>) => void}// Context creation@@ -47,108 +83,87 @@ const MeetingContext = createContext<MeetingContextType | undefined>(undefined)export function MeetingProvider({ children }: { children: ReactNode }) {const [data, setData] = useState<LiveMeetingData | null>(null)const [isLoading, setIsLoading] = useState(true)+ const latestChunksRef = useRef<TranscriptionChunk[]>([])+ const { settings } = useSettings()+ const [improvingChunks, setImprovingChunks] = useState<Record<number, boolean>>({})+ const [recentlyImproved, setRecentlyImproved] = useState<Record<number, boolean>>({})- useEffect(() => {- const loadData = async () => {- try {- console.log('MeetingProvider: loading data')- const stored = await liveStore.getItem<LiveMeetingData>(LIVE_MEETING_KEY)- console.log('MeetingProvider: loaded data:', {- exists: !!stored,- chunks: stored?.chunks?.length,- title: stored?.title,- notes: stored?.notes?.length,- notesData: stored?.notes?.map(n => ({- id: n.id,- text: n.text?.slice(0, 50),- timestamp: n.timestamp- }))- })-- if (!stored) {- console.log('MeetingProvider: no stored data, initializing new')+ // Single source of truth for loading data+ const loadData = async () => {+ try {+ let activeMeeting: LiveMeetingData | null = null++ // Get all meetings and find the first non-archived one+ const allMeetings = await meetingStore.keys()+ for (const key of allMeetings) {+ const meeting = await meetingStore.getItem<LiveMeetingData>(key)+ if (meeting && !meeting.isArchived) {+ activeMeeting = meeting+ break}-- setData(stored || {+ }++ console.log('MeetingProvider: loaded data:', {+ exists: !!activeMeeting,+ id: activeMeeting?.id,+ chunks: activeMeeting?.chunks?.length,+ title: activeMeeting?.title,+ })++ if (!activeMeeting) {+ const startTime = new Date().toISOString()+ const newData: LiveMeetingData = {+ id: `live-meeting-${startTime}`,chunks: [],- editedChunks: {},+ mergedChunks: [],+ editedMergedChunks: {},speakerMappings: {},lastProcessedIndex: -1,- startTime: new Date().toISOString(),+ startTime,title: null,notes: [],analysis: null,- deviceNames: new Set(),- selectedDevices: new Set()- })- } catch (error) {- console.error('MeetingProvider: failed to load meeting data:', error)- } finally {- setIsLoading(false)+ deviceNames: new Set<string>(),+ selectedDevices: new Set<string>(),+ isAiNotesEnabled: true, // Default to enabled+ isArchived: false+ }+ await meetingStore.setItem(newData.id, newData)+ setData(newData)+ } else {+ setData(activeMeeting)}++ return activeMeeting+ } catch (error) {+ console.error('MeetingProvider: failed to load:', error)+ return null+ } finally {+ setIsLoading(false)}+ }++ // Expose reload function through context+ const reloadData = async () => {+ setIsLoading(true)+ await loadData()+ }++ useEffect(() => {+ console.log('meeting provider mounted')loadData()+ return () => console.log('meeting provider unmounted')}, [])const updateStore = async (newData: LiveMeetingData) => {- // Debug: log current and new notes details- console.log('updateStore: checking changes', {- currentNotes: data?.notes?.length,- newNotes: newData.notes?.length,- currentNotesData: data?.notes?.map(n => ({- text: n.text?.slice(0, 50),- timestamp: n.timestamp,- id: n.id- })),- newNotesData: newData.notes?.map(n => ({- text: n.text?.slice(0, 50),- timestamp: n.timestamp,- id: n.id- })),- stack: new Error().stack?.split('\n').slice(1, 3)- });-- // Debug: log title differences for clarity- console.log('updateStore: checking title change', {- currentTitle: data?.title,- newTitle: newData.title,- titleChanged: data?.title !== newData.title- });-- // If no previous data, always update- if (!data) {- console.log('updateStore: no previous data, saving');- await liveStore.setItem(LIVE_MEETING_KEY, newData);- setData(newData);- return;- }-- // Determine if notes have changed- const notesChanged =- data.notes.length !== newData.notes.length ||- JSON.stringify(data.notes) !== JSON.stringify(newData.notes);-- // Determine if title has changed- const titleChanged = data.title !== newData.title;-- // If neither notes nor title changed, skip saving- if (!notesChanged && !titleChanged) {- console.log('updateStore: no changes detected', { notesChanged, titleChanged });- return;- }-- console.log('updateStore: saving changes', {- currentNotes: data.notes.length,- newNotes: newData.notes.length,- notesChanged,- titleChanged- });-- try {- await liveStore.setItem(LIVE_MEETING_KEY, newData);- setData(newData);+ try {+ await meetingStore.setItem(newData.id, newData)+ setData(newData)+ latestChunksRef.current = newData.chunks+ return true} catch (error) {- console.error('updateStore: failed:', error);+ console.error('updateStore: failed:', error)+ return false}};@@ -168,31 +183,23 @@ export function MeetingProvider({ children }: { children: ReactNode }) {const setNotes = async (notes: Note[]) => {if (!data) return- console.log('setting notes:', {- count: notes.length,- notes: notes.map(n => ({- text: n.text?.slice(0, 50),- timestamp: n.timestamp,- id: n.id- })),- stack: new Error().stack?.split('\n').slice(1,3)+ // console.log('setting notes:', {+ // count: notes.length,+ // notes: notes.map(n => ({+ // text: n.text?.slice(0, 50),+ // timestamp: n.timestamp,+ // id: n.id+ // })),+ // currentTitle: data.title,+ // stack: new Error().stack?.split('\n').slice(1,3)+ // })+ await updateStore({+ ...data,+ notes,+ title: data.title,+ startTime: data.startTime,+ id: data.id})- await updateStore({ ...data, notes })- }-- const setSegments = async (segments: MeetingSegment[]) => {- if (!data) return- console.log('setting segments:', segments.length)- const chunks = segments.map((seg, index) => ({- id: Date.now() + index,- timestamp: seg.timestamp,- text: seg.transcription,- deviceName: seg.deviceName,- speaker: seg.speaker,- isInput: seg.deviceName?.toLowerCase().includes('input') || false,- device: seg.deviceName || 'unknown',- }))- await updateStore({ ...data, chunks })}const setAnalysis = async (analysis: MeetingAnalysis | null) => {@@ -201,6 +208,24 @@ export function MeetingProvider({ children }: { children: ReactNode }) {await updateStore({ ...data, analysis })}+ const handleNewChunk = useCallback(+ createHandleNewChunk({+ setData,+ setImprovingChunks,+ setRecentlyImproved,+ updateStore,+ settings+ }),+ [settings]+ )++ // Initialize ref when data loads+ useEffect(() => {+ if (data) {+ latestChunksRef.current = data.chunks+ }+ }, [data])+const value = useMemo(() => ({title: data?.title || '',setTitle,@@ -208,17 +233,23 @@ export function MeetingProvider({ children }: { children: ReactNode }) {setNotes,segments: (data?.chunks || []).map(chunk => ({timestamp: chunk.timestamp,- transcription: data?.editedChunks[chunk.id] || chunk.text,+ transcription: data?.editedMergedChunks[chunk.id]?.text || chunk.text,deviceName: chunk.deviceName || '',speaker: data?.speakerMappings[chunk.speaker || 'speaker_0'] || chunk.speaker || 'speaker_0'})),- setSegments,+ setSegments: async () => {},analysis: data?.analysis || null,setAnalysis,isLoading,data,- updateStore- }), [data, isLoading])+ updateStore,+ reloadData,+ onNewChunk: handleNewChunk,+ improvingChunks,+ setImprovingChunks,+ recentlyImproved,+ setRecentlyImproved,+ }), [data, isLoading, handleNewChunk, improvingChunks, recentlyImproved])return (<MeetingContext.Provider value={value}>@@ -235,95 +266,125 @@ export function useMeetingContext() {return context}-// Storage operations-export const getCurrentKey = () => LIVE_MEETING_KEY--export const clearCurrentKey = () => {- liveStore.removeItem(LIVE_MEETING_KEY)- console.log('cleared live meeting data')-}--export async function storeLiveChunks(chunks: TranscriptionChunk[]): Promise<void> {+// Rename function to better reflect its purpose+export async function archiveLiveMeeting(): Promise<LiveMeetingData | null> {try {- const existing = await liveStore.getItem<LiveMeetingData>(LIVE_MEETING_KEY)- const data: LiveMeetingData = {- chunks,- editedChunks: existing?.editedChunks ?? {},- speakerMappings: existing?.speakerMappings ?? {},- lastProcessedIndex: existing?.lastProcessedIndex ?? -1,- startTime: existing?.startTime ?? new Date().toISOString(),- title: existing?.title ?? null,- notes: existing?.notes ?? [],- analysis: existing?.analysis ?? null,- deviceNames: existing?.deviceNames ?? new Set(),- selectedDevices: existing?.selectedDevices ?? new Set()+ // Find active meeting+ const allMeetings = await meetingStore.keys()+ for (const key of allMeetings) {+ const meeting = await meetingStore.getItem<LiveMeetingData>(key)+ if (meeting && !meeting.isArchived) {+ console.log('archiving active meeting:', {+ id: meeting.id,+ title: meeting.title+ })+ const archivedMeeting = {+ ...meeting,+ isArchived: true,+ endTime: new Date().toISOString()+ }+ await meetingStore.setItem(key, archivedMeeting)+ return archivedMeeting+ }}- console.log('storing live meeting data')- await liveStore.setItem(LIVE_MEETING_KEY, data)+ return null} catch (error) {- console.error('failed to store live meeting:', error)+ console.error('failed to archive meeting data:', error)+ throw error+ }+}+++// Add function to delete an archived meeting by its start time+export async function deleteArchivedMeeting(startTime: string): Promise<void> {+ try {+ let keyToDelete: string | null = null++ // Find the meeting with matching start time+ await meetingStore.iterate<LiveMeetingData, void>((value: LiveMeetingData, key: string) => {+ if (value.startTime === startTime) {+ keyToDelete = key+ return+ }+ })++ if (keyToDelete) {+ console.log('deleting archived meeting:', {+ key: keyToDelete,+ startTime+ })+ await meetingStore.removeItem(keyToDelete)+ } else {+ console.log('meeting not found for deletion:', startTime)}+ } catch (error) {+ console.error('failed to delete archived meeting:', error)+ throw error+ }}-export async function getLiveMeetingData(): Promise<LiveMeetingData | null> {+// Add function to update an archived meeting+export async function updateArchivedMeeting(id: string, update: Partial<LiveMeetingData>) {try {- console.log('getLiveMeetingData: loading')- const data = await liveStore.getItem<LiveMeetingData>(LIVE_MEETING_KEY)+ const meeting = await meetingStore.getItem<LiveMeetingData>(id)+ if (!meeting) {+ console.error('meeting not found for update:', { id })+ return null+ }- // Ensure dates are properly restored- if (data?.notes) {- data.notes = data.notes.map(note => ({- ...note,- timestamp: new Date(note.timestamp),- editedAt: note.editedAt ? new Date(note.editedAt) : undefined- }))+ // Create updated meeting data - preserve existing fields+ const updated = {+ ...meeting, // First spread existing meeting+ ...update, // Then apply updates+ // Explicitly preserve critical fields unless intentionally updated+ title: update.title ?? meeting.title,+ startTime: update.startTime ?? meeting.startTime,+ id: meeting.id, // Never allow id to be changed+ isArchived: true // Always keep archived status}- console.log('getLiveMeetingData: result:', {- exists: !!data,- chunks: data?.chunks?.length,- title: data?.title,- notes: data?.notes?.length,- firstNote: data?.notes?.[0]?.text?.slice(0, 50)+ console.log('updating archived meeting:', {+ id,+ oldTitle: meeting.title,+ newTitle: updated.title,+ preservedFields: {+ notes: updated.notes?.length,+ chunks: updated.chunks?.length,+ startTime: updated.startTime+ },+ fullUpdate: update})- return data++ await meetingStore.setItem(id, updated)+ return updated} catch (error) {- console.error('getLiveMeetingData: failed:', error)+ console.error('failed to update archived meeting:', error)return null}}-export async function clearLiveMeetingData(): Promise<void> {+export async function getAllMeetings(): Promise<LiveMeetingData[]> {try {- const currentData = await liveStore.getItem<LiveMeetingData>(LIVE_MEETING_KEY)- console.log('clearing live meeting data:', {- had_title: !!currentData?.title,- notes_count: currentData?.notes.length,- chunks_count: currentData?.chunks.length,- analysis: !!currentData?.analysis,- start_time: currentData?.startTime,- })+ const meetings: LiveMeetingData[] = []- // Create empty state- const emptyState: LiveMeetingData = {- chunks: [],- editedChunks: {},- speakerMappings: {},- lastProcessedIndex: -1,- startTime: new Date().toISOString(),- title: null,- notes: [],- analysis: null,- deviceNames: new Set(),- selectedDevices: new Set()- }-- // Set empty state first, then remove- await liveStore.setItem(LIVE_MEETING_KEY, emptyState)- await liveStore.removeItem(LIVE_MEETING_KEY)- console.log('live meeting data cleared successfully')+ await meetingStore.iterate<LiveMeetingData, void>((value: LiveMeetingData) => {+ meetings.push(value)+ })++ // Sort by start time, newest first+ meetings.sort((a, b) =>+ new Date(b.startTime).getTime() - new Date(a.startTime).getTime()+ )++ console.log('loaded all meetings:', {+ count: meetings.length,+ live: meetings.find(m => !m.isArchived)?.title,+ archived: meetings.filter(m => m.isArchived).length+ })++ return meetings} catch (error) {- console.error('failed to clear live meeting data:', error)- throw error+ console.error('failed to get meetings:', error)+ return []}}\ No newline at end of filediff --git a/pipes/meeting/src/components/live-transcription/hooks/storage-vocabulary.ts b/pipes/meeting/src/components/live-transcription/hooks/storage-vocabulary.tsindex b63cf2837..03b2e7dcb 100644--- a/pipes/meeting/src/components/live-transcription/hooks/storage-vocabulary.ts+++ b/pipes/meeting/src/components/live-transcription/hooks/storage-vocabulary.ts@@ -14,7 +14,7 @@ const vocabularyStore = localforage.createInstance({storeName: "corrections"})-const CURRENT_STORAGE_VERSION = 1+// const CURRENT_STORAGE_VERSION = 1export async function addVocabularyEntry(original: string, corrected: string, meetingId?: string): Promise<void> {try {@@ -43,13 +43,13 @@ export async function getVocabularyEntries(): Promise<VocabularyEntry[]> {const entries = await vocabularyStore.getItem<VocabularyEntry[]>("vocabulary") || []// Log storage stats- const entriesCount = entries.length- const storageSize = new TextEncoder().encode(JSON.stringify(entries)).length / 1024-- console.log("vocabulary storage stats:", {- entriesCount,- storageSize: `${storageSize.toFixed(2)}kb`,- })+ // const entriesCount = entries.length+ // const storageSize = new TextEncoder().encode(JSON.stringify(entries)).length / 1024+//+ // console.log("vocabulary storage stats:", {+ // entriesCount,+ // storageSize: `${storageSize.toFixed(2)}kb`,+ // })return entries} catch (error) {diff --git a/pipes/meeting/src/components/live-transcription/hooks/text-editor-auto-scroll.ts b/pipes/meeting/src/components/live-transcription/hooks/text-editor-auto-scroll.tsnew file mode 100644index 000000000..43aaaefd5--- /dev/null+++ b/pipes/meeting/src/components/live-transcription/hooks/text-editor-auto-scroll.ts@@ -0,0 +1,54 @@+import { useEffect, useRef, useState } from 'react'++export function useTextEditorAutoScroll() {+ const textareaRef = useRef<HTMLTextAreaElement>(null)+ const [shouldAutoScroll, setShouldAutoScroll] = useState(true)+ const lastStateRef = useRef(true)+ const isUserScrolling = useRef(false)+ const scrollTimeout = useRef<NodeJS.Timeout>()++ const scrollToBottom = () => {+ const element = textareaRef.current+ if (!element || isUserScrolling.current) return++ // Use requestAnimationFrame to ensure content is rendered+ requestAnimationFrame(() => {+ element.scrollTop = element.scrollHeight+ })+ }++ const onScroll = () => {+ const element = textareaRef.current+ if (!element) return++ // Clear existing timeout+ if (scrollTimeout.current) {+ clearTimeout(scrollTimeout.current)+ }++ isUserScrolling.current = true++ // Check if we're near bottom (within 50px)+ const isAtBottom =+ Math.abs(element.scrollHeight - element.clientHeight - element.scrollTop) < 50++ if (isAtBottom !== lastStateRef.current) {+ console.log('text-editor auto-scroll:', isAtBottom ? 'enabled' : 'disabled')+ lastStateRef.current = isAtBottom+ }++ setShouldAutoScroll(isAtBottom)++ // Reset user scrolling flag after 100ms of no scroll events+ scrollTimeout.current = setTimeout(() => {+ isUserScrolling.current = false+ }, 100)+ }++ return {+ textareaRef,+ onScroll,+ isScrolledToBottom: shouldAutoScroll,+ scrollToBottom+ }+}\ No newline at end of filediff --git a/pipes/meeting/src/components/live-transcription/new-meeting-wrapper.tsx b/pipes/meeting/src/components/live-transcription/new-meeting-wrapper.tsxindex 7b08e634e..712ab6651 100644--- a/pipes/meeting/src/components/live-transcription/new-meeting-wrapper.tsx+++ b/pipes/meeting/src/components/live-transcription/new-meeting-wrapper.tsx@@ -8,20 +8,23 @@ import { NotesEditor } from '@/components/live-transcription/notes-editor'import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"import Split from 'react-split'import { TranscriptionView } from '@/components/live-transcription/transcription-view'-import { ArrowLeft } from "lucide-react"+import { Square, Play } from "lucide-react"import { useRouter } from "next/navigation"-import { MeetingProvider } from '@/components/live-transcription/hooks/storage-for-live-meeting'+import { MeetingProvider, useMeetingContext, archiveLiveMeeting, LiveMeetingData } from '@/components/live-transcription/hooks/storage-for-live-meeting'import { useSettings } from "@/lib/hooks/use-settings"-import { clearLiveMeetingData } from './hooks/storage-for-live-meeting'+import { Button } from '@/components/ui/button'+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"+import { toast } from "@/hooks/use-toast"+import { handleStartNewMeeting } from '@/components/meeting-history/meeting-utils'+import { cn } from "@/lib/utils"-interface Props {- onBack: () => void-}-export function LiveTranscription({ onBack }: Props) {+export function LiveTranscription() {const {chunks,isLoadingRecent: isLoading,+ isRecording,+ toggleRecording} = useTranscriptionService()const { scrollRef, onScroll, isScrolledToBottom } = useAutoScroll(chunks)@@ -30,11 +33,11 @@ export function LiveTranscription({ onBack }: Props) {const [sizes, setSizes] = useState([50, 50])const router = useRouter()const { settings } = useSettings()+ const { data, updateStore, reloadData } = useMeetingContext()const updateHeight = () => {const vh = window.innerHeightconst headerOffset = 32- console.log('window height:', vh, 'header offset:', headerOffset)setWindowHeight(vh - headerOffset)}@@ -45,6 +48,11 @@ export function LiveTranscription({ onBack }: Props) {return () => window.removeEventListener('resize', updateHeight)}, []) // Empty deps array since updateHeight is stable+ useEffect(() => {+ console.log('live transcription component mounted')+ return () => console.log('live transcription component unmounted')+ }, [])+const handleTimeClick = (timestamp: Date) => {console.log('clicking time:', timestamp)@@ -71,47 +79,76 @@ export function LiveTranscription({ onBack }: Props) {if (newSizes[1] < 25) setSizes([100, 0])}- const handleBack = () => {- console.log('navigating back to meeting history')- router.push('/meetings')+ const handleNewMeeting = async () => {+ await handleStartNewMeeting(data)}return (<div className="h-full flex flex-col"><div- className="w-full"+ className="w-full relative"style={{ height: windowHeight ? `${windowHeight}px` : '100vh' }}>+ {/* Update recording toggle button with tooltip */}+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ onClick={() => toggleRecording()}+ className="absolute right-7 z-20 hover:bg-gray-100/80 transition-colors"+ title={isRecording ? "stop recording" : "start recording"}+ >+ {isRecording ? (+ <Square className="h-4 w-4 text-red-500 fill-red-500" />+ ) : (+ <Play className="h-4 w-4 text-green-500 fill-green-500" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent side="bottom" className="text-xs">+ {isRecording ? (+ <span>stop recording transcription</span>+ ) : (+ <span>start recording transcription</span>+ )}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>++ {/* Mobile-first approach: vertical on mobile, horizontal on desktop */}<Split- className="flex gap-0 h-full [&_.gutter]:bg-gray-100 [&_.gutter]:bg-dotted [&_.gutter]:w-[3px] [&_.gutter]:mx-1 [&_.gutter]:cursor-col-resize"+ className={cn(+ "flex h-full",+ // Base mobile styles+ "flex-col [&_.gutter]:h-[3px] [&_.gutter]:my-1 [&_.gutter]:cursor-row-resize",+ // Desktop styles (md and up)+ "md:flex-row md:[&_.gutter]:w-[3px] md:[&_.gutter]:mx-1 md:[&_.gutter]:cursor-col-resize",+ "[&_.gutter]:bg-gray-100 [&_.gutter]:bg-dotted"+ )}sizes={sizes}minSize={0}snapOffset={100}onDragEnd={onDragEnd}onDrag={onDrag}+ direction={typeof window !== 'undefined' && window.innerWidth >= 768 ? 'horizontal' : 'vertical'}>{/* Transcription Panel */}- <div className="flex flex-col relative">+ <div className="h-full overflow-hidden"><TranscriptionView- chunks={chunks}settings={settings}isLoading={isLoading}- isAutoScrollEnabled={isScrolledToBottom}- scrollRef={scrollRef}- onScroll={onScroll}- isScrolledToBottom={isScrolledToBottom}/></div>{/* Notes Panel */}- <div>+ <div className="h-full overflow-hidden"><NotesEditoronTimeClick={handleTimeClick}- onBack={handleBack}- onNewMeeting={() => {- clearLiveMeetingData()- router.refresh()- }}+ onNewMeeting={handleNewMeeting}+ isRecording={isRecording}+ onToggleRecording={toggleRecording}/></div></Split>diff --git a/pipes/meeting/src/components/live-transcription/notes-editor.tsx b/pipes/meeting/src/components/live-transcription/notes-editor.tsxindex cf527217b..2897ed5cd 100644--- a/pipes/meeting/src/components/live-transcription/notes-editor.tsx+++ b/pipes/meeting/src/components/live-transcription/notes-editor.tsx@@ -1,25 +1,32 @@'use client'import { useState, useEffect, useRef, useMemo, memo } from 'react'-import { ArrowDown, ArrowLeft, List, FileText, Wand2, Sparkles, PlusCircle, ChevronDown } from 'lucide-react'+import { ArrowDown, ArrowLeft, List, FileText, Wand2, Sparkles, PlusCircle, ChevronDown, Mic, MicOff, CheckCircle2 } from 'lucide-react'import { useAutoScroll } from './hooks/auto-scroll'import { TextEditor } from './text-editor-within-notes-editor'import { Note } from '../meeting-history/types'-import { useMeetingContext, clearLiveMeetingData } from './hooks/storage-for-live-meeting'-import { generateMeetingName } from '../meeting-history/ai-meeting-title'+import { useMeetingContext, archiveLiveMeeting } from './hooks/storage-for-live-meeting'+import { generateMeetingName } from './hooks/ai-meeting-title'import { useSettings } from '@/lib/hooks/use-settings'import { useToast } from '@/hooks/use-toast'import { generateMeetingNotes } from './hooks/ai-create-all-notes'import { improveNote } from './hooks/ai-create-note'import { useRouter } from "next/navigation"+import { Switch } from "@/components/ui/switch"interface Props {onTimeClick: (timestamp: Date) => void- onBack: () => voidonNewMeeting: () => void+ isRecording: boolean+ onToggleRecording: () => void}-export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNewMeeting }: Props) {+export const NotesEditor = memo(function NotesEditor({+ onTimeClick,+ onNewMeeting,+ isRecording,+ onToggleRecording+}: Props) {const {title,setTitle,@@ -27,7 +34,10 @@ export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNesetNotes,segments,analysis,- setAnalysis+ setAnalysis,+ data,+ isLoading,+ updateStore,} = useMeetingContext()const [currentMessage, setCurrentMessage] = useState("")const [editingId, setEditingId] = useState<string | null>(null)@@ -112,16 +122,6 @@ export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNe})))- useEffect(() => {- console.log('NotesEditor deps changed:', {- notesLength: notes.length,- segmentsLength: segments.length,- hasAnalysis: !!analysis,- title,- stack: new Error().stack?.split('\n')[2] // Just the immediate caller- })- }, [notes.length, segments.length, analysis, title])-useEffect(() => {function handleClickOutside(event: MouseEvent) {if (editingId && editRef.current && !editRef.current.contains(event.target as Node)) {@@ -215,32 +215,26 @@ export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNe}const handleGenerateTitle = async () => {- if (isGeneratingTitle) return+ if (isGeneratingTitle || isLoading) returnsetIsGeneratingTitle(true)try {- console.log("generating title for meeting")- const meeting = {- id: crypto.randomUUID(),- notes: notes.map(note => ({- id: note.id,- text: note.text,- timestamp: note.timestamp.toISOString(),- editedAt: note.editedAt?.toISOString()- })),- meetingStart: notes[0]?.timestamp.toISOString() || new Date().toISOString(),- meetingEnd: notes[notes.length - 1]?.timestamp.toISOString() || new Date().toISOString(),- humanName: title,- aiName: null,- agenda: null,- aiSummary: null,- participants: null,- selectedDevices: new Set<string>(),- deviceNames: new Set<string>(),- segments+ console.log("generating title for meeting", {+ hasData: !!data,+ isLoading,+ dataState: {+ merged_chunks: data?.mergedChunks.length,+ edited_chunks: Object.keys(data?.editedMergedChunks || {}).length,+ notes: notes.length,+ has_analysis: !!analysis+ }+ })++ if (!data) {+ throw new Error("meeting data not initialized")}- const aiName = await generateMeetingName(meeting, settings)+ const aiName = await generateMeetingName(data, settings)await setTitle(aiName)toast({@@ -380,40 +374,6 @@ export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNeawait setNotes(updatedNotes)}-- const handleNewMeeting = async () => {- console.log('starting new meeting from notes editor')- try {- // Save current state for logging- const currentTitle = title- const notesCount = notes.length-- console.log('current meeting state:', {- title: currentTitle,- notes_count: notesCount,- has_analysis: !!analysis- })-- // Clear storage first- await clearLiveMeetingData()-- // Wait a bit to ensure storage is cleared- await new Promise(resolve => setTimeout(resolve, 100))-- console.log('storage cleared, forcing navigation')- // Force a full navigation instead of client-side- window.location.href = '/meetings/live'-- } catch (error) {- console.error('failed to start new meeting:', error)- toast({- title: "error",- description: "failed to start new meeting. please try again",- variant: "destructive",- })- }- }-// Log every render// useEffect(() => {// console.log('NotesEditor render:', {@@ -428,6 +388,11 @@ export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNesetLocalTitle(title)}, [title])+ const handleNewMeetingClick = () => {+ setShowNav(false) // Close the sidebar+ onNewMeeting() // Call the passed handler+ }+return (<div className="h-full flex flex-col bg-card relative"><div@@ -440,15 +405,42 @@ export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNe${showNav ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-1 pointer-events-none'}`}><div className="flex flex-col gap-1 bg-gray-100/80 backdrop-blur p-1 rounded-lg shadow-sm">- <button- onClick={onBack}+ <button+ onClick={async () => {+ console.log('finishing meeting:', {+ hasData: !!data,+ isArchived: data?.isArchived+ })+ try {+ // Only try to archive if meeting exists and isn't already archived+ if (data && !data.isArchived) {+ const archived = await archiveLiveMeeting()+ console.log('archive result:', {+ success: archived,+ meetingId: data.id+ })+ if (!archived) {+ throw new Error("failed to archive meeting")+ }+ }+ router.push('/meetings')+ } catch (error) {+ console.error('failed to finish meeting:', error)+ toast({+ title: "error",+ description: "failed to finish meeting. please try again",+ variant: "destructive",+ })+ }+ }}className="flex items-center gap-2 px-3 py-1.5 text-xs hover:bg-gray-200/80 rounded transition-colors w-full text-left"><ArrowLeft className="h-4 w-4" />- <span>back to meetings menu</span>+ <span>back to meetings history</span></button>+<button- onClick={handleNewMeeting}+ onClick={handleNewMeetingClick}className="flex items-center gap-2 px-3 py-1.5 text-xs hover:bg-gray-200/80 rounded transition-colors w-full text-left"><PlusCircle className="h-4 w-4" />@@ -471,7 +463,23 @@ export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNe<span>append AI summary</span></button>-+ <div className="mt-1 pt-1 border-t border-gray-200">+ <div className="px-3 py-1 text-xs text-gray-500">settings</div>+ <div className="flex items-center justify-between px-3 py-1.5">+ <span className="text-xs">auto ai notes</span>+ <Switch+ checked={data?.isAiNotesEnabled ?? true}+ onCheckedChange={async (checked) => {+ if (!data) return+ await updateStore({+ ...data,+ isAiNotesEnabled: checked+ })+ }}+ />+ </div>+ </div>+<div className="mt-1 pt-1 border-t border-gray-200"><div className="px-3 py-1 text-xs text-gray-500">view type</div><button@@ -493,148 +501,152 @@ export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNe</div></div></div>- <ChevronDown className={`h-5 w-5 text-gray-400 transition-transform duration-200 hover:text-gray-600- ${showNav ? 'rotate-180' : ''}`} />+ <div className="p-1 rounded-md bg-gray-100/80 backdrop-blur hover:bg-gray-200/80 transition-colors">+ <ChevronDown className={`h-5 w-5 text-gray-400 transition-transform duration-200 hover:text-gray-600+ ${showNav ? 'rotate-180' : ''}`} />+ </div></div>- <div className="flex-1">- {TitleInput}- {showInvalidTime && (- <div className="absolute top-2 right-2 bg-red-100 text-red-600 px-2 py-1 rounded text-xs">- invalid time format- </div>- )}+ <div className="flex-1 min-h-0 flex flex-col">+ <div className="flex-none">+ {TitleInput}+ {showInvalidTime && (+ <div className="absolute top-2 right-2 bg-red-100 text-red-600 px-2 py-1 rounded text-xs">+ invalid time format+ </div>+ )}+ </div>- {viewMode === 'timeline' ? (- <div- ref={scrollRef}- onScroll={onScroll}- className="flex-1 overflow-y-auto p-3 space-y-3"- >- {sortedNotes.map(note => (- <div- key={note.id}- onClick={() => !editingId && onTimeClick(note.timestamp)}- className="text-sm mb-2 hover:bg-gray-100 active:bg-gray-200 transition-colors select-text cursor-pointer group"- >- <div className="flex items-center justify-between">- <div className="flex items-center gap-1">- {editingTime === note.id ? (- <div className="relative">- <input- ref={editTimeRef}- type="text"- id={`time-edit-${note.id}`}- name={`time-edit-${note.id}`}- value={editTimeText}- onChange={(e) => setEditTimeText(e.target.value)}- className="w-24 bg-white border rounded px-1 py-0.5 focus:outline-none text-xs text-gray-500"- autoFocus- onKeyDown={(e) => {- if (e.key === 'Enter') {- e.preventDefault()- updateTime(note.id)- }- if (e.key === 'Escape') {- setEditingTime(null)- }- }}- />- <div className="absolute -bottom-4 left-0 text-[10px] text-gray-500">- format: HH:MM:SS+ <div className="flex-1 min-h-0">+ {viewMode === 'timeline' ? (+ <div+ ref={scrollRef}+ onScroll={onScroll}+ className="h-full overflow-y-auto p-3 space-y-3"+ >+ {sortedNotes.map(note => (+ <div+ key={note.id}+ onClick={() => !editingId && onTimeClick(note.timestamp)}+ className="text-sm mb-2 hover:bg-gray-100 active:bg-gray-200 transition-colors select-text cursor-pointer group"+ >+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-1">+ {editingTime === note.id ? (+ <div className="relative">+ <input+ ref={editTimeRef}+ type="text"+ id={`time-edit-${note.id}`}+ name={`time-edit-${note.id}`}+ value={editTimeText}+ onChange={(e) => setEditTimeText(e.target.value)}+ className="w-24 bg-white border rounded px-1 py-0.5 focus:outline-none text-xs text-gray-500"+ autoFocus+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault()+ updateTime(note.id)+ }+ if (e.key === 'Escape') {+ setEditingTime(null)+ }+ }}+ />+ <div className="absolute -bottom-4 left-0 text-[10px] text-gray-500">+ format: HH:MM:SS+ </div></div>- </div>- ) : (- <span className="text-gray-500 text-xs hover:underline">- {note.timestamp instanceof Date ?- note.timestamp.toLocaleTimeString() :- new Date(note.timestamp).toLocaleTimeString()- }- </span>- )}- {!editingTime && (+ ) : (+ <span className="text-gray-500 text-xs hover:underline">+ {note.timestamp instanceof Date ?+ note.timestamp.toLocaleTimeString() :+ new Date(note.timestamp).toLocaleTimeString()+ }+ </span>+ )}+ {!editingTime && (+ <button+ onClick={(e) => startEditingTime(note, e)}+ className="opacity-0 group-hover:opacity-100 transition-opacity hover:bg-gray-200 rounded text-xs text-gray-500 px-1"+ >+ edit+ </button>+ )}+ </div>+ <div className="flex items-center gap-2">+ {note.editedAt && (+ <span className="text-gray-400 text-xs">+ edited {note.editedAt.toLocaleTimeString()}+ </span>+ )}<button- onClick={(e) => startEditingTime(note, e)}- className="opacity-0 group-hover:opacity-100 transition-opacity hover:bg-gray-200 rounded text-xs text-gray-500 px-1"+ onClick={async (e) => {+ e.stopPropagation()+ await handleImprove(note)+ }}+ className="opacity-0 group-hover:opacity-100 transition-opacity hover:bg-gray-200 rounded text-xs text-gray-500 px-2 py-0.5">- edit+ improve</button>- )}+ </div></div>- <div className="flex items-center gap-2">- {note.editedAt && (- <span className="text-gray-400 text-xs">- edited {note.editedAt.toLocaleTimeString()}- </span>- )}- <button- onClick={async (e) => {+ {editingId === note.id ? (+ <div+ ref={editRef}+ className="mt-1"+ >+ <input+ type="text"+ id={`note-edit-${note.id}`}+ name={`note-edit-${note.id}`}+ value={editText}+ onChange={(e) => setEditText(e.target.value)}+ className="w-full bg-gray-50 border rounded px-2 py-1 focus:outline-none font-mono text-sm"+ autoFocus+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault()+ updateNote()+ }+ if (e.key === 'Escape') {+ setEditingId(null)+ }+ }}+ />+ <div className="mt-1 text-xs text-gray-500">+ press Enter to save • Esc to discard+ </div>+ </div>+ ) : (+ <div+ className="mt-1 cursor-text hover:bg-gray-50 transition-colors rounded"+ onClick={(e) => {e.stopPropagation()- await handleImprove(note)+ startEditing(note, e)}}- className="opacity-0 group-hover:opacity-100 transition-opacity hover:bg-gray-200 rounded text-xs text-gray-500 px-2 py-0.5">- improve- </button>- </div>- </div>- {editingId === note.id ? (- <div- ref={editRef}- className="mt-1"- >- <input- type="text"- id={`note-edit-${note.id}`}- name={`note-edit-${note.id}`}- value={editText}- onChange={(e) => setEditText(e.target.value)}- className="w-full bg-gray-50 border rounded px-2 py-1 focus:outline-none font-mono text-sm"- autoFocus- onKeyDown={(e) => {- if (e.key === 'Enter') {- e.preventDefault()- updateNote()- }- if (e.key === 'Escape') {- setEditingId(null)- }- }}- />- <div className="mt-1 text-xs text-gray-500">- press Enter to save • Esc to discard+ {note.text}</div>- </div>- ) : (- <div- className="mt-1 cursor-text hover:bg-gray-50 transition-colors rounded"- onClick={(e) => {- e.stopPropagation()- startEditing(note, e)- }}- >- {note.text}- </div>- )}- </div>- ))}- </div>- ) : (- <TextEditor- notes={sortedNotes}- setNotes={(newNotes: Note[]) => setNotes(newNotes)}- scrollRef={scrollRef}- onScroll={onScroll}- isEditing={true}- analysis={analysis?.summary ? {- summary: analysis.summary,- facts: [],- events: [],- flow: [],- decisions: []- } : null}- />- )}+ )}+ </div>+ ))}+ </div>+ ) : (+ <TextEditor+ notes={sortedNotes}+ setNotes={(newNotes: Note[]) => setNotes(newNotes)}+ isEditing={true}+ analysis={analysis?.summary ? {+ summary: analysis.summary,+ facts: [],+ events: [],+ flow: [],+ decisions: []+ } : null}+ />+ )}+ </div>{!isScrolledToBottom && (<button@@ -644,24 +656,24 @@ export const NotesEditor = memo(function NotesEditor({ onTimeClick, onBack, onNe<ArrowDown className="h-4 w-4" /></button>)}-- {viewMode === 'timeline' && (- <form onSubmit={sendMessage} className="p-2 bg-gray-100">- <input- type="text"- id="new-note"- name="new-note"- value={currentMessage}- onChange={(e) => setCurrentMessage(e.target.value)}- className="flex-1 px-2 py-1.5 bg-transparent focus:outline-none text-sm"- placeholder="type a note..."- />- </form>- )}</div>++ {viewMode === 'timeline' && (+ <form onSubmit={sendMessage} className="flex-none p-2 bg-gray-100">+ <input+ type="text"+ id="new-note"+ name="new-note"+ value={currentMessage}+ onChange={(e) => setCurrentMessage(e.target.value)}+ className="flex-1 px-2 py-1.5 bg-transparent focus:outline-none text-sm"+ placeholder="type a note..."+ />+ </form>+ )}</div>)}, (prevProps, nextProps) => {// Only re-render if props actually changedreturn Object.is(prevProps, nextProps)-})\ No newline at end of file+})diff --git a/pipes/meeting/src/components/live-transcription/text-editor-within-notes-editor.tsx b/pipes/meeting/src/components/live-transcription/text-editor-within-notes-editor.tsxindex 44fdc7c6e..7487969db 100644--- a/pipes/meeting/src/components/live-transcription/text-editor-within-notes-editor.tsx+++ b/pipes/meeting/src/components/live-transcription/text-editor-within-notes-editor.tsx@@ -6,6 +6,7 @@ import { MeetingAnalysis } from './hooks/ai-create-all-notes'import { ChunkOverlay } from './floating-container-buttons'import { useSettings } from "@/lib/hooks/use-settings"import { useMeetingContext } from './hooks/storage-for-live-meeting'+import { useTextEditorAutoScroll } from './hooks/text-editor-auto-scroll'interface TextEditorProps {notes: Note[]@@ -35,22 +36,44 @@ export function TextEditor({const textDebounceRef = useRef<NodeJS.Timeout>()const initializedRef = useRef(false)- // Initialize only once when component mounts+ const {+ textareaRef,+ onScroll: autoScrollOnScroll,+ isScrolledToBottom,+ scrollToBottom+ } = useTextEditorAutoScroll()++ // Update localText whenever notes changeuseEffect(() => {- // Initialize localText only when notes are available and the editor has not been initialized yet- if (!initializedRef.current && notes.length > 0) {- console.log('text-editor: initializing localText from updated notes', { notesCount: notes.length });- const text = notes- .map(note => {- const text = note.text || '';- // Use bullet point if the note text starts with "- "- return text.startsWith('- ') ? '• ' + text.slice(2) : text;- })- .join('\n');- setLocalText(text);- initializedRef.current = true;+ // console.log('text-editor: notes updated', {+ // notesCount: notes.length,+ // lastNote: notes[notes.length - 1]?.text?.slice(0, 50),+ // isInitialized: initializedRef.current+ // })++ const text = notes+ .map(note => {+ const text = note.text || ''+ // Use bullet point if the note text starts with "- "+ return text.startsWith('- ') ? '• ' + text.slice(2) : text+ })+ .join('\n')++ // Always update localText when notes change+ setLocalText(text)++ // Mark as initialized if not already+ if (!initializedRef.current) {+ initializedRef.current = true}- }, [notes]); // dependency updated to react on changes to `notes`+ }, [notes]) // React to notes changes++ // Auto-scroll when content changes+ useEffect(() => {+ if (isScrolledToBottom) {+ scrollToBottom()+ }+ }, [localText, isScrolledToBottom])const handleMouseMove = (e: React.MouseEvent, noteId: string) => {const rect = e.currentTarget.getBoundingClientRect()@@ -132,16 +155,19 @@ export function TextEditor({editedAt: undefined})+return (<divref={scrollRef}- onScroll={onScroll}className="flex flex-col h-full"><textarea+ ref={textareaRef}+ onScroll={autoScrollOnScroll}value={localText}onChange={(e) => {const newValue = e.target.value+ // console.log('textarea onChange:', { newValue: e.target.value });setLocalText(newValue)if (textDebounceRef.current) {diff --git a/pipes/meeting/src/components/live-transcription/transcription-view.tsx b/pipes/meeting/src/components/live-transcription/transcription-view.tsxindex 688a07f4c..0c8391cbc 100644--- a/pipes/meeting/src/components/live-transcription/transcription-view.tsx+++ b/pipes/meeting/src/components/live-transcription/transcription-view.tsx@@ -10,36 +10,43 @@ import { Button } from "@/components/ui/button"import { DialogFooter } from "@/components/ui/dialog"import { addVocabularyEntry } from './hooks/storage-vocabulary'import { generateMeetingNote } from './hooks/ai-create-note-based-on-chunk'-import { improveTranscription } from './hooks/ai-improve-chunk-transcription'import { useMeetingContext } from './hooks/storage-for-live-meeting'import type { Settings } from "@screenpipe/browser"import { cn } from "@/lib/utils"-import {- storeLiveChunks,- LiveMeetingData,-} from './hooks/storage-for-live-meeting'import { useRecentChunks } from './hooks/pull-meetings-from-screenpipe'+import { useAutoScroll } from './hooks/auto-scroll'++interface DiffChunk {+ value: string+ added?: boolean+ removed?: boolean+}interface TranscriptionViewProps {- chunks: TranscriptionChunk[]isLoading: boolean- scrollRef: React.RefObject<HTMLDivElement>- onScroll: () => void- isAutoScrollEnabled: boolean- isScrolledToBottom: booleansettings: Settings}-export function TranscriptionView({- chunks,- isLoading,- scrollRef,- onScroll,- isAutoScrollEnabled,- isScrolledToBottom,- settings-}: TranscriptionViewProps) {- const { title, notes, setNotes, data, updateStore } = useMeetingContext()+function DiffText({ diffs }: { diffs: DiffChunk[] | null }) {+ if (!diffs) return null++ return (+ <>+ {diffs.map((diff, i) => {+ if (diff.added) {+ return <span key={i} className="bg-green-100">{diff.value}</span>+ }+ if (diff.removed) {+ return <span key={i} className="bg-red-100 line-through">{diff.value}</span>+ }+ return <span key={i}>{diff.value}</span>+ })}+ </>+ )+}++export function TranscriptionView({ isLoading, settings }: TranscriptionViewProps) {+ const { title, notes, setNotes, data, updateStore, reloadData, improvingChunks, recentlyImproved } = useMeetingContext()const [viewMode, setViewMode] = useState<'overlay' | 'sidebar' | 'timestamp'>('overlay')const [useOverlay, setUseOverlay] = useState(false)const [mergeModalOpen, setMergeModalOpen] = useState(false)@@ -48,45 +55,31 @@ export function TranscriptionView({const [targetSpeaker, setTargetSpeaker] = useState<string | null>(null)const [customSpeaker, setCustomSpeaker] = useState<string>('')const [speakerMappings, setSpeakerMappings] = useState<Record<string, string>>({})- const [editedChunks, setEditedChunks] = useState<Record<number, string>>({})const [selectedText, setSelectedText] = useState('')const [selectionPosition, setSelectionPosition] = useState<{ x: number; y: number } | null>(null)const [vocabDialogOpen, setVocabDialogOpen] = useState(false)const [vocabEntry, setVocabEntry] = useState('')const [notification, setNotification] = useState<{message: string, type: 'success' | 'error'} | null>(null)- const [improvingChunks, setImprovingChunks] = useState<Record<number, boolean>>({})- const [recentlyImproved, setRecentlyImproved] = useState<Record<number, boolean>>({})- const lastProcessedChunkRef = useRef<number>(-1)+ const lastProcessedChunkRef = useRef<number>(0)const [showLoadButton, setShowLoadButton] = useState(false)const [loadingHistory, setLoadingHistory] = useState(false)const { fetchRecentChunks } = useRecentChunks()+ const initialDataLoadRef = useRef(true)+ const { scrollRef, onScroll, isScrolledToBottom } = useAutoScroll(data?.chunks || [])- // Add logging for component mount/unmountuseEffect(() => {- console.log('transcription view mounted', {- chunksCount: chunks.length,- isLoading,- hasTitle: !!title,- hasNotes: notes.length > 0- })- return () => {- console.log('transcription view unmounting', {- chunksCount: chunks.length,- isLoading- })- }+ console.log('transcription view mounted')+ return () => console.log('transcription view unmounted')}, [])- // Add logging for chunks updatesuseEffect(() => {- console.log('chunks updated in transcription view', {- count: chunks.length,- lastChunk: chunks[chunks.length - 1]?.text,- isLoading- })- }, [chunks])+ if (data?.editedMergedChunks && initialDataLoadRef.current) {+ console.log('loading initial data from storage')+ lastProcessedChunkRef.current = data.chunks?.length - 1 || 0+ initialDataLoadRef.current = false+ }+ }, [data])- // Helper functionsconst getDisplaySpeaker = (speaker: string) => {return speakerMappings[speaker] ?? speaker}@@ -96,10 +89,9 @@ export function TranscriptionView({return speaker.startsWith('speaker_') ? `speaker ${speaker.split('_')[1]}` : speaker}- // Memoized valuesconst uniqueSpeakers = useMemo(() => {const speakerFirstAppearance = new Map<string, Date>()- chunks.forEach(chunk => {+ data?.chunks?.forEach(chunk => {if (chunk.speaker !== undefined) {const mappedSpeaker = speakerMappings[chunk.speaker] || chunk.speakerif (!speakerFirstAppearance.has(mappedSpeaker)) {@@ -108,7 +100,7 @@ export function TranscriptionView({}})- return Array.from(new Set(chunks.map(chunk => {+ return Array.from(new Set(data?.chunks?.map(chunk => {const speaker = chunk.speakerreturn speaker !== undefined ? speakerMappings[speaker] || speaker : undefined})))@@ -118,52 +110,13 @@ export function TranscriptionView({const timeB = speakerFirstAppearance.get(b)?.getTime() || 0return timeB - timeA})- }, [chunks, speakerMappings])-- const mergeChunks = useMemo(() => {- const merged: typeof chunks = []-- for (let i = 0; i < chunks.length; i++) {- const current = chunks[i]- const prev = merged[merged.length - 1]-- const currentSpeaker = current.speaker !== undefined ? getDisplaySpeaker(current.speaker) : undefined- const prevSpeaker = prev?.speaker !== undefined ? getDisplaySpeaker(prev.speaker) : undefined-- if (prev && currentSpeaker === prevSpeaker) {- merged[merged.length - 1] = {- ...prev,- text: `${prev.text} ${current.text}`,- }- } else {- merged.push(current)- }- }-- return merged- }, [chunks, speakerMappings])-- // Load initial state- useEffect(() => {- console.log('storing chunks in transcription view', {- count: chunks.length,- isLoading- })- storeLiveChunks(chunks)- }, [chunks])+ }, [data?.chunks, speakerMappings])const loadStoredData = async () => {try {setLoadingHistory(true)await fetchRecentChunks()-- if (data) {- console.log('loaded stored meeting data:', data)- setEditedChunks(data.editedChunks)- setSpeakerMappings(data.speakerMappings)- lastProcessedChunkRef.current = data.lastProcessedIndex- setShowLoadButton(false)- }+ await reloadData()} catch (error) {console.error('failed to load history:', error)} finally {@@ -171,28 +124,6 @@ export function TranscriptionView({}}- // Store chunks when they update- useEffect(() => {- console.log('storing chunks:', {- count: chunks.length,- isLoading- })- storeLiveChunks(chunks)- }, [chunks])-- // Move handleTextEdit inside the component- const handleTextEdit = useCallback(async (index: number, newText: string) => {- console.log('text edited for chunk', index, ':', newText)- if (!data) return-- const newEditedChunks = {- ...editedChunks,- [index]: newText- }- setEditedChunks(newEditedChunks)- await updateStore({ ...data, editedChunks: newEditedChunks })- }, [data, editedChunks, updateStore])-const mergeSpeakers = async (newSpeaker: string) => {if (!selectedSpeaker) returnif (!data) return@@ -211,19 +142,6 @@ export function TranscriptionView({setCustomSpeaker('')}- // Update last processed index- useEffect(() => {- if (lastProcessedChunkRef.current >= 0) {- if (data) {- updateStore({- ...data,- lastProcessedIndex: lastProcessedChunkRef.current- })- }- }- }, [lastProcessedChunkRef.current, data, updateStore])-- // Add selection handlerconst handleSelection = () => {const selection = window.getSelection()if (!selection || selection.isCollapsed) {@@ -241,7 +159,6 @@ export function TranscriptionView({}}- // Update vocabulary handler to open dialogconst addToVocabulary = () => {console.log('opening vocabulary dialog for:', selectedText)setVocabEntry(selectedText)@@ -249,7 +166,6 @@ export function TranscriptionView({setSelectionPosition(null)}- // Handle saving vocabularyconst handleSaveVocab = async () => {try {console.log('saving vocabulary:', selectedText, 'as', vocabEntry)@@ -267,112 +183,16 @@ export function TranscriptionView({}}- // Process previous merged chunk when a new one arrives- useEffect(() => {- const currentChunkIndex = mergeChunks.length - 1- const previousChunkIndex = currentChunkIndex - 1-- // Only process if we have a previous chunk and haven't processed it yet- if (previousChunkIndex >= 0 &&- previousChunkIndex > lastProcessedChunkRef.current &&- !improvingChunks[previousChunkIndex]) {-- const improveChunk = async () => {- setImprovingChunks(prev => ({ ...prev, [previousChunkIndex]: true }))-- try {- const chunk = mergeChunks[previousChunkIndex]- console.log('improving previous merged chunk:', chunk.text)-- const contextChunks = mergeChunks.slice(- Math.max(0, previousChunkIndex - 4),- previousChunkIndex + 1- )-- const improved = await improveTranscription(- chunk.text,- {- meetingTitle: title,- recentChunks: contextChunks,- notes: notes.map(note => note.text),- },- settings- )-- if (improved !== chunk.text) {- console.log('chunk improved:', improved)- await handleTextEdit(previousChunkIndex, improved)- setRecentlyImproved(prev => ({ ...prev, [previousChunkIndex]: true }))- setTimeout(() => {- setRecentlyImproved(prev => ({ ...prev, [previousChunkIndex]: false }))- }, 1000)- }-- lastProcessedChunkRef.current = previousChunkIndex- } catch (error) {- console.error('failed to improve chunk:', error)- } finally {- setImprovingChunks(prev => ({ ...prev, [previousChunkIndex]: false }))- }- }-- improveChunk()- }- }, [mergeChunks, title, notes, settings, data, updateStore, handleTextEdit, improvingChunks])-- // Update segments when mergeChunks changes- useEffect(() => {- console.log('updating segments in transcription view', {- mergedChunksCount: mergeChunks.length,- editedChunksCount: Object.keys(editedChunks).length,- speakerMappingsCount: Object.keys(speakerMappings).length- })- // Don't call setNotes here as it overwrites meeting notes- // Instead, update segments separately- }, [mergeChunks, editedChunks, speakerMappings])-- const handleGenerateNote = async (index: number) => {+ const handleGenerateNote = async (chunk: TranscriptionChunk) => {try {- console.log('generating note for chunk:', index)- const contextChunks = mergeChunks.slice(- Math.max(0, index - 4),- index + 1- )-- const note = await generateMeetingNote(contextChunks, settings)- console.log('generated note:', note)-- // Add the generated note to the meeting context- setNotes([...notes, {- id: crypto.randomUUID(),- text: note,- timestamp: new Date(mergeChunks[index].timestamp)- }])-+ const note = await generateMeetingNote([chunk], settings)+ setNotes([...notes, { id: crypto.randomUUID(), text: note, timestamp: new Date(chunk.timestamp) }])} catch (error) {console.error('failed to generate note:', error)}}- // Add immediate chunk processing- useEffect(() => {- console.log('processing new chunks:', {- total: chunks.length,- merged: mergeChunks.length- })-- // Force a re-render when chunks update- const timer = requestAnimationFrame(() => {- if (scrollRef.current && isAutoScrollEnabled) {- scrollRef.current.scrollTo({- top: scrollRef.current.scrollHeight,- behavior: 'smooth'- })- }- })-- return () => cancelAnimationFrame(timer)- }, [chunks, mergeChunks.length])+ const mergedChunks = data?.mergedChunks || []return (<>@@ -394,12 +214,12 @@ export function TranscriptionView({onMouseUp={handleSelection}className="flex-1 overflow-y-auto bg-card min-h-0">- {mergeChunks.length === 0 && (+ {(!data?.chunks || data.chunks.length === 0) && (<div className="flex items-center justify-center h-full text-gray-500"><p>waiting for transcription...</p></div>)}- {mergeChunks.length > 0 && (+ {data?.chunks && data.chunks.length > 0 && (<div className="space-y-2 relative p-4"><buttononClick={() => setViewMode(prev => {@@ -412,8 +232,11 @@ export function TranscriptionView({>{viewMode === 'overlay' ? <LayoutList className="h-4 w-4" /> : viewMode === 'sidebar' ? <Layout className="h-4 w-4" /> : <Layout className="h-4 w-4" />}</button>- {mergeChunks.map((chunk, i) => (- <div key={i} className="text-sm mb-2 group relative">+ {mergedChunks.map((chunk) => (+ <div+ key={chunk.id}+ className="text-sm mb-2 group relative"+ >{viewMode === 'overlay' ? (<><ChunkOverlay@@ -426,20 +249,17 @@ export function TranscriptionView({setMergeModalOpen(true)}}}- onGenerateNote={() => handleGenerateNote(i)}+ onGenerateNote={() => handleGenerateNote(chunk)}/><div className="relative">- <div- contentEditable- suppressContentEditableWarning- onBlur={(e) => handleTextEdit(i, e.currentTarget.textContent || '')}- className={cn(- "outline-none focus:ring-1 focus:ring-gray-200 rounded px-1 -mx-1",- improvingChunks[i] && "animate-shimmer bg-gradient-to-r from-transparent via-gray-100/50 to-transparent bg-[length:200%_100%]",- recentlyImproved[i] && "animate-glow"- )}- >- {editedChunks[i] ?? chunk.text}+ <div className={cn(+ "outline-none rounded px-1 -mx-1",+ improvingChunks[chunk.id] && "animate-shimmer bg-gradient-to-r from-transparent via-gray-100/50 to-transparent bg-[length:200%_100%]",+ recentlyImproved[chunk.id] && "animate-glow"+ )}>+ {data?.editedMergedChunks[chunk.id]?.diffs ? (+ <DiffText diffs={data.editedMergedChunks[chunk.id].diffs} />+ ) : data?.editedMergedChunks[chunk.id]?.text || chunk.text}</div></div></>@@ -459,13 +279,8 @@ export function TranscriptionView({</button>)}</div>- <div- contentEditable- suppressContentEditableWarning- onBlur={(e) => handleTextEdit(i, e.currentTarget.textContent || '')}- className="outline-none focus:ring-1 focus:ring-gray-200 rounded flex-1"- >- {editedChunks[i] ?? chunk.text}+ <div className="outline-none rounded flex-1">+ {chunk.text}</div></div>) : (@@ -483,13 +298,8 @@ export function TranscriptionView({</button>)}</div>- <div- contentEditable- suppressContentEditableWarning- onBlur={(e) => handleTextEdit(i, e.currentTarget.textContent || '')}- className="outline-none focus:ring-1 focus:ring-gray-200 rounded flex-1"- >- {editedChunks[i] ?? chunk.text}+ <div className="outline-none rounded flex-1">+ {chunk.text}</div></div>)}@@ -500,7 +310,7 @@ export function TranscriptionView({</div></div>- {!isAutoScrollEnabled && !isScrolledToBottom && (+ {!isScrolledToBottom && (<buttononClick={() => scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })}className="absolute bottom-4 right-4 p-2 bg-black text-white rounded-full shadow-lg hover:bg-gray-800 transition-colors"@@ -509,7 +319,6 @@ export function TranscriptionView({</button>)}- {/* Add vocabulary button */}{selectedText && selectionPosition && (<buttononClick={addToVocabulary}@@ -524,7 +333,6 @@ export function TranscriptionView({</button>)}- {/* Speaker Merge Modal */}<Dialog open={mergeModalOpen} onOpenChange={setMergeModalOpen}><DialogContent className="sm:max-w-md max-h-[70vh] flex flex-col"><DialogHeader>@@ -575,7 +383,6 @@ export function TranscriptionView({</DialogContent></Dialog>- {/* Speaker Name Modal */}<Dialog open={nameModalOpen} onOpenChange={setNameModalOpen}><DialogContent className="sm:max-w-md"><DialogHeader>diff --git a/pipes/meeting/src/components/live-transcription/use-transcription-service.ts b/pipes/meeting/src/components/live-transcription/use-transcription-service.tsindex 2a2da9d25..1e71ec48e 100644--- a/pipes/meeting/src/components/live-transcription/use-transcription-service.ts+++ b/pipes/meeting/src/components/live-transcription/use-transcription-service.ts@@ -1,37 +1,93 @@import { useRecentChunks } from './hooks/pull-meetings-from-screenpipe'import { useTranscriptionStream } from './hooks/screenpipe-stream-transcription-api'import { useBrowserTranscriptionStream } from './hooks/browser-stream-transcription-api'-import { useEffect, useRef } from 'react'-import { getLiveMeetingData } from './hooks/storage-for-live-meeting'+import { useEffect, useRef, useState, useCallback } from 'react'+import { useMeetingContext } from './hooks/storage-for-live-meeting'import { usePostHog } from 'posthog-js/react'type TranscriptionMode = 'browser' | 'screenpipe'-export function useTranscriptionService(mode: TranscriptionMode = 'browser') {+// Update GLOBAL_STATE to include health check result+const GLOBAL_STATE = {+ isInitialized: false,+ healthChecked: false,+ isHealthy: false+}++export function useTranscriptionService(mode?: TranscriptionMode) {const { chunks, setChunks, isLoading, fetchRecentChunks } = useRecentChunks()- const { startTranscriptionScreenpipe, stopTranscriptionScreenpipe } = useTranscriptionStream(setChunks)- const { startTranscriptionBrowser, stopTranscriptionBrowser } = useBrowserTranscriptionStream(setChunks)- const initRef = useRef(false)+ const { onNewChunk } = useMeetingContext()+ const { startTranscriptionScreenpipe, stopTranscriptionScreenpipe } = useTranscriptionStream(onNewChunk)+ const { startTranscriptionBrowser, stopTranscriptionBrowser } = useBrowserTranscriptionStream(onNewChunk)const modeRef = useRef<TranscriptionMode | null>(null)const posthog = usePostHog()+ const [isHealthChecking, setIsHealthChecking] = useState(true)++ // New state and refs for recording control+ const [isRecording, setIsRecording] = useState(false)+ const mountedRef = useRef(true)+ const isTransitioningRef = useRef(false)+ const keepRecordingRef = useRef(false)++ // Check health and determine initial mode+ const checkHealth = async () => {+ try {+ const response = await fetch('http://localhost:3030/health')+ const health = await response.json()++ if (health.status === 'healthy') {+ console.log('transcription-service: health check passed, using screenpipe')+ return 'screenpipe'+ } else {+ console.log('transcription-service: health check failed, using browser')+ return 'browser'+ }+ } catch (error) {+ console.log('transcription-service: health check error, using browser:', error)+ return 'browser'+ }+ }- // Load stored chunks only once+ // Simplified initialization effect without intervaluseEffect(() => {- const loadStoredChunks = async () => {- if (initRef.current) return- initRef.current = true+ const initializeTranscription = async () => {+ if (modeRef.current !== null) return // Already initialized++ setIsHealthChecking(true)- const storedData = await getLiveMeetingData()- if (storedData?.chunks) {- console.log('transcription-service: loading stored chunks:', storedData.chunks.length)- setChunks(storedData.chunks)+ // Only check health once+ let healthMode: TranscriptionMode+ if (!GLOBAL_STATE.healthChecked) {+ healthMode = await checkHealth()+ GLOBAL_STATE.healthChecked = true+ GLOBAL_STATE.isHealthy = healthMode === 'screenpipe'+ } else {+ healthMode = GLOBAL_STATE.isHealthy ? 'screenpipe' : 'browser'+ console.log('transcription-service: using cached health status:', healthMode)}++ const finalMode = mode || healthMode+ console.log('transcription-service: initializing with mode:', finalMode)++ modeRef.current = finalMode+ posthog.capture('meeting_web_app_transcription_mode_initialized', {+ mode: finalMode,+ requested_mode: mode,+ health_mode: healthMode,+ from_cache: GLOBAL_STATE.healthChecked+ })++ setIsHealthChecking(false)}- loadStoredChunks()- }, [setChunks])++ initializeTranscription()+ // No more interval needed+ }, [mode, startTranscriptionScreenpipe, stopTranscriptionScreenpipe, startTranscriptionBrowser, stopTranscriptionBrowser, posthog])// Handle transcription mode initialization and changesuseEffect(() => {+ if (isHealthChecking || !mode) return+// First mount or mode changeif (modeRef.current !== mode) {console.log('transcription-service: mode', modeRef.current ? 'changed from ' + modeRef.current + ' to: ' + mode : 'initialized to: ' + mode)@@ -80,11 +136,89 @@ export function useTranscriptionService(mode: TranscriptionMode = 'browser') {posthog.capture('meeting_web_app_transcription_stopped', { mode: modeRef.current })}}- }, [mode, startTranscriptionScreenpipe, stopTranscriptionScreenpipe, startTranscriptionBrowser, stopTranscriptionBrowser, posthog])+ }, [mode, isHealthChecking, startTranscriptionScreenpipe, stopTranscriptionScreenpipe, startTranscriptionBrowser, stopTranscriptionBrowser, posthog])++ // Add toggle functionality+ const toggleRecording = useCallback(async (newState?: boolean) => {+ const nextState = newState ?? !isRecording+ console.log('toggling recording:', {+ current: isRecording,+ next: nextState,+ mode: modeRef.current+ })++ keepRecordingRef.current = nextState++ if (nextState) {+ if (!GLOBAL_STATE.isInitialized) {+ // Use current mode if none specified+ const currentMode = mode || modeRef.current+ if (!currentMode) {+ console.error('transcription-service: no mode available')+ return+ }++ modeRef.current = currentMode+ if (currentMode === 'browser') {+ startTranscriptionBrowser()+ } else {+ startTranscriptionScreenpipe()+ }+ GLOBAL_STATE.isInitialized = true+ }+ } else {+ // Stop transcription logic - Fix: Use modeRef.current instead of mode+ if (GLOBAL_STATE.isInitialized) {+ if (modeRef.current === 'browser') {+ stopTranscriptionBrowser()+ } else {+ stopTranscriptionScreenpipe()+ }+ GLOBAL_STATE.isInitialized = false+ }+ }+ setIsRecording(nextState)+ }, [isRecording, mode, startTranscriptionBrowser, startTranscriptionScreenpipe,+ stopTranscriptionBrowser, stopTranscriptionScreenpipe])++ // Better cleanup on unmount+ useEffect(() => {+ console.log('transcription service mounted')+ mountedRef.current = true+ return () => {+ console.log('transcription service unmounting, keepRecording:', keepRecordingRef.current)+ mountedRef.current = false+ if (!keepRecordingRef.current) {+ isTransitioningRef.current = true+ if (modeRef.current === 'browser') {+ stopTranscriptionBrowser()+ } else {+ stopTranscriptionScreenpipe()+ }+ GLOBAL_STATE.isInitialized = false+ console.log('transcription service cleanup complete')+ }+ }+ }, [stopTranscriptionBrowser, stopTranscriptionScreenpipe])++ // Keep transcription active on tab visibility change+ useEffect(() => {+ const handleVisibilityChange = () => {+ console.log('visibility changed, keeping transcription active:', {+ state: document.visibilityState+ })+ // No action taken on tab hidden/visible+ }++ document.addEventListener('visibilitychange', handleVisibilityChange)+ return () => document.removeEventListener('visibilitychange', handleVisibilityChange)+ }, [])return {chunks,- isLoadingRecent: isLoading,- fetchRecentChunks+ isLoadingRecent: isLoading || isHealthChecking,+ fetchRecentChunks,+ isRecording,+ toggleRecording}}\ No newline at end of filediff --git a/pipes/meeting/src/components/meeting-history/ai-meeting-summary.ts b/pipes/meeting/src/components/meeting-history/ai-meeting-summary.tsdeleted file mode 100644index c72a87c84..000000000--- a/pipes/meeting/src/components/meeting-history/ai-meeting-summary.ts+++ /dev/null@@ -1,170 +0,0 @@-import { Meeting } from "./types";-import type { Settings } from "@screenpipe/browser"-import { createAiClient } from "./ai-meeting-title";--export async function generateMeetingSummary(- meeting: Meeting,- settings: Settings-): Promise<string> {- const openai = createAiClient({ settings });-- try {- console.log(- "generating ai summary for meeting:",- {- id: meeting.id,- segments_count: meeting.segments.length,- notes_count: meeting.notes.length,- total_transcript_length: meeting.segments.reduce((acc, s) => acc + s.transcription.length, 0),- total_notes_length: meeting.notes.reduce((acc, n) => acc + n.text.length, 0)- }- );-- // Create prompt from meeting data- const transcriptContent = meeting.segments- .map(- (s) =>- `[${s.speaker}]: ${s.transcription}`- )- .join("\n");-- // Add notes context if available- const notesContext = meeting.notes.length > 0- ? `\nMeeting notes:\n${meeting.notes.join("\n")}`- : "";-- const currentSummary = meeting.aiSummary;- const summaryContext = currentSummary- ? `\nCurrent summary: "${currentSummary}"\nPlease generate a new summary that might be more accurate.`- : "";-- const currentTitle = meeting.humanName || meeting.aiName;- const titleContext = currentTitle- ? `\nMeeting title: "${currentTitle}"`- : "";-- // First AI call for detailed analysis- const analysisMessages = [- {- role: "system" as const,- content: "you are a meeting participant. analyze our discussion to understand: who was there, what we talked about, what we decided, and what our next steps are. be specific but concise.",- },- {- role: "user" as const,- content: `please analyze our meeting:${titleContext}\n\n${transcriptContent}${notesContext}`,- },- ];-- console.log("sending request to openai for meeting analysis");- const analysisResponse = await openai.chat.completions.create({- model: settings.aiModel,- messages: analysisMessages,- temperature: 0.7,- max_tokens: 500,- });-- const analysis = analysisResponse.choices[0]?.message?.content?.trim() || "";- console.log("generated meeting analysis:", analysis.slice(0, 100) + "...");-- // Second AI call for final concise summary using the analysis- const messages = [- {- role: "system" as const,- content: "you are a meeting participant writing a quick summary (max 100 words) of what we just discussed. focus on our key decisions and next steps. use bullet points for clarity. write in first person plural (we/our). do not use markdown formatting.",- },- {- role: "user" as const,- content: `write a quick summary of our meeting (max 100 words). what did we discuss and decide? what are our next steps? do not use markdown formatting:-meeting title: ${titleContext}-${summaryContext}-our discussion details: ${analysis}--transcript:-${transcriptContent}-${notesContext}`,- },- ];-- console.log("sending request to openai for final meeting summary", {- current_title: currentTitle,- current_summary: currentSummary ? currentSummary.slice(0, 100) + "..." : null,- analysis_sample: analysis.slice(0, 100) + "..."- });-- const response = await openai.chat.completions.create({- model: settings.aiModel,- messages,- temperature: 0.7,- max_tokens: 200, // Reduced for more concise summaries- });-- const aiSummary = (response.choices[0]?.message?.content?.trim() || "no summary available")- .replace(/\*\*/g, '') // Remove any markdown bold- .replace(/^#+\s*/gm, '') // Remove markdown headers- .replace(/^\s*[-*]\s*/gm, '• ') // Standardize bullet points- .trim();- console.log("generated ai summary:", aiSummary.slice(0, 100) + "...");-- // Final AI call to condense the summary- const condensedMessages = [- {- role: "system" as const,- content: "you are a meeting participant writing a very brief summary (50 words) of what we just discussed. focus on our main points and next actions. use bullet points. write in first person plural (we/our). do not use markdown formatting.",- },- {- role: "user" as const,- content: `give me the key points from our meeting in 50 words or less:--${aiSummary}`,- },- ];-- console.log("sending request to openai for condensed summary");- const condensedResponse = await openai.chat.completions.create({- model: settings.aiModel,- messages: condensedMessages,- temperature: 0.7,- max_tokens: 100,- });-- const condensedSummary = (condensedResponse.choices[0]?.message?.content?.trim() || aiSummary)- .replace(/\*\*/g, '')- .replace(/^#+\s*/gm, '')- .replace(/^\s*[-*]\s*/gm, '• ')- .trim();-- console.log("generated condensed summary:", condensedSummary.slice(0, 100) + "...");-- return condensedSummary;- } catch (error) {- console.error("error generating meeting summary:", error);- return "failed to generate summary";- }-}--// Helper function to generate summaries for multiple meetings-export async function generateMeetingSummaries(- meetings: Meeting[],- settings: Settings-): Promise<Record<string, string>> {- const results: Record<string, string> = {};-- // Process meetings in parallel with a concurrency limit- const concurrencyLimit = 2; // Reduced from 3 due to larger content- const chunks = [];-- for (let i = 0; i < meetings.length; i += concurrencyLimit) {- chunks.push(meetings.slice(i, i + concurrencyLimit));- }-- for (const chunk of chunks) {- const promises = chunk.map(async (meeting) => {- const summary = await generateMeetingSummary(meeting, settings);- results[meeting.id] = summary;- });-- await Promise.all(promises);- }-- return results;-}\ No newline at end of filediff --git a/pipes/meeting/src/components/meeting-history/ai-meeting-title.ts b/pipes/meeting/src/components/meeting-history/ai-meeting-title.tsdeleted file mode 100644index 0bbab3338..000000000--- a/pipes/meeting/src/components/meeting-history/ai-meeting-title.ts+++ /dev/null@@ -1,121 +0,0 @@-import { Meeting } from "./types";-import { OpenAI } from "openai";-import type { Settings } from "@screenpipe/browser"--interface AiClientConfig {- settings: Settings;-}--export function createAiClient({ settings }: AiClientConfig) {- return new OpenAI({- apiKey:- settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,- dangerouslyAllowBrowser: true,- });-}--export async function generateMeetingName(- meeting: Meeting,- settings: Settings-): Promise<string> {- const openai = createAiClient({ settings });-- try {- console.log(- "generating ai name for meeting:",- {- id: meeting.id,- segments_count: meeting.segments.length,- notes_count: meeting.notes.length,- total_transcript_length: meeting.segments.reduce((acc, s) => acc + s.transcription.length, 0),- total_notes_length: meeting.notes.reduce((acc, n) => acc + n.text.length, 0)- }- );-- // Create prompt from meeting data- const transcriptSample = meeting.segments- .map(- (s) =>- `[${s.speaker}]: ${s.transcription}`- )- .join("\n");-- // Add notes context if available- const notesContext = meeting.notes.length > 0- ? `\nMeeting notes:\n${meeting.notes.join("\n")}`- : "";-- const currentTitle = meeting.humanName || meeting.aiName;- const titleContext = currentTitle- ? `\nCurrent title: "${currentTitle}"\nPlease generate a new title that might be more accurate.`- : "";-- const messages = [- {- role: "system" as const,- content: "you are a helpful assistant that generates concise (max 6 words) but informative meeting titles. include key facts like participants, purpose, or project name if available. avoid generic descriptions.",- },- {- role: "user" as const,- content: `analyze the meeting context and generate a factual title that captures WHO (key participants/teams), WHAT (main topic/project), or WHY (purpose/goal) if these are clear from the context. keep it under 6 words:${titleContext}\n\n${transcriptSample}${notesContext}`,- },- ];-- console.log("sending request to openai for meeting name", {- current_title: currentTitle,- segments_sample: transcriptSample.slice(0, 100) + "..."- });- const response = await openai.chat.completions.create({- model: settings.aiModel,- messages,- temperature: 0.7,- max_tokens: 20,- });-- const aiName = response.choices[0]?.message?.content?.trim() || "untitled meeting";- // console.log("raw generated ai name:", aiName);-- // Sanitize the AI generated name- const sanitizedName = aiName- .replace(/["']/g, '') // Remove quotes- .replace(/[^\w\s-]/g, ' ') // Replace special chars with space- .trim();-- console.log("sanitized ai name:", sanitizedName);-- return sanitizedName;- } catch (error) {- console.error("error generating meeting name:", error);- return "untitled meeting";- }-}--// Helper function to generate names for multiple meetings-export async function generateMeetingNames(- meetings: Meeting[],- settings: Settings-): Promise<Record<string, string>> {- const results: Record<string, string> = {};-- // Process meetings in parallel with a concurrency limit- const concurrencyLimit = 3;- const chunks = [];-- for (let i = 0; i < meetings.length; i += concurrencyLimit) {- chunks.push(meetings.slice(i, i + concurrencyLimit));- }-- for (const chunk of chunks) {- const promises = chunk.map(async (meeting) => {- const name = await generateMeetingName(meeting, settings);- results[meeting.id] = name;- });-- await Promise.all(promises);- }-- return results;-}\ No newline at end of filediff --git a/pipes/meeting/src/components/meeting-history/components/meeting-card.tsx b/pipes/meeting/src/components/meeting-history/components/meeting-card.tsxindex f56a67332..37e27a69d 100644--- a/pipes/meeting/src/components/meeting-history/components/meeting-card.tsx+++ b/pipes/meeting/src/components/meeting-history/components/meeting-card.tsx@@ -1,28 +1,50 @@import { Card, CardContent } from "@/components/ui/card"-import { Meeting } from "../types"import { Button } from "@/components/ui/button"-import { Wand2, FileText, ChevronDown } from "lucide-react"+import { Wand2, FileText, ChevronDown, Trash2 } from "lucide-react"import { useState } from "react"-import { generateMeetingName } from "../ai-meeting-title"-import { useSettings } from "@/lib/hooks/use-settings"-import { updateMeeting } from "../hooks/storage-meeting-data"import { useToast } from "@/hooks/use-toast"import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card"-import { generateMeetingSummary } from "../ai-meeting-summary"import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"import { MeetingPrepDetails } from "./meeting-prep-card"import { Settings } from "@screenpipe/browser"+import { LiveMeetingData } from "@/components/live-transcription/hooks/storage-for-live-meeting"+import { generateMeetingName } from "../../live-transcription/hooks/ai-meeting-title"+import { generateMeetingSummary } from "../../live-transcription/hooks/ai-meeting-summary"+import { MeetingAnalysis } from "../../live-transcription/hooks/ai-create-all-notes"+import type { MeetingPrep } from "../types"+import { useRouter } from "next/navigation"+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"+import { Checkbox } from "@/components/ui/checkbox"interface MeetingCardProps {- meeting: Meeting- onUpdate: (id: string, update: { aiName?: string; aiSummary?: string }) => void+ meeting: LiveMeetingData+ onUpdate: (id: string, update: {+ aiName?: string;+ aiSummary?: string;+ analysis?: MeetingAnalysis | null;+ title?: string;+ }) => voidsettings: Settings+ onDelete?: () => void+ isLive?: boolean+ onLoadArchived?: () => void}-export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {+function getWordCount(meeting: LiveMeetingData): number {+ return meeting.chunks?.reduce((count, chunk) => {+ // Split by whitespace and filter out empty strings+ const words = chunk.text?.split(/\s+/).filter(word => word.length > 0) || []+ return count + words.length+ }, 0) || 0+}++export function MeetingCard({ meeting, onUpdate, settings, onDelete, isLive, onLoadArchived }: MeetingCardProps) {+ const router = useRouter()const [isGenerating, setIsGenerating] = useState(false)const [isGeneratingSummary, setIsGeneratingSummary] = useState(false)const { toast } = useToast()+ const [showDeleteDialog, setShowDeleteDialog] = useState(false)+ const [dontAskAgain, setDontAskAgain] = useState(false)const formatTime = (dateStr: string): string => {return new Date(dateStr).toLocaleTimeString([], {@@ -31,7 +53,8 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {})}- const formatDuration = (start: string, end: string): string => {+ const formatDuration = (start: string, end?: string): string => {+ if (!end) return '0m'const startTime = new Date(start).getTime()const endTime = new Date(end).getTime()const durationMs = endTime - startTime@@ -55,16 +78,18 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {throw new Error("no settings found")}- console.log("generating name for meeting:", meeting.id)- const aiName = await generateMeetingName(meeting, settings)+ console.log("generating name for meeting:", {+ id: meeting.id,+ currentTitle: meeting.title+ })- if (!meeting.id) {- throw new Error("no meeting id found")- }+ const newTitle = await generateMeetingName(meeting, settings)- // Update meeting in storage and notify parent- await updateMeeting(meeting.id, { aiName })- onUpdate(meeting.id, { aiName })+ onUpdate(meeting.id, {+ title: newTitle,+ aiName: newTitle, // Adding this for backwards compatibility+ analysis: meeting.analysis // Preserve existing analysis+ })toast({title: "name generated",@@ -91,16 +116,23 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {throw new Error("no settings found")}- console.log("generating summary for meeting:", meeting.id)- const aiSummary = await generateMeetingSummary(meeting, settings)+ console.log("generating summary for meeting:", {+ id: meeting.id,+ title: meeting.title+ })- if (!meeting.id) {- throw new Error("no meeting id found")- }+ const aiSummary = await generateMeetingSummary(meeting, settings)- // Update meeting in storage and notify parent- await updateMeeting(meeting.id, { aiSummary })- onUpdate(meeting.id, { aiSummary })+ // Update only the analysis field while preserving other fields+ onUpdate(meeting.id, {+ analysis: {+ facts: meeting.analysis?.facts || [],+ events: meeting.analysis?.events || [],+ flow: meeting.analysis?.flow || [],+ decisions: meeting.analysis?.decisions || [],+ summary: [aiSummary]+ }+ })toast({title: "summary generated",@@ -109,7 +141,7 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {} catch (error) {console.error("failed to generate summary:", error)toast({- title: "generation failed",+ title: "generation failed",description: "failed to generate ai summary. please try again",variant: "destructive",})@@ -118,24 +150,72 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {}}- const getDurationMinutes = (start: string, end: string): number => {+ const getDurationMinutes = (start: string, end?: string): number => {+ if (!end) return 0const startTime = new Date(start).getTime()const endTime = new Date(end).getTime()return Math.floor((endTime - startTime) / (1000 * 60))}- const getDurationScale = (minutes: number): string => {- // Scale between 0.5 and 1 for meetings between 0 and 60 minutes- const scale = 0.5 + Math.min(minutes / 60, 1) * 0.5- return `scale-y-[${scale}]`+ const durationMinutes = getDurationMinutes(meeting.startTime, meeting.endTime)++ const wordCount = getWordCount(meeting)++ const handleCardClick = () => {+ if (isLive) {+ // Instead of router.push, use window.location for a full page load+ window.location.href = '/meetings/live'+ } else if (onLoadArchived) {+ console.log('loading archived meeting:', {+ id: meeting.id,+ title: meeting.title,+ startTime: meeting.startTime+ })+ onLoadArchived()+ }}- const durationMinutes = getDurationMinutes(meeting.meetingStart, meeting.meetingEnd)- const scaleClass = getDurationScale(durationMinutes)+ const handleDeleteClick = (e: React.MouseEvent) => {+ e.stopPropagation()+ const skipConfirm = localStorage.getItem('skipDeleteConfirm') === 'true'++ if (skipConfirm) {+ onDelete?.()+ } else {+ setShowDeleteDialog(true)+ }+ }++ const handleConfirmDelete = () => {+ if (dontAskAgain) {+ localStorage.setItem('skipDeleteConfirm', 'true')+ }+ setShowDeleteDialog(false)+ onDelete?.()+ }return (- <Card className="w-full mb-1 border-0 -mx-2">+ <Card+ className="w-full mb-1 border-0 -mx-2 cursor-pointer hover:bg-accent/50"+ onClick={handleCardClick}+ ><CardContent className="p-3 relative">+ {!isLive && onLoadArchived && (+ <div className="absolute right-2 top-2">+ <HoverCard openDelay={0} closeDelay={0}>+ <HoverCardTrigger>+ <div className="text-xs text-muted-foreground bg-accent/50 px-1.5 py-0.5 rounded">+ archived+ </div>+ </HoverCardTrigger>+ <HoverCardContent className="w-auto p-2">+ <span className="text-sm text-muted-foreground">+ click to load and edit this meeting+ </span>+ </HoverCardContent>+ </HoverCard>+ </div>+ )}<div className="absolute left-0 top-0 bottom-0 w-1 bg-muted-foreground/10 origin-bottom transition-transform duration-500"style={{transform: `scaleY(${0.5 + Math.min(durationMinutes / 60, 1) * 0.5})`,@@ -145,17 +225,20 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {<div className="flex gap-4"><div className="flex-none w-[30%]"><h3 className="text-base font-bold">- {(meeting.humanName || meeting.aiName || "untitled meeting").replace(/^"|"$/g, '')}+ {meeting.title || "untitled meeting"}</h3><div className="text-sm text-muted-foreground flex items-center justify-between"><div className="flex items-center">- {formatTime(meeting.meetingStart)} • {formatDuration(meeting.meetingStart, meeting.meetingEnd)}- <div- className="h-3 w-2 bg-muted-foreground/20 origin-left transition-transform duration-500 ml-2"- style={{ transform: `scaleX(${0.5 + Math.min(durationMinutes / 60, 1) * 5.0})` }}- />+ {formatTime(meeting.startTime)} • {formatDuration(meeting.startTime, meeting.endTime)}+ {wordCount > 0 && (+ <>+ {" • "}+ {wordCount.toLocaleString()} words+ </>+ )}</div><div className="flex">+ {/* Temporarily disabled title generation<HoverCard openDelay={0} closeDelay={0}><HoverCardTrigger asChild><Button@@ -174,6 +257,8 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {</span></HoverCardContent></HoverCard>+ */}+ {/* Temporarily disabled summary generation<HoverCard openDelay={0} closeDelay={0}><HoverCardTrigger asChild><Button@@ -192,7 +277,8 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {</span></HoverCardContent></HoverCard>- {meeting.aiPrep && (+ */}+ {meeting.analysis && !meeting.endTime && 'previousContext' in meeting.analysis && (<HoverCard openDelay={0} closeDelay={0}><HoverCardTrigger asChild><Collapsible>@@ -207,7 +293,7 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {</Button></CollapsibleTrigger><CollapsibleContent className="absolute left-0 right-0 mt-2 z-20 bg-white dark:bg-gray-950 border rounded-md p-4 shadow-lg">- <MeetingPrepDetails aiPrep={meeting.aiPrep} />+ <MeetingPrepDetails aiPrep={meeting.analysis as unknown as MeetingPrep} /></CollapsibleContent></Collapsible></HoverCardTrigger>@@ -218,23 +304,79 @@ export function MeetingCard({ meeting, onUpdate, settings }: MeetingCardProps) {</HoverCardContent></HoverCard>)}+ <HoverCard openDelay={0} closeDelay={0}>+ <HoverCardTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="h-6 px-1 text-destructive"+ onClick={handleDeleteClick}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </HoverCardTrigger>+ <HoverCardContent className="w-auto p-2">+ <span className="text-sm text-muted-foreground">+ delete this meeting+ </span>+ </HoverCardContent>+ </HoverCard></div></div></div><div className="flex-1">- {meeting.agenda && (- <div className="text-sm text-muted-foreground mb-2">- {meeting.agenda}- </div>- )}- {meeting.aiSummary && (+ {meeting.analysis?.summary && (<div className="text-sm text-muted-foreground">- {meeting.aiSummary}+ {meeting.analysis.summary}</div>)}</div></div></CardContent>+ <Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>+ <DialogContent onClick={(e) => e.stopPropagation()}>+ <DialogHeader>+ <DialogTitle>delete meeting</DialogTitle>+ </DialogHeader>+ <DialogDescription>+ are you sure you want to delete this meeting?+ </DialogDescription>+ <div className="flex items-center space-x-2" onClick={(e) => e.stopPropagation()}>+ <Checkbox+ id="dontAskAgain"+ checked={dontAskAgain}+ onCheckedChange={(checked) => setDontAskAgain(checked as boolean)}+ />+ <label+ htmlFor="dontAskAgain"+ className="text-sm text-muted-foreground"+ onClick={(e) => e.stopPropagation()}+ >+ don't ask again+ </label>+ </div>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={(e) => {+ e.stopPropagation()+ setShowDeleteDialog(false)+ }}+ >+ cancel+ </Button>+ <Button+ variant="destructive"+ onClick={(e) => {+ e.stopPropagation()+ handleConfirmDelete()+ }}+ >+ delete+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog></Card>)}\ No newline at end of filediff --git a/pipes/meeting/src/components/meeting-history/components/meeting-settings.tsx b/pipes/meeting/src/components/meeting-history/components/meeting-settings.tsxindex dcb853630..817a960d1 100644--- a/pipes/meeting/src/components/meeting-history/components/meeting-settings.tsx+++ b/pipes/meeting/src/components/meeting-history/components/meeting-settings.tsx@@ -6,7 +6,7 @@ import { Input } from "@/components/ui/input"import { ArrowLeft, Trash2, Eye, EyeOff } from "lucide-react"import { useEffect, useState } from 'react'import { getMeetings, getAllUpdates } from '../hooks/storage-meeting-data'-import { liveStore } from '../../live-transcription/hooks/storage-for-live-meeting'+import { meetingStore } from '../../live-transcription/hooks/storage-for-live-meeting'interface MeetingSettingsProps {onBack: () => void@@ -39,10 +39,10 @@ export function MeetingSettings({ onBack }: MeetingSettingsProps) {const updates = await getAllUpdates()// Get all live meetings- const liveKeys = await liveStore.keys()+ const liveKeys = await meetingStore.keys()const liveMeetings: Record<string, any> = {}for (const key of liveKeys) {- liveMeetings[key] = await liveStore.getItem(key)+ liveMeetings[key] = await meetingStore.getItem(key)}console.log('loaded storage data:', {diff --git a/pipes/meeting/src/components/meeting-history/components/mockup-upcoming-meetings.tsx b/pipes/meeting/src/components/meeting-history/components/mockup-upcoming-meetings.tsxindex 43661b4cc..b21bb9efa 100644--- a/pipes/meeting/src/components/meeting-history/components/mockup-upcoming-meetings.tsx+++ b/pipes/meeting/src/components/meeting-history/components/mockup-upcoming-meetings.tsx@@ -1,27 +1,27 @@-import { Meeting, MeetingPrep } from "../types"import { MeetingCard } from "./meeting-card"-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"-import { ChevronDown } from "lucide-react"-import { MeetingPrepDetails } from "./meeting-prep-card"import { useSettings } from "@/lib/hooks/use-settings"+import { LiveMeetingData } from "@/components/live-transcription/hooks/storage-for-live-meeting"// Mock data for upcoming meetings-const MOCK_UPCOMING_MEETINGS: Meeting[] = [+const MOCK_UPCOMING_MEETINGS: LiveMeetingData[] = [{id: "1",- humanName: "Recording demo for screenpipe",- meetingStart: "2024-01-30T15:00:00",- meetingEnd: "2024-01-30T17:00:00",+ title: "Recording demo for screenpipe",+ startTime: "2024-01-30T15:00:00",+ endTime: "2024-01-30T17:00:00",agenda: "screenpipe intelligence showcasing example app of meeting assistant called granola 2.0. Participants record a studio quality demo of the product, talking about its feature and overall company advancements",- aiSummary: null,+ analysis: null,participants_invited: ["louis beaumont", "matt diakonov"],recurrence: "weekly on thursday",- aiName: null,participants: null,- selectedDevices: new Set(),- deviceNames: new Set(),- segments: [],+ chunks: [],+ mergedChunks: [],+ editedMergedChunks: {},+ speakerMappings: {},+ lastProcessedIndex: -1,notes: [],+ deviceNames: new Set(),+ selectedDevices: new Set(),aiPrep: {previousContext: {lastInteraction: "2024-01-23: LinkedIn Agent Demo",@@ -62,23 +62,27 @@ const MOCK_UPCOMING_MEETINGS: Meeting[] = ["emphasize platform capabilities through agent examples"]}- }+ },+ isAiNotesEnabled: true,},{id: "2",- humanName: "Ship-it at f.inc (accountability group)",- meetingStart: "2024-01-30T17:00:00",- meetingEnd: "2024-01-30T18:00:00",+ title: "Ship-it at f.inc (accountability group)",+ startTime: "2024-01-30T17:00:00",+ endTime: "2024-01-30T18:00:00",agenda: "Participants share one liner about startup, progress in the last week, the biggest problem, next week plan",- aiSummary: null,+ analysis: null,participants_invited: ["Hubert Thieblot", 'all portfolio companies in dev tools', "louis beaumont", "matt diakonov"],recurrence: "weekly on thursday",- aiName: null,participants: null,- selectedDevices: new Set(),- deviceNames: new Set(),- segments: [],+ chunks: [],+ mergedChunks: [],+ editedMergedChunks: {},+ speakerMappings: {},+ lastProcessedIndex: -1,notes: [],+ deviceNames: new Set(),+ selectedDevices: new Set(),aiPrep: {previousContext: {lastInteraction: "2024-01-23: LinkedIn Agent Demo",@@ -119,22 +123,26 @@ const MOCK_UPCOMING_MEETINGS: Meeting[] = ["emphasize platform capabilities through agent examples"]}- }+ },+ isAiNotesEnabled: true,},{id: "3",- humanName: "English class with Kelly 🇺🇸 🔥 Speaking, Grammar",- meetingStart: "2024-01-30T19:30:00",- meetingEnd: "2024-01-30T19:55:00",+ title: "English class with Kelly 🇺🇸 🔥 Speaking, Grammar",+ startTime: "2024-01-30T19:30:00",+ endTime: "2024-01-30T19:55:00",agenda: "Read outloud to fix pronounciation issues, thick russian accent, grammar mistakes",- aiSummary: null,+ analysis: null,recurrence: "daily",- aiName: null,participants: null,- selectedDevices: new Set(),- deviceNames: new Set(),- segments: [],+ chunks: [],+ mergedChunks: [],+ editedMergedChunks: {},+ speakerMappings: {},+ lastProcessedIndex: -1,notes: [],+ deviceNames: new Set(),+ selectedDevices: new Set(),aiPrep: {previousContext: {lastInteraction: "2024-01-23: LinkedIn Agent Demo",@@ -175,15 +183,16 @@ const MOCK_UPCOMING_MEETINGS: Meeting[] = ["emphasize platform capabilities through agent examples"]}- }+ },+ isAiNotesEnabled: true,},{id: "4",- humanName: "b2b between Matthew Diakonov and Mauricio Matsumoto Dias",- meetingStart: "2024-01-31T10:00:00",- meetingEnd: "2024-01-31T10:30:00",+ title: "b2b between Matthew Diakonov and Mauricio Matsumoto Dias",+ startTime: "2024-01-31T10:00:00",+ endTime: "2024-01-31T10:30:00",agenda: "Enterprise deal with the largest ERP system in Brazil - TOTVS, regular meeting to manage progress of POC",- aiSummary: null,+ analysis: null,participants_invited: ["Matthew Diakonov",@@ -196,12 +205,15 @@ const MOCK_UPCOMING_MEETINGS: Meeting[] = [guestCount: 7,confirmedCount: 7,organizer: "Matthew Diakonov",- aiName: null,participants: null,- selectedDevices: new Set(),- deviceNames: new Set(),- segments: [],+ chunks: [],+ mergedChunks: [],+ editedMergedChunks: {},+ speakerMappings: {},+ lastProcessedIndex: -1,notes: [],+ deviceNames: new Set(),+ selectedDevices: new Set(),aiPrep: {previousContext: {lastInteraction: "2024-01-24: Initial POC planning",@@ -237,22 +249,26 @@ const MOCK_UPCOMING_MEETINGS: Meeting[] = ["prepare specific TOTVS use cases"]}- }+ },+ isAiNotesEnabled: true,},{id: "5",- humanName: "Dentist Stockton",- meetingStart: "2024-01-31T14:30:00",- meetingEnd: "2024-01-31T15:30:00",+ title: "Dentist Stockton",+ startTime: "2024-01-31T14:30:00",+ endTime: "2024-01-31T15:30:00",agenda: "Cleaning teeth - important to keep log of daily dental log and notice any issues early on",- aiSummary: null,+ analysis: null,recurrence: "every half a year",- aiName: null,participants: null,- selectedDevices: new Set(),- deviceNames: new Set(),- segments: [],+ chunks: [],+ mergedChunks: [],+ editedMergedChunks: {},+ speakerMappings: {},+ lastProcessedIndex: -1,notes: [],+ deviceNames: new Set(),+ selectedDevices: new Set(),aiPrep: {previousContext: {lastInteraction: "2024-01-23: LinkedIn Agent Demo",@@ -293,7 +309,8 @@ const MOCK_UPCOMING_MEETINGS: Meeting[] = ["emphasize platform capabilities through agent examples"]}- }+ },+ isAiNotesEnabled: true,}]@@ -332,12 +349,12 @@ export function UpcomingMeetings() {<div key={meeting.id} className="relative"><div className="absolute -left-0 z-10 -top-2"><div className="flex items-center gap-1 text-xs text-muted-foreground bg-accent rounded px-1 border border-border/40">- {meeting.humanName?.toLowerCase().includes("recording demo") && (+ {meeting.title?.toLowerCase().includes("recording demo") && (<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />)}- {meeting.humanName?.toLowerCase().includes("recording demo") ?+ {meeting.title?.toLowerCase().includes("recording demo") ?"now" :- `${getUpcomingTime(meeting.meetingStart)[0]} ${getUpcomingTime(meeting.meetingStart)[1]}`}+ `${getUpcomingTime(meeting.startTime)[0]} ${getUpcomingTime(meeting.startTime)[1]}`}</div></div><MeetingCard meeting={meeting} onUpdate={handleUpdate} settings={settings} />diff --git a/pipes/meeting/src/components/meeting-history/meeting-history.tsx b/pipes/meeting/src/components/meeting-history/meeting-history.tsxindex 5d257e39c..e33dd7723 100644--- a/pipes/meeting/src/components/meeting-history/meeting-history.tsx+++ b/pipes/meeting/src/components/meeting-history/meeting-history.tsx@@ -1,111 +1,166 @@"use client"-import { useState, useEffect, useCallback } from "react"-import { Meeting } from "./types"-import { useMeetings } from "./hooks/use-meetings"+import { useState, useEffect } from "react"import { MeetingCard } from "./components/meeting-card"import { Button } from "@/components/ui/button"import { Loader2, PlusCircle, Settings as SettingsIcon } from "lucide-react"import { useRouter } from "next/navigation"import { MeetingSettings } from "./components/meeting-settings"-import { UpcomingMeetings } from "./components/mockup-upcoming-meetings"-import { getLiveMeetingData, clearLiveMeetingData } from "@/components/live-transcription/hooks/storage-for-live-meeting"+import {+ LiveMeetingData,+ deleteArchivedMeeting,+ updateArchivedMeeting,+ useMeetingContext,+ getAllMeetings,+} from "@/components/live-transcription/hooks/storage-for-live-meeting"import { useSettings } from "@/lib/hooks/use-settings"+import { MeetingAnalysis } from "@/components/live-transcription/hooks/ai-create-all-notes"+import { handleStartNewMeeting } from "@/components/meeting-history/meeting-utils"+import { toast } from "@/hooks/use-toast"+import { handleLoadMeeting } from "@/components/meeting-history/meeting-utils"export function MeetingHistory() {const [mounted, setMounted] = useState(false)const [showSettings, setShowSettings] = useState(false)const [windowHeight, setWindowHeight] = useState(0)- const [hasLiveMeeting, setHasLiveMeeting] = useState(false)+ const [archivedMeetings, setArchivedMeetings] = useState<LiveMeetingData[]>([])+ const [loading, setLoading] = useState(true)+ const [refreshTrigger, setRefreshTrigger] = useState(0)- const { meetings, loading, error, updateMeetings } = useMeetings()const { settings } = useSettings()const router = useRouter()- const handleResume = useCallback(async () => {- if (!hasLiveMeeting) return-- console.log('resume: attempting navigation to live meeting')+ const handleUpdate = async (id: string, update: {+ aiName?: string;+ aiSummary?: string;+ analysis?: MeetingAnalysis | null;+ }) => {try {- const liveData = await getLiveMeetingData()- console.log('resume: current live meeting state:', {- hasTitle: !!liveData?.title,- notesCount: liveData?.notes?.length,- firstNote: liveData?.notes?.[0]?.text?.slice(0, 50)+ console.log('updating meeting:', {+ id,+ update,+ currentMeetings: archivedMeetings.length,})- await router.push('/meetings/live')- console.log('resume: navigation completed')- } catch (e) {- console.error('resume: navigation failed:', e)- }- }, [hasLiveMeeting, router])-- const handleNewMeeting = useCallback(async () => {- if (hasLiveMeeting) {- console.log('existing meeting detected, prompting user')- const confirmed = window.confirm('You have an existing meeting in progress. Start a new one anyway?')- if (!confirmed) {- console.log('user chose to resume existing meeting')- await handleResume()- return- }- console.log('user chose to start new meeting, clearing existing data')- await clearLiveMeetingData()++ // Handle archived meeting+ await updateArchivedMeeting(id, {+ title: update.aiName,+ analysis: update.analysis+ })++ // Refresh archived meetings list+ const updated = await getAllMeetings()+ setArchivedMeetings(updated.filter(m => m.isArchived))++ } catch (error) {+ console.error('failed to update meeting:', error)}- console.log('starting new meeting')+ }++ const handleLoadArchived = async (meeting: LiveMeetingData) => {+ console.log('loading archived meeting details:', {+ id: meeting.id,+ isArchived: true,+ title: meeting.title,+ startTime: meeting.startTime,+ hasChunks: meeting.chunks?.length,+ hasNotes: meeting.notes?.length,+ hasAnalysis: !!meeting.analysis,+ deviceNames: [...(meeting.deviceNames || [])],+ selectedDevices: [...(meeting.selectedDevices || [])]+ })++ await handleLoadMeeting(meeting)+ }++ const handleDelete = async (meeting: LiveMeetingData) => {try {- await router.push('/meetings/live')- console.log('navigation completed')- } catch (e) {- console.error('navigation failed:', e)+ // Check if user has disabled delete confirmations+ const skipConfirm = localStorage.getItem('skipDeleteConfirm') === 'true'++ if (!skipConfirm) {+ const result = await new Promise<boolean>((resolve) => {+ const checkbox = document.createElement('input')+ checkbox.type = 'checkbox'+ checkbox.id = 'dontAskAgain'++ const message = document.createElement('div')+ message.innerHTML = `+ Are you sure you want to delete this meeting?+ <br/><br/>+ <label style="display: flex; align-items: center; gap: 8px;">+ <input type="checkbox" id="dontAskAgain" />+ <span>don't ask again</span>+ </label>+ `++ const confirmed = window.confirm(message.innerText)+ const dontAskAgain = (document.getElementById('dontAskAgain') as HTMLInputElement)?.checked++ if (dontAskAgain) {+ localStorage.setItem('skipDeleteConfirm', 'true')+ }++ resolve(confirmed)+ })++ if (!result) {+ console.log('meeting deletion cancelled by user')+ return+ }+ }++ console.log('deleting meeting:', {+ title: meeting.title,+ startTime: meeting.startTime+ })+ await deleteArchivedMeeting(meeting.startTime)++ // Refresh the meetings list+ setRefreshTrigger(prev => prev + 1)+ } catch (error) {+ console.error('failed to delete meeting:', error)}- }, [hasLiveMeeting, router, handleResume])+ }- useEffect(() => {- updateHeight()- window.addEventListener('resize', updateHeight)- return () => window.removeEventListener('resize', updateHeight)- }, [])+ const handleNewMeeting = async () => {+ await handleStartNewMeeting()+ }useEffect(() => {- const checkLiveMeeting = async () => {- const liveData = await getLiveMeetingData()- console.log('checking for live meeting:', {- exists: !!liveData,- title: liveData?.title,- notesCount: liveData?.notes?.length,- hasAnalysis: !!liveData?.analysis- })- setHasLiveMeeting(!!liveData)+ const loadMeetings = async () => {+ setLoading(true)+ try {+ const meetings = await getAllMeetings()+ console.log('loaded meetings:', {+ total: meetings.length,+ live: meetings.find(m => !m.isArchived)?.title+ })++ setArchivedMeetings(meetings.filter(m => m.isArchived))+ } catch (error) {+ console.error('failed to load meetings:', error)+ } finally {+ setLoading(false)+ }}- checkLiveMeeting()- }, [])+ loadMeetings()+ }, [refreshTrigger])useEffect(() => {+ const updateHeight = () => {+ const vh = window.innerHeight+ const headerOffset = 32+ setWindowHeight(vh - headerOffset)+ }++ updateHeight()+ window.addEventListener('resize', updateHeight)setMounted(true)- console.log('meeting-history mounted')++ return () => window.removeEventListener('resize', updateHeight)}, [])- const updateHeight = () => {- const vh = window.innerHeight- const headerOffset = 32- console.log('meeting list height:', vh, 'header offset:', headerOffset)- setWindowHeight(vh - headerOffset)- }-- const handleMeetingUpdate = (id: string, update: { aiName?: string; aiSummary?: string }) => {- console.log('handling meeting update:', {- meetingId: id,- update,- currentMeetingsCount: meetings.length- })- const updatedMeetings = meetings.map(meeting => {- return meeting.id === id ? { ...meeting, ...update } : meeting- })- console.log('updated meetings count:', updatedMeetings.length)- updateMeetings(updatedMeetings)- }-if (!mounted) return nullif (showSettings) {@@ -125,7 +180,7 @@ export function MeetingHistory() {<div className="h-4" /><div className="flex items-center justify-between mb-6"><h2 className="text-base font-bold text-muted-foreground uppercase tracking-wider">- meeting and conversation history+ meeting history</h2><div className="flex gap-2"><Button@@ -135,16 +190,6 @@ export function MeetingHistory() {><SettingsIcon className="h-4 w-4" /></Button>- {hasLiveMeeting && (- <Button- onClick={handleResume}- variant="outline"- size="sm"- >- <PlusCircle className="h-4 w-4 mr-2" />- resume meeting- </Button>- )}<ButtononClick={handleNewMeeting}variant="default"@@ -160,42 +205,32 @@ export function MeetingHistory() {className="w-full overflow-auto"style={{ height: windowHeight ? `${windowHeight}px` : '100vh' }}>- {error ? (- <div className="flex flex-col items-center justify-center h-full gap-4">- <p className="text-destructive">failed to load meetings</p>- </div>- ) : (- <div className="space-y-6">- {/* <div className="bg-accent/50 rounded-lg">- <h3 className="text-xl font-semibold mb-6 text-muted-foreground pl-4">upcoming</h3>- <UpcomingMeetings />- </div> */}-- <div>- {Object.entries(groupMeetingsByDate(meetings)).map(([date, dateMeetings]) => (- <div key={date}>- <h3 className="text-xl font-semibold mb-3 text-muted-foreground">{date}</h3>- {dateMeetings.map((meeting) => (- <MeetingCard- key={meeting.id}- meeting={meeting}- settings={settings}- onUpdate={handleMeetingUpdate}- />- ))}- </div>+ <div className="space-y-6">+ {/* Show archived meetings grouped by date */}+ {Object.entries(groupMeetingsByDate(archivedMeetings)).map(([date, meetings]) => (+ <div key={date}>+ <h3 className="text-xl font-semibold mb-3 text-muted-foreground">{date}</h3>+ {meetings.map((meeting) => (+ <MeetingCard+ key={meeting.id}+ meeting={meeting}+ settings={settings}+ onDelete={() => handleDelete(meeting)}+ onUpdate={handleUpdate}+ onLoadArchived={() => handleLoadArchived(meeting)}+ />))}</div>- </div>- )}+ ))}+ </div></div></div>)}-function groupMeetingsByDate(meetings: Meeting[]): Record<string, Meeting[]> {+function groupMeetingsByDate(meetings: LiveMeetingData[]): Record<string, LiveMeetingData[]> {return meetings.reduce((groups, meeting) => {- const date = new Date(meeting.meetingStart).toLocaleDateString([], {+ const date = new Date(meeting.startTime).toLocaleDateString([], {weekday: 'long',month: 'long',day: 'numeric'@@ -206,5 +241,5 @@ function groupMeetingsByDate(meetings: Meeting[]): Record<string, Meeting[]> {}groups[date].push(meeting)return groups- }, {} as Record<string, Meeting[]>)+ }, {} as Record<string, LiveMeetingData[]>)}\ No newline at end of filediff --git a/pipes/meeting/src/components/meeting-history/meeting-utils.ts b/pipes/meeting/src/components/meeting-history/meeting-utils.tsnew file mode 100644index 000000000..04b3fa429--- /dev/null+++ b/pipes/meeting/src/components/meeting-history/meeting-utils.ts@@ -0,0 +1,93 @@+import { toast } from "@/hooks/use-toast"+import { archiveLiveMeeting } from "@/components/live-transcription/hooks/storage-for-live-meeting"+import type { LiveMeetingData } from "@/components/live-transcription/hooks/storage-for-live-meeting"+import { meetingStore } from "@/components/live-transcription/hooks/storage-for-live-meeting"++export async function handleStartNewMeeting(currentData?: LiveMeetingData | null) {+ console.log('starting new meeting:', {+ hasCurrentData: !!currentData,+ currentTitle: currentData?.title,+ isArchived: currentData?.isArchived+ })++ try {+ // 1. Archive current meeting if exists and not archived+ if (currentData && !currentData.isArchived) {+ const archived = await archiveLiveMeeting()+ if (!archived) {+ throw new Error("failed to archive current meeting")+ }+ }++ // 2. Create new meeting data+ const startTime = new Date().toISOString()+ const newData: LiveMeetingData = {+ id: `live-meeting-${startTime}`,+ chunks: [],+ mergedChunks: [],+ editedMergedChunks: {},+ speakerMappings: {},+ lastProcessedIndex: -1,+ startTime,+ title: null,+ notes: [],+ analysis: null,+ deviceNames: new Set<string>(),+ selectedDevices: new Set<string>(),+ isArchived: false,+ isAiNotesEnabled: true+ }++ // 3. Store new meeting and wait for confirmation+ await meetingStore.setItem(newData.id, newData)++ // 4. Use window.location for a full page reload to ensure clean state+ window.location.href = '/meetings/live'+ return true++ } catch (error) {+ console.error('failed to start new meeting:', error)+ toast({+ title: "error",+ description: "failed to start new meeting. please try again",+ variant: "destructive",+ })+ return false+ }+}++export async function handleLoadMeeting(meeting: LiveMeetingData) {+ console.log('loading meeting:', {+ id: meeting.id,+ title: meeting.title,+ isArchived: meeting.isArchived+ })++ try {+ // 1. Archive current meeting if exists+ const archived = await archiveLiveMeeting()+ if (!archived) {+ console.log('no active meeting to archive')+ }++ // 2. Unarchive and update the target meeting+ const updatedMeeting = {+ ...meeting,+ isArchived: false+ }+ await meetingStore.setItem(meeting.id, updatedMeeting)++ // 3. Force a full page reload to ensure clean state+ window.location.href = '/meetings/live?from=archive'+ return true++ } catch (error) {+ console.error('failed to load meeting:', error)+ toast({+ title: "error",+ description: "failed to load meeting. please try again",+ variant: "destructive",+ })+ return false+ }+}\ No newline at end of filediff --git a/pipes/meeting/src/components/providers/posthog-provider.tsx b/pipes/meeting/src/components/providers/posthog-provider.tsxindex 7cce59179..96c44d234 100644--- a/pipes/meeting/src/components/providers/posthog-provider.tsx+++ b/pipes/meeting/src/components/providers/posthog-provider.tsx@@ -8,20 +8,20 @@ import { Suspense } from 'react'// Separate component for page view tracking to handle suspensefunction PageViewTracker() {- const pathname = usePathname()- const searchParams = useSearchParams()-- useEffect(() => {- if (pathname) {- let url = window.origin + pathname- if (searchParams.toString()) {- url = url + `?${searchParams.toString()}`- }- posthog.capture('$pageview', {- $current_url: url,- })- }- }, [pathname, searchParams])+ // const pathname = usePathname()+ // const searchParams = useSearchParams()++ // useEffect(() => {+ // if (pathname) {+ // let url = window.origin + pathname+ // if (searchParams.toString()) {+ // url = url + `?${searchParams.toString()}`+ // }+ // posthog.capture('$pageview', {+ // $current_url: url,+ // })+ // }+ // }, [pathname, searchParams])return null}@@ -31,31 +31,34 @@ export default function PostHogProvider({}: {children: React.ReactNode}) {- useEffect(() => {- if (typeof window !== 'undefined') {- const posthogKey = process.env.NEXT_PUBLIC_POSTHOG_API_KEY- if (!posthogKey) {- console.warn('posthog: missing NEXT_PUBLIC_POSTHOG_API_KEY')- return- }-- posthog.init(posthogKey, {- api_host: 'https://app.posthog.com',- capture_pageview: false,- bootstrap: {- distinctID: process.env.NODE_ENV,- },- debug: false,- })- }- }, [])-- return (- <Provider client={posthog}>- <Suspense>- <PageViewTracker />- </Suspense>- {children}- </Provider>- )+ // useEffect(() => {+ // if (typeof window !== 'undefined') {+ // const posthogKey = process.env.NEXT_PUBLIC_POSTHOG_API_KEY+ // if (!posthogKey) {+ // console.warn('posthog: missing NEXT_PUBLIC_POSTHOG_API_KEY')+ // return+ // }++ // posthog.init(posthogKey, {+ // api_host: 'https://app.posthog.com',+ // capture_pageview: false,+ // bootstrap: {+ // distinctID: process.env.NODE_ENV,+ // },+ // debug: false,+ // })+ // }+ // }, [])++ // For now, just render children without PostHog tracking+ return children++ // return (+ // <Provider client={posthog}>+ // <Suspense>+ // <PageViewTracker />+ // </Suspense>+ // {children}+ // </Provider>+ // )}\ No newline at end of filediff --git a/pipes/meeting/src/components/providers/root-provider.tsx b/pipes/meeting/src/components/providers/root-provider.tsxnew file mode 100644index 000000000..ed10e0e86--- /dev/null+++ b/pipes/meeting/src/components/providers/root-provider.tsx@@ -0,0 +1,17 @@+'use client'++import { MeetingProvider } from "@/components/live-transcription/hooks/storage-for-live-meeting"+import { SettingsProvider } from "@/lib/hooks/use-settings"+import PostHogProvider from "./posthog-provider"++export function RootProvider({ children }: { children: React.ReactNode }) {+ return (+ <PostHogProvider>+ <SettingsProvider>+ <MeetingProvider>+ {children}+ </MeetingProvider>+ </SettingsProvider>+ </PostHogProvider>+ )+}\ No newline at end of filediff --git a/pipes/meeting/src/components/status-live-transcription.tsx b/pipes/meeting/src/components/status-live-transcription.tsxnew file mode 100644index 000000000..e3795aa06--- /dev/null+++ b/pipes/meeting/src/components/status-live-transcription.tsx@@ -0,0 +1,50 @@+import React, { useRef, useEffect, useState, useCallback } from 'react'++const useBrowserTranscriptionStream = () => {+ const ws = useRef<WebSocket | null>(null)+ const [isConnected, setIsConnected] = useState(false)++ useEffect(() => {+ const socket = new WebSocket('ws://localhost:8080')+ ws.current = socket++ socket.onopen = () => {+ console.log('websocket connected')+ setIsConnected(true)+ }++ socket.onerror = (error) => {+ console.error('websocket error:', error)+ setIsConnected(false)+ }++ socket.onclose = () => {+ console.log('websocket closed')+ setIsConnected(false)+ }++ return () => {+ socket.close()+ ws.current = null+ }+ }, [])++ const stopTranscriptionBrowser = useCallback(() => {+ if (!ws.current || !isConnected) {+ console.log('websocket not ready, skipping stop command')+ return+ }++ try {+ ws.current.send(JSON.stringify({ type: 'stop' }))+ } catch (err) {+ console.error('failed to send stop command:', err)+ }+ }, [isConnected])++ return {+ stopTranscriptionBrowser,+ }+}++export default useBrowserTranscriptionStream\ No newline at end of filediff --git a/pipes/meeting/src/lib/hooks/use-settings.tsx b/pipes/meeting/src/lib/hooks/use-settings.tsxindex e1e7f31b8..98ce37a31 100644--- a/pipes/meeting/src/lib/hooks/use-settings.tsx+++ b/pipes/meeting/src/lib/hooks/use-settings.tsx@@ -3,6 +3,7 @@import { useState, useEffect, createContext, useContext, ReactNode } from "react";import type { Settings } from "@screenpipe/browser";import { getDefaultSettings } from "@screenpipe/browser";+import { isEqual } from 'lodash'interface SettingsContextType {settings: Settings;@@ -42,12 +43,12 @@ export function SettingsProvider({ children }: { children: ReactNode }) {const response = await fetch("/api/settings");if (!response.ok) {console.log("using default settings (web mode)")- setSettings(initialSettings); // Use initialSettings instead of defaultSettings- return;+ return; // Don't update if using defaults}const data = await response.json();- // Preserve our hardcoded token when merging settings- setSettings({++ // Only update settings if they've actually changed+ const newSettings = {...initialSettings,...data,aiProviderType: "screenpipe-cloud",@@ -61,10 +62,12 @@ export function SettingsProvider({ children }: { children: ReactNode }) {},aiUrl: initialSettings.aiUrl,aiModel: initialSettings.aiModel- });+ };++ // Only update if settings actually changed+ setSettings(prev => isEqual(prev, newSettings) ? prev : newSettings);} catch (err) {console.log("failed to load settings, using defaults:", err)- setSettings(initialSettings); // Use initialSettings instead of defaultSettings} finally {setLoading(false);}diff --git a/pipes/meeting/src/lib/storage/chat-storage.ts b/pipes/meeting/src/lib/storage/chat-storage.tsnew file mode 100644index 000000000..6330994bf--- /dev/null+++ b/pipes/meeting/src/lib/storage/chat-storage.ts@@ -0,0 +1,110 @@+import localforage from "localforage"++// Only initialize localforage on the client side+const chatStore = typeof window !== 'undefined'+ ? localforage.createInstance({+ name: "chat-sessions",+ storeName: "chats"+ })+ : null++export interface ChatSession {+ id: string+ threadId: string+ messages: Array<{+ id: string+ content: string+ fromUser: boolean+ timestamp: string+ }>+ startTime: string+ endTime?: string+ isArchived?: boolean+}++// In-memory fallback for server-side+const serverSideStore = new Map<string, ChatSession>()++export async function createChatSession(sessionId: string, threadId: string): Promise<ChatSession> {+ const session: ChatSession = {+ id: sessionId,+ threadId,+ messages: [],+ startTime: new Date().toISOString(),+ }++ if (chatStore) {+ await chatStore.setItem(sessionId, session)+ } else {+ serverSideStore.set(sessionId, session)+ }++ console.log('created new chat session:', { sessionId, threadId })+ return session+}++export async function getChatSession(sessionId: string): Promise<ChatSession | null> {+ try {+ if (chatStore) {+ return await chatStore.getItem<ChatSession>(sessionId)+ }+ return serverSideStore.get(sessionId) || null+ } catch (error) {+ console.error('failed to get chat session:', error)+ return null+ }+}++export async function updateChatSession(sessionId: string, update: Partial<ChatSession>): Promise<ChatSession | null> {+ try {+ const session = await getChatSession(sessionId)+ if (!session) return null++ const updated = {+ ...session,+ ...update,+ id: session.id, // Never allow id change+ }++ if (chatStore) {+ await chatStore.setItem(sessionId, updated)+ } else {+ serverSideStore.set(sessionId, updated)+ }++ return updated+ } catch (error) {+ console.error('failed to update chat session:', error)+ return null+ }+}++export async function archiveChatSession(sessionId: string): Promise<ChatSession | null> {+ return updateChatSession(sessionId, {+ isArchived: true,+ endTime: new Date().toISOString()+ })+}++export async function getAllChatSessions(): Promise<ChatSession[]> {+ try {+ const sessions: ChatSession[] = []+ if (chatStore) {+ await chatStore.iterate<ChatSession, void>((value) => {+ sessions.push(value)+ })+ } else {+ serverSideStore.forEach((value) => {+ sessions.push(value)+ })+ }++ // Sort by start time, newest first+ return sessions.sort((a, b) =>+ new Date(b.startTime).getTime() - new Date(a.startTime).getTime()+ )+ } catch (error) {+ console.error('failed to get all chat sessions:', error)+ return []+ }+}\ No newline at end of file