Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat: Dynamic OAuth redirect URIs, onboarding wizard, Windows compatibility
trohitg732a946756ee
diff --git a/.env.template b/.env.templateindex b6e46565..31877120 100644--- a/.env.template+++ b/.env.template@@ -1,6 +1,7 @@# Service Ports (used by start.js, vite, and docker-compose)VITE_CLIENT_PORT=3000PYTHON_BACKEND_PORT=3010+NODEJS_EXECUTOR_PORT=3020WHATSAPP_RPC_PORT=9400REDIS_PORT=6379@@ -77,17 +78,10 @@ WS_LOGGING_ENABLED=trueWEBSOCKET_URL=wss://relay.zeenie.xyz/wsWEBSOCKET_API_KEY=-# WhatsApp Service URL-WHATSAPP_SERVICE_URL=http://localhost:5000-# AI Proxy Configuration (Ollama-style proxy for Claude Code CLI)# Default port for AI proxy servers (e.g., Ollama, Claude Code CLI proxy)AI_PROXY_DEFAULT_PORT=11434-# OAuth Redirect URIs-GMAIL_REDIRECT_URI=http://localhost:3010/api/gmail/callback-TWITTER_REDIRECT_URI=http://localhost:3010/api/twitter/callback-# External API Keys (managed through UI, these are optional defaults)OPENAI_API_KEY=GOOGLE_MAPS_API_KEY=diff --git a/.github/workflows/test-install.yml b/.github/workflows/test-install.ymlindex ffeda351..5370581f 100644--- a/.github/workflows/test-install.yml+++ b/.github/workflows/test-install.yml@@ -57,7 +57,7 @@ jobs:if: runner.os != 'Windows'shell: bashrun: |- machinaos start &+ machina start &PID=$!for i in {1..15}; do@@ -69,10 +69,10 @@ jobs:doneif kill -0 $PID 2>/dev/null; then- echo "machinaos start: OK"- machinaos stop || kill $PID 2>/dev/null || true+ echo "machina start: OK"+ machina stop || kill $PID 2>/dev/null || trueelse- echo "machinaos start: FAILED"+ echo "machina start: FAILED"exit 1fi@@ -80,7 +80,7 @@ jobs:if: runner.os == 'Windows'shell: pwshrun: |- $job = Start-Job -ScriptBlock { machinaos start }+ $job = Start-Job -ScriptBlock { machina start }Start-Sleep -Seconds 15try {@@ -91,11 +91,11 @@ jobs:}if ($job.State -eq "Running") {- Write-Host "machinaos start: OK"+ Write-Host "machina start: OK"Stop-Job $jobRemove-Job $job} else {- Write-Host "machinaos start: FAILED"+ Write-Host "machina start: FAILED"Receive-Job $jobexit 1}diff --git a/CLAUDE.md b/CLAUDE.mdindex 438b734f..583f82ca 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -27,6 +27,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Server Documentation](./docs-internal/server-readme.md)** | Python backend architecture and API documentation || **[Skill Creation Guide](./server/skills/GUIDE.md)** | How to create new skills (folder structure, SKILL.md format, metadata, supporting files) || **[New Service Integration](./docs-internal/new_service_integration.md)** | Complete guide for integrating external services (OAuth, database, handlers, nodes, AI tools) - use Google Workspace as reference |+| **[Onboarding Service](./docs-internal/onboarding.md)** | First-launch welcome wizard with 5 steps, database persistence, and replay from Settings || **[Polyglot Server](../polyglot-server/ARCHITECTURE.md)** | Plugin registry microservice with MCP gateway (optional integration) |## Design Principles & Standards@@ -923,6 +924,7 @@ Authentication is handled via OAuth 2.0 PKCE flow in the Credentials Modal:| File | Description ||------|-------------|| `server/services/twitter_oauth.py` | OAuth 2.0 PKCE flow implementation |+| `server/services/oauth_utils.py` | Runtime OAuth redirect URI derivation from request context || `server/routers/twitter.py` | OAuth callback endpoint, token exchange || `server/services/handlers/twitter.py` | Node handlers using XDK SDK || `client/src/nodeDefinitions/twitterNodes.ts` | 4 node definitions |@@ -965,7 +967,7 @@ client.users.get_followers(user_id, max_results=100, user_fields=["created_at"])```bashTWITTER_CLIENT_ID=your_client_idTWITTER_CLIENT_SECRET=your_client_secret-TWITTER_REDIRECT_URI=http://localhost:3010/api/twitter/callback+# TWITTER_REDIRECT_URI is derived at runtime from request context (no env var needed)```### Google Workspace Nodes (7 nodes)@@ -1021,9 +1023,10 @@ GOOGLE_WORKSPACE_SCOPES = [**Key Files:**| File | Description ||------|-------------|-| `server/services/google_oauth.py` | OAuth 2.0 flow (authorization URL, token exchange) |+| `server/services/google_oauth.py` | OAuth 2.0 flow (authorization URL, token exchange, `get_callback_paths()`) |+| `server/services/oauth_utils.py` | Runtime OAuth redirect URI derivation from request context || `server/services/handlers/google_auth.py` | Shared credential helper (`get_google_credentials()`) used by all 6 handlers |-| `server/config/google_apis.json` | API endpoints and scopes config |+| `server/config/google_apis.json` | API endpoints, scopes, and OAuth callback paths || `server/routers/google.py` | OAuth callback and status endpoints || `server/services/handlers/gmail.py` | Gmail handlers + `handle_gmail_receive` polling trigger || `server/services/handlers/calendar.py` | Calendar handlers |@@ -1064,11 +1067,8 @@ Access and refresh tokens are stored via OAuth system (after Google login):| `tasks-skill` | `tasks_create`, `tasks_list`, `tasks_complete` | Manage Google Tasks || `contacts-skill` | `contacts_create`, `contacts_list`, `contacts_search` | Manage contacts |-**Environment Variables:**-```bash-# OAuth redirect (optional, defaults to localhost:3010)-GOOGLE_REDIRECT_URI=http://localhost:3010/api/google/callback-```+**OAuth Redirect URIs:**+OAuth redirect URIs are derived at runtime from the request/WebSocket context via `server/services/oauth_utils.py`. No environment variable needed -- works automatically in dev (`http://localhost:3010`) and production (`https://domain.com`).**Google API Pricing:** All Google Workspace APIs are free with rate limits. See `server/config/pricing.json` for configured limits.@@ -1273,12 +1273,12 @@ python -m services.temporal.worker### CLI Commands (npx or global install)```bash-npx machinaos start # Start all services-npx machinaos stop # Stop all services-npx machinaos build # Build for production-npx machinaos clean # Clean build artifacts-npx machinaos docker:up # Start with Docker-npx machinaos help # Show all commands+npx machina start # Start all services+npx machina stop # Stop all services+npx machina build # Build for production+npx machina clean # Clean build artifacts+npx machina docker:up # Start with Docker+npx machina help # Show all commands```### npm Scripts@@ -1344,6 +1344,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.✅ **Authentication System**: n8n-style JWT authentication with HttpOnly cookies, single-owner and multi-user modes✅ **Cache System**: n8n-pattern cache with Redis (production) / SQLite (local dev) / Memory fallback hierarchy✅ **AI Thinking/Reasoning**: Extended thinking for Claude, Gemini 2.5/Flash Thinking, Groq Qwen3/QwQ with output available in Input Data & Variables for downstream nodes+✅ **Onboarding Service**: 5-step welcome wizard with Ant Design UI, database persistence, skip/resume/replay support## Key Features@@ -2805,7 +2806,10 @@ Example workflows use the same format as UI exports:}],"edges": [],- "version": "0.0.10"+ "nodeParameters": {+ "start_1": { "someParam": "value" }+ },+ "version": "0.0.35"}```@@ -2817,7 +2821,8 @@ Example workflows use the same format as UI exports:| `description` | Optional description || `nodes` | Array of node objects with id, type, position, data || `edges` | Array of edge connections between nodes |-| `version` | App version (e.g., "0.0.10") |+| `nodeParameters` | Optional map of node_id to parameter objects (saved to DB on import) |+| `version` | App version (e.g., "0.0.35") |### Key Files| File | Description |@@ -2873,6 +2878,50 @@ if "examples_loaded" not in columns:))```+## Onboarding Service++### Overview+Multi-step welcome wizard that appears after first launch, guiding users through platform capabilities. Database-backed, skippable, resumable, and replayable from Settings.++See **[Onboarding Service](./docs-internal/onboarding.md)** for full documentation.++### Architecture+- **5-step wizard** using existing `Modal` component + Ant Design `Steps`, `Card`, `Button`, `Typography`, `Tag`+- **Database persistence** via `UserSettings.onboarding_completed` + `UserSettings.onboarding_step`+- **No new WebSocket handlers** -- reuses `get_user_settings` / `save_user_settings`+- **Existing users** auto-skip via migration (`examples_loaded=1` -> `onboarding_completed=1`)++### Steps++| Step | Component | Title | Purpose |+|------|-----------|-------|---------|+| 0 | `WelcomeStep` | Welcome to MachinaOs | Platform intro + feature highlights |+| 1 | `ConceptsStep` | Key Concepts | Nodes, Edges, Agents, Skills, Normal/Dev Mode |+| 2 | `ApiKeyStep` | API Key Setup | Provider list + "Open Credentials" button |+| 3 | `CanvasStep` | Canvas Tour | Visual UI layout diagram + keyboard shortcuts |+| 4 | `GetStartedStep` | Get Started | Example workflows, quick recipe, tips |++### Key Files+| File | Description |+|------|-------------|+| `client/src/hooks/useOnboarding.ts` | State hook with WebSocket persistence |+| `client/src/components/onboarding/OnboardingWizard.tsx` | Main wizard with Ant Design Steps |+| `client/src/components/onboarding/steps/*.tsx` | 5 step components using antd + @ant-design/icons |+| `client/src/Dashboard.tsx` | Renders wizard + passes `reopenTrigger` |+| `client/src/components/ui/SettingsPanel.tsx` | "Replay Welcome Guide" button in Help section |+| `server/models/database.py` | `UserSettings.onboarding_completed`, `onboarding_step` |+| `server/core/database.py` | Migration + CRUD for onboarding fields |++### Replay from Settings+- SettingsPanel has a "Replay Welcome Guide" button in the Help section+- Clicking it: closes Settings, increments `onboardingReopenTrigger` in Dashboard+- `useOnboarding` detects trigger change, resets state, reopens wizard from step 0++### Adding New Steps+1. Create `client/src/components/onboarding/steps/NewStep.tsx` using Ant Design components+2. Import in `OnboardingWizard.tsx`, add to `renderStep()` switch and `stepItems` array+3. Update `TOTAL_STEPS` in `useOnboarding.ts`+## AI Chat Model Development Guide### Adding New AI Providers@@ -4860,8 +4909,9 @@ This function:- QR codes generated as base64 PNG in memory (no file I/O, no `data/qr` directory)- Source: https://github.com/trohitg/whatsapp-rpc- **Node Data Architecture**: `node.data` only stores `label` (display name). All parameters are stored in the database via `save_node_parameters` WebSocket handler. This prevents parameter bloat in workflow JSON exports and keeps React Flow state lightweight. `useDragAndDrop.ts` saves default parameters to DB on drop, not to `node.data`.-- **Workflow Export Sanitization**: `exportWorkflow()` in `useWorkflow.ts` strips transient fields (`selected`, `dragging`, `width`, `height`, `measured`, `positionAbsolute`) from nodes and edges before export. Only `id`, `type`, `position`, `data.label` are included per node.+- **Workflow Export/Import with Parameters**: Exported workflow JSON includes a `nodeParameters` field containing all node configuration (provider, model, prompt, skillsConfig, etc.) fetched from the database at export time. On import, embedded `nodeParameters` are saved back to the database. `sanitizeNodes()` in `workflowExport.ts` still strips `node.data` to UI-only fields (`label`, `disabled`, `condition`). A `parameterSanitizer.ts` utility exists for credential stripping but is currently disabled (pass-through). Old exports without `nodeParameters` import cleanly (backward compatible). Key files: `client/src/utils/workflowExport.ts`, `client/src/utils/parameterSanitizer.ts`, `client/src/Dashboard.tsx` (export/import handlers), `server/services/example_loader.py`.- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB is source of truth for skill instructions (seeded from SKILL.md on first load). Icon resolution: node definition (SVG) > SKILL.md metadata (emoji) > fallback. Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor.-- **Example Workflows**: Auto-load example workflows from `workflows/` folder on first use. Uses `UserSettings.examples_loaded` flag to track import status. Supports anonymous users (`user_id="default"`). Reuses existing `database.save_workflow()` for import. See "Example Workflows" section for details.+- **Example Workflows**: Auto-load example workflows from `workflows/` folder on first use. Uses `UserSettings.examples_loaded` flag to track import status. Supports anonymous users (`user_id="default"`). Reuses existing `database.save_workflow()` for import. Embedded `nodeParameters` in example JSON files are saved to the database on import. See "Example Workflows" section for details.+- **Onboarding Service**: 5-step welcome wizard (Welcome, Concepts, API Keys, Canvas Tour, Get Started) using Ant Design Steps/Card/Button/Typography. Database-backed via `UserSettings.onboarding_completed` + `onboarding_step`. Existing users auto-skip (migration marks `examples_loaded=1` as completed). Replayable from Settings "Help" section. No new WebSocket handlers needed. See [Onboarding Service](./docs-internal/onboarding.md) for details.- **Node.js Code Executor**: Persistent Node.js server (Express + tsx) at port 3020 for JavaScript/TypeScript execution, replacing subprocess spawning per execution. Handlers in `server/services/handlers/code.py` call `NodeJSClient` which makes HTTP requests to the Node.js server. All config via environment variables (`NODEJS_EXECUTOR_URL`, `NODEJS_EXECUTOR_PORT`, etc.).- never use emojis in prints\ No newline at end of filediff --git a/README.md b/README.mdindex 11442512..c2b3d8a7 100644--- a/README.md+++ b/README.md@@ -25,7 +25,7 @@ Mashup of N8N + Openclaw but with better visibility of what it's doing and also```bashnpm install -g machinaos-machinaos start+machina start```Open http://localhost:3000@@ -93,7 +93,7 @@ Click **Credentials** in the toolbar to add your API keys for AI providers, Goog## Documentation-Full docs: https://docs.machinaos.dev+Full docs: https://docs.zeenie.xyz/## Communitydiff --git a/bin/cli.js b/bin/cli.jsindex 8d00715f..8c71a918 100755--- a/bin/cli.js+++ b/bin/cli.js@@ -9,7 +9,8 @@ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');const PKG = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf-8'));const COMMANDS = {- start: 'Start the development server',+ start: 'Start in production mode',+ dev: 'Start development server (hot-reload)',stop: 'Stop all running services',build: 'Build the project for production',clean: 'Clean build artifacts',@@ -25,17 +26,24 @@ function printHelp() {console.log(`MachinaOS - Workflow Automation Platform-Usage: machinaos <command>+Usage: machina <command> [flags]Commands:${Object.entries(COMMANDS).map(([cmd, desc]) => ` ${cmd.padEnd(14)} ${desc}`).join('\n')}+Flags:+ --verbose, -v Show full service logs (start)+ --skip-whatsapp Skip WhatsApp service (start, dev)+ --daemon Use gunicorn backend (dev)+Examples:- machinaos start # Start development server- machinaos build # Build for production- machinaos docker:up # Start with Docker+ machina start # Production server (clean output)+ machina start -v # Production with full logs+ machina dev # Development with hot-reload+ machina build # Build for production+ machina docker:up # Start with Docker-Documentation: https://github.com/trohitg/MachinaOS+Documentation: https://docs.zeenie.xyz/`);}@@ -100,8 +108,10 @@ function checkDeps() {}}-function run(script) {- const child = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['run', script], {+function run(script, extraArgs = []) {+ const npmArgs = ['run', script];+ if (extraArgs.length) npmArgs.push('--', ...extraArgs);+ const child = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', npmArgs, {cwd: ROOT,stdio: 'inherit',shell: true,@@ -118,10 +128,10 @@ const cmd = process.argv[2] || 'help';if (cmd === 'help' || cmd === '--help' || cmd === '-h') {printHelp();} else if (cmd === 'version' || cmd === '--version' || cmd === '-v') {- console.log(`machinaos v${PKG.version}`);-} else if (cmd === 'start' || cmd === 'build') {+ console.log(`machina v${PKG.version}`);+} else if (cmd === 'start' || cmd === 'dev' || cmd === 'build') {checkDeps();- run(cmd);+ run(cmd, process.argv.slice(3));} else if (COMMANDS[cmd]) {run(cmd);} else {diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 9564201a..1697aabf 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -44,6 +44,7 @@ import WorkflowSidebar from './components/ui/WorkflowSidebar';import SettingsPanel, { WorkflowSettings, defaultSettings } from './components/ui/SettingsPanel';import AIResultModal from './components/ui/AIResultModal';import CredentialsModal from './components/CredentialsModal';+import OnboardingWizard from './components/onboarding/OnboardingWizard';import ErrorBoundary from './components/ui/ErrorBoundary';import ConsolePanel from './components/ui/ConsolePanel';import { useAppTheme } from './hooks/useAppTheme';@@ -365,6 +366,7 @@ const DashboardContent: React.FC = () => {});const [settingsOpen, setSettingsOpen] = React.useState(false);const [credentialsOpen, setCredentialsOpen] = React.useState(false);+ const [onboardingReopenTrigger, setOnboardingReopenTrigger] = React.useState(0);// Console panel visibility from store (database-backed)const consolePanelVisible = useAppStore((state) => state.consolePanelVisible);@@ -1267,6 +1269,10 @@ const DashboardContent: React.FC = () => {onClose={() => setSettingsOpen(false)}settings={settings}onSettingsChange={setSettings}+ onReplayOnboarding={() => {+ setSettingsOpen(false);+ setOnboardingReopenTrigger(prev => prev + 1);+ }}/>{/* Credentials Modal */}@@ -1275,6 +1281,12 @@ const DashboardContent: React.FC = () => {onClose={() => setCredentialsOpen(false)}/>+ {/* Onboarding Wizard */}+ <OnboardingWizard+ onOpenCredentials={() => setCredentialsOpen(true)}+ reopenTrigger={onboardingReopenTrigger}+ />+{/* Node Context Menu (right-click) */}{contextMenu && (<NodeContextMenudiff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsxindex 501760ba..52df6e25 100644--- a/client/src/components/AIAgentNode.tsx+++ b/client/src/components/AIAgentNode.tsx@@ -374,9 +374,7 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectasetConfigValid(validation.valid);setConfigErrors(validation.errors);- if (!validation.valid) {- console.warn(`${config.title} ${id} configuration issues:`, validation.errors);- }+ // Configuration issues are expected before user fills in parameters - no need to log} catch (error) {console.error('Configuration validation error:', error);setConfigValid(false);diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsxindex 95aebabd..ca6e9eef 100644--- a/client/src/components/CredentialsModal.tsx+++ b/client/src/components/CredentialsModal.tsx@@ -19,7 +19,7 @@ import QRCodeDisplay from './ui/QRCodeDisplay';import ApiKeyInput from './ui/ApiKeyInput';import { useApiKeys, ProviderDefaults, ProviderUsageSummary, APIUsageSummary } from '../hooks/useApiKeys';import { useAppTheme } from '../hooks/useAppTheme';-import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useGoogleStatus, useTelegramStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';+import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useGoogleStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';import { useWhatsApp } from '../hooks/useWhatsApp';import {OpenAIIcon, ClaudeIcon, GeminiIcon, GroqIcon, OpenRouterIcon, CerebrasIcon,diff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsxindex 245c1647..2c1be1e4 100644--- a/client/src/components/SquareNode.tsx+++ b/client/src/components/SquareNode.tsx@@ -197,9 +197,7 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectabconst hasRequiredParams = data && Object.keys(data).length > 0;setIsConfigured(hasRequiredParams && !!apiKey);- if (!apiKey && provider) {- console.warn(`[SquareNode] ${definition?.displayName} ${id}: No API key configured for ${provider}`);- }+ // Missing API key is expected before user configures credentials - no need to log} catch (error) {console.error('Configuration check error:', error);setHasApiKey(false);diff --git a/client/src/components/onboarding/OnboardingWizard.tsx b/client/src/components/onboarding/OnboardingWizard.tsxnew file mode 100644index 00000000..1e08cd91--- /dev/null+++ b/client/src/components/onboarding/OnboardingWizard.tsx@@ -0,0 +1,145 @@+import React from 'react';+import { Steps, Button, Space } from 'antd';+import { ArrowLeftOutlined, ArrowRightOutlined, CheckOutlined } from '@ant-design/icons';+import Modal from '../ui/Modal';+import { useOnboarding } from '../../hooks/useOnboarding';+import { useAppTheme } from '../../hooks/useAppTheme';+import WelcomeStep from './steps/WelcomeStep';+import ConceptsStep from './steps/ConceptsStep';+import ApiKeyStep from './steps/ApiKeyStep';+import CanvasStep from './steps/CanvasStep';+import GetStartedStep from './steps/GetStartedStep';++interface OnboardingWizardProps {+ onOpenCredentials: () => void;+ reopenTrigger?: number;+}++const stepItems = [+ { title: 'Welcome' },+ { title: 'Concepts' },+ { title: 'API Keys' },+ { title: 'Canvas' },+ { title: 'Get Started' },+];++const OnboardingWizard: React.FC<OnboardingWizardProps> = ({ onOpenCredentials, reopenTrigger }) => {+ const theme = useAppTheme();+ const {+ isVisible,+ currentStep,+ isLoading,+ hasChecked,+ totalSteps,+ nextStep,+ prevStep,+ skip,+ complete,+ } = useOnboarding(reopenTrigger);++ if (!isVisible || !hasChecked || isLoading) return null;++ const isLastStep = currentStep >= totalSteps - 1;++ const renderStep = () => {+ switch (currentStep) {+ case 0: return <WelcomeStep />;+ case 1: return <ConceptsStep />;+ case 2: return <ApiKeyStep onOpenCredentials={onOpenCredentials} />;+ case 3: return <CanvasStep />;+ case 4: return <GetStartedStep />;+ default: return <WelcomeStep />;+ }+ };++ return (+ <Modal+ isOpen={isVisible}+ onClose={skip}+ title="Welcome Guide"+ maxWidth="680px"+ maxHeight="85vh"+ >+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ padding: '20px 24px 16px',+ }}>+ {/* Progress steps */}+ <Steps+ current={currentStep}+ size="small"+ items={stepItems}+ style={{ marginBottom: 20 }}+ />++ {/* Step content */}+ <div style={{+ flex: 1,+ overflowY: 'auto',+ minHeight: 0,+ paddingRight: 4,+ }}>+ {renderStep()}+ </div>++ {/* Footer navigation */}+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ paddingTop: 16,+ marginTop: 16,+ borderTop: `1px solid ${theme.colors.border}`,+ }}>+ {/* Left: Skip */}+ <Button type="text" onClick={skip} size="small" style={{ color: theme.colors.textSecondary }}>+ Skip for now+ </Button>++ {/* Right: Back + Next/Finish */}+ <Space>+ {currentStep > 0 && (+ <Button+ icon={<ArrowLeftOutlined />}+ onClick={prevStep}+ size="middle"+ >+ Back+ </Button>+ )}+ {isLastStep ? (+ <Button+ type="primary"+ icon={<CheckOutlined />}+ onClick={complete}+ size="middle"+ style={{+ backgroundColor: theme.dracula.green,+ borderColor: theme.dracula.green,+ }}+ >+ Start Building+ </Button>+ ) : (+ <Button+ type="primary"+ onClick={nextStep}+ size="middle"+ style={{+ backgroundColor: theme.dracula.purple,+ borderColor: theme.dracula.purple,+ }}+ >+ Next <ArrowRightOutlined />+ </Button>+ )}+ </Space>+ </div>+ </div>+ </Modal>+ );+};++export default OnboardingWizard;diff --git a/client/src/components/onboarding/steps/ApiKeyStep.tsx b/client/src/components/onboarding/steps/ApiKeyStep.tsxnew file mode 100644index 00000000..324543cd--- /dev/null+++ b/client/src/components/onboarding/steps/ApiKeyStep.tsx@@ -0,0 +1,91 @@+import React from 'react';+import { Typography, Button, Space, Alert } from 'antd';+import { KeyOutlined, LinkOutlined } from '@ant-design/icons';+import {+ OpenAIIcon, ClaudeIcon, GeminiIcon, GroqIcon, OpenRouterIcon, CerebrasIcon,+} from '../../icons/AIProviderIcons';+import { useAppTheme } from '../../../hooks/useAppTheme';++const { Title, Text } = Typography;++interface ApiKeyStepProps {+ onOpenCredentials: () => void;+}++const providers = [+ { name: 'OpenAI', icon: <OpenAIIcon />, desc: 'GPT-4o, o3, o4 models', url: 'platform.openai.com' },+ { name: 'Anthropic', icon: <ClaudeIcon />, desc: 'Claude Opus, Sonnet models', url: 'console.anthropic.com' },+ { name: 'Google', icon: <GeminiIcon />, desc: 'Gemini Pro, Flash models', url: 'aistudio.google.com' },+ { name: 'Groq', icon: <GroqIcon />, desc: 'Ultra-fast Llama, Qwen', url: 'console.groq.com' },+ { name: 'OpenRouter', icon: <OpenRouterIcon />, desc: 'Access 200+ models', url: 'openrouter.ai' },+ { name: 'Cerebras', icon: <CerebrasIcon />, desc: 'Fast inference on custom HW', url: 'cloud.cerebras.ai' },+];++const ApiKeyStep: React.FC<ApiKeyStepProps> = ({ onOpenCredentials }) => {+ const theme = useAppTheme();++ return (+ <div style={{ padding: '4px 0' }}>+ <div style={{ textAlign: 'center', marginBottom: 16 }}>+ <Title level={4} style={{ margin: '0 0 4px 0' }}>+ <KeyOutlined style={{ marginRight: 8, color: theme.dracula.yellow }} />+ API Key Setup+ </Title>+ <Text type="secondary" style={{ fontSize: 12 }}>+ Configure at least one AI provider to use AI agents+ </Text>+ </div>++ <Space direction="vertical" size={8} style={{ width: '100%' }}>+ {providers.map((p) => (+ <div+ key={p.name}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 10,+ padding: '8px 12px',+ backgroundColor: theme.colors.backgroundAlt,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: 6,+ }}+ >+ <div style={{ width: 24, height: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>+ {p.icon}+ </div>+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text strong style={{ fontSize: 13, display: 'block' }}>{p.name}</Text>+ <Text type="secondary" style={{ fontSize: 11 }}>{p.desc}</Text>+ </div>+ <Text type="secondary" style={{ fontSize: 10 }}>+ <LinkOutlined /> {p.url}+ </Text>+ </div>+ ))}+ </Space>++ <div style={{ textAlign: 'center', marginTop: 20 }}>+ <Button+ type="primary"+ icon={<KeyOutlined />}+ onClick={onOpenCredentials}+ style={{+ backgroundColor: theme.dracula.cyan,+ borderColor: theme.dracula.cyan,+ }}+ >+ Open Credentials+ </Button>+ </div>++ <Alert+ type="info"+ showIcon+ message="You can always change API keys later from the toolbar credentials button."+ style={{ marginTop: 16, fontSize: 12 }}+ />+ </div>+ );+};++export default ApiKeyStep;diff --git a/client/src/components/onboarding/steps/CanvasStep.tsx b/client/src/components/onboarding/steps/CanvasStep.tsxnew file mode 100644index 00000000..1d3c38a9--- /dev/null+++ b/client/src/components/onboarding/steps/CanvasStep.tsx@@ -0,0 +1,150 @@+import React from 'react';+import { Typography, Tag, Space } from 'antd';+import {+ LayoutOutlined,+ ToolOutlined,+ CodeOutlined,+} from '@ant-design/icons';+import { useAppTheme } from '../../../hooks/useAppTheme';++const { Title, Text } = Typography;++const CanvasStep: React.FC = () => {+ const theme = useAppTheme();++ const shortcuts = [+ { keys: 'Ctrl+S', action: 'Save workflow' },+ { keys: 'F2', action: 'Rename node' },+ { keys: 'Delete', action: 'Remove node' },+ { keys: 'Ctrl+C', action: 'Copy node' },+ ];++ return (+ <div style={{ padding: '4px 0' }}>+ <div style={{ textAlign: 'center', marginBottom: 16 }}>+ <Title level={4} style={{ margin: '0 0 4px 0' }}>Canvas Tour</Title>+ <Text type="secondary" style={{ fontSize: 12 }}>+ Navigate the main interface regions+ </Text>+ </div>++ {/* Visual layout diagram */}+ <div style={{+ border: `1px solid ${theme.colors.border}`,+ borderRadius: 8,+ overflow: 'hidden',+ marginBottom: 16,+ }}>+ {/* Toolbar */}+ <div style={{+ padding: '6px 10px',+ backgroundColor: `${theme.dracula.orange}15`,+ borderBottom: `1px solid ${theme.colors.border}`,+ display: 'flex',+ alignItems: 'center',+ gap: 6,+ }}>+ <ToolOutlined style={{ color: theme.dracula.orange, fontSize: 12 }} />+ <Text style={{ fontSize: 11, color: theme.dracula.orange }} strong>Toolbar</Text>+ <div style={{ flex: 1 }} />+ <Tag color="orange" style={{ fontSize: 10, margin: 0, lineHeight: '18px' }}>Run</Tag>+ <Tag color="purple" style={{ fontSize: 10, margin: 0, lineHeight: '18px' }}>Deploy</Tag>+ <Tag color="cyan" style={{ fontSize: 10, margin: 0, lineHeight: '18px' }}>Save</Tag>+ </div>++ {/* Main area */}+ <div style={{ display: 'flex', height: 120 }}>+ {/* Sidebar */}+ <div style={{+ width: 80,+ backgroundColor: `${theme.dracula.cyan}10`,+ borderRight: `1px solid ${theme.colors.border}`,+ padding: 6,+ display: 'flex',+ flexDirection: 'column',+ gap: 3,+ }}>+ <Text style={{ fontSize: 9, color: theme.dracula.cyan }} strong>Sidebar</Text>+ {['Workflow 1', 'Workflow 2'].map(w => (+ <div key={w} style={{+ fontSize: 8,+ padding: '2px 4px',+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: 3,+ color: theme.colors.textSecondary,+ }}>{w}</div>+ ))}+ </div>++ {/* Canvas */}+ <div style={{+ flex: 1,+ backgroundColor: `${theme.dracula.purple}08`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ position: 'relative',+ }}>+ <div style={{ textAlign: 'center' }}>+ <LayoutOutlined style={{ fontSize: 20, color: theme.dracula.purple, opacity: 0.5 }} />+ <div style={{ fontSize: 9, color: theme.dracula.purple, marginTop: 2 }}>Canvas</div>+ </div>+ </div>++ {/* Palette */}+ <div style={{+ width: 80,+ backgroundColor: `${theme.dracula.green}10`,+ borderLeft: `1px solid ${theme.colors.border}`,+ padding: 6,+ display: 'flex',+ flexDirection: 'column',+ gap: 3,+ }}>+ <Text style={{ fontSize: 9, color: theme.dracula.green }} strong>Palette</Text>+ {['AI Agents', 'AI Models', 'Skills'].map(c => (+ <div key={c} style={{+ fontSize: 8,+ padding: '2px 4px',+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: 3,+ color: theme.colors.textSecondary,+ }}>{c}</div>+ ))}+ </div>+ </div>++ {/* Console */}+ <div style={{+ padding: '6px 10px',+ backgroundColor: `${theme.dracula.pink}10`,+ borderTop: `1px solid ${theme.colors.border}`,+ display: 'flex',+ alignItems: 'center',+ gap: 6,+ }}>+ <CodeOutlined style={{ color: theme.dracula.pink, fontSize: 12 }} />+ <Text style={{ fontSize: 11, color: theme.dracula.pink }} strong>Console</Text>+ <div style={{ flex: 1 }} />+ <Tag style={{ fontSize: 9, margin: 0, lineHeight: '16px' }}>Chat</Tag>+ <Tag style={{ fontSize: 9, margin: 0, lineHeight: '16px' }}>Logs</Tag>+ </div>+ </div>++ {/* Keyboard shortcuts */}+ <div>+ <Text strong style={{ fontSize: 12, display: 'block', marginBottom: 8 }}>Keyboard Shortcuts</Text>+ <Space wrap size={[8, 6]}>+ {shortcuts.map((s) => (+ <span key={s.keys} style={{ fontSize: 12 }}>+ <Tag style={{ fontSize: 11, fontFamily: 'monospace' }}>{s.keys}</Tag>+ <Text type="secondary" style={{ fontSize: 11 }}>{s.action}</Text>+ </span>+ ))}+ </Space>+ </div>+ </div>+ );+};++export default CanvasStep;diff --git a/client/src/components/onboarding/steps/ConceptsStep.tsx b/client/src/components/onboarding/steps/ConceptsStep.tsxnew file mode 100644index 00000000..e3313931--- /dev/null+++ b/client/src/components/onboarding/steps/ConceptsStep.tsx@@ -0,0 +1,102 @@+import React from 'react';+import { Typography, Space } from 'antd';+import {+ AppstoreOutlined,+ BranchesOutlined,+ RobotOutlined,+ ToolOutlined,+ SwapOutlined,+} from '@ant-design/icons';+import { useAppTheme } from '../../../hooks/useAppTheme';++const { Title, Text, Paragraph } = Typography;++const ConceptsStep: React.FC = () => {+ const theme = useAppTheme();++ const concepts = [+ {+ icon: <AppstoreOutlined />,+ title: 'Nodes',+ desc: 'Building blocks of your workflow. Each node performs a specific action like sending a message, calling an AI model, or processing data.',+ color: theme.dracula.cyan,+ },+ {+ icon: <BranchesOutlined />,+ title: 'Edges',+ desc: "Connections between nodes that define data flow. Drag from one node's output to another's input to connect them.",+ color: theme.dracula.green,+ },+ {+ icon: <RobotOutlined />,+ title: 'AI Agents',+ desc: 'Intelligent nodes that use LLMs (Claude, GPT, Gemini) to reason, call tools, and complete tasks autonomously.',+ color: theme.dracula.purple,+ },+ {+ icon: <ToolOutlined />,+ title: 'Skills & Tools',+ desc: 'Connect skills and tools to agents to extend their capabilities. Skills provide instructions, tools provide actions.',+ color: theme.dracula.orange,+ },+ {+ icon: <SwapOutlined />,+ title: 'Normal vs Dev Mode',+ desc: 'Normal mode shows AI-focused nodes for simple workflows. Dev mode unlocks all 108+ nodes for advanced automation.',+ color: theme.dracula.pink,+ },+ ];++ return (+ <div style={{ padding: '4px 0' }}>+ <div style={{ textAlign: 'center', marginBottom: 16 }}>+ <Title level={4} style={{ margin: '0 0 4px 0' }}>Key Concepts</Title>+ <Text type="secondary" style={{ fontSize: 12 }}>+ Understanding these will help you build powerful workflows+ </Text>+ </div>++ <Space direction="vertical" size={10} style={{ width: '100%' }}>+ {concepts.map((c) => (+ <div+ key={c.title}+ style={{+ display: 'flex',+ alignItems: 'flex-start',+ gap: 12,+ padding: 12,+ backgroundColor: `${c.color}10`,+ border: `1px solid ${c.color}25`,+ borderRadius: 6,+ }}+ >+ <div style={{+ width: 32,+ height: 32,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: `${c.color}20`,+ borderRadius: 6,+ fontSize: 16,+ color: c.color,+ flexShrink: 0,+ }}>+ {c.icon}+ </div>+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text strong style={{ fontSize: 13, color: c.color, display: 'block', marginBottom: 2 }}>+ {c.title}+ </Text>+ <Paragraph type="secondary" style={{ fontSize: 12, margin: 0, lineHeight: 1.5 }}>+ {c.desc}+ </Paragraph>+ </div>+ </div>+ ))}+ </Space>+ </div>+ );+};++export default ConceptsStep;diff --git a/client/src/components/onboarding/steps/GetStartedStep.tsx b/client/src/components/onboarding/steps/GetStartedStep.tsxnew file mode 100644index 00000000..cfd9dea1--- /dev/null+++ b/client/src/components/onboarding/steps/GetStartedStep.tsx@@ -0,0 +1,103 @@+import React from 'react';+import { Typography, Card, Space, Tag } from 'antd';+import {+ PlayCircleOutlined,+ ExperimentOutlined,+ BookOutlined,+ SettingOutlined,+} from '@ant-design/icons';+import { useAppTheme } from '../../../hooks/useAppTheme';++const { Title, Text, Paragraph } = Typography;++const GetStartedStep: React.FC = () => {+ const theme = useAppTheme();++ const tips = [+ {+ icon: <PlayCircleOutlined />,+ title: 'Try an Example Workflow',+ desc: 'Open the sidebar and click on one of the pre-loaded example workflows to see how things work.',+ color: theme.dracula.green,+ },+ {+ icon: <ExperimentOutlined />,+ title: 'Build Your First Workflow',+ desc: (+ <>+ Quick recipe: drag{' '}+ <Tag style={{ fontSize: 10, lineHeight: '16px', margin: '0 2px' }}>Chat Trigger</Tag>+ <Text type="secondary" style={{ fontSize: 12 }}>{'\u2192'}</Text>{' '}+ <Tag style={{ fontSize: 10, lineHeight: '16px', margin: '0 2px' }}>Zeenie</Tag>+ <Text type="secondary" style={{ fontSize: 12 }}>{'\u2192'}</Text>{' '}+ <Tag style={{ fontSize: 10, lineHeight: '16px', margin: '0 2px' }}>Claude Model</Tag>+ {' '}then click <Tag color="green" style={{ fontSize: 10, lineHeight: '16px', margin: '0 2px' }}>Run</Tag>+ </>+ ),+ color: theme.dracula.purple,+ },+ {+ icon: <BookOutlined />,+ title: 'Explore AI Skills',+ desc: 'Use the Master Skill node to browse and enable built-in skills for your AI agents.',+ color: theme.dracula.cyan,+ },+ {+ icon: <SettingOutlined />,+ title: 'Revisit This Guide',+ desc: 'You can replay this welcome guide anytime from Settings.',+ color: theme.dracula.orange,+ },+ ];++ return (+ <div style={{ padding: '4px 0' }}>+ <div style={{ textAlign: 'center', marginBottom: 16 }}>+ <Title level={4} style={{ margin: '0 0 4px 0' }}>Get Started</Title>+ <Text type="secondary" style={{ fontSize: 12 }}>+ Here are some things to try first+ </Text>+ </div>++ <Space direction="vertical" size={10} style={{ width: '100%' }}>+ {tips.map((t, i) => (+ <Card+ key={i}+ size="small"+ style={{+ borderColor: `${t.color}30`,+ backgroundColor: `${t.color}08`,+ }}+ >+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>+ <div style={{+ width: 28,+ height: 28,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: `${t.color}20`,+ borderRadius: 6,+ color: t.color,+ fontSize: 14,+ flexShrink: 0,+ }}>+ {t.icon}+ </div>+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text strong style={{ fontSize: 13, color: t.color, display: 'block', marginBottom: 2 }}>+ {t.title}+ </Text>+ <Paragraph type="secondary" style={{ fontSize: 12, margin: 0, lineHeight: 1.5 }}>+ {t.desc}+ </Paragraph>+ </div>+ </div>+ </Card>+ ))}+ </Space>+ </div>+ );+};++export default GetStartedStep;diff --git a/client/src/components/onboarding/steps/WelcomeStep.tsx b/client/src/components/onboarding/steps/WelcomeStep.tsxnew file mode 100644index 00000000..e11e2881--- /dev/null+++ b/client/src/components/onboarding/steps/WelcomeStep.tsx@@ -0,0 +1,65 @@+import React from 'react';+import { Typography, Card, Row, Col } from 'antd';+import {+ RocketOutlined,+ ApiOutlined,+ DragOutlined,+ ThunderboltOutlined,+} from '@ant-design/icons';+import { useAppTheme } from '../../../hooks/useAppTheme';++const { Title, Text, Paragraph } = Typography;++const features = [+ { icon: <ApiOutlined />, label: '108+ Nodes', desc: 'Workflow building blocks' },+ { icon: <RocketOutlined />, label: '6 AI Providers', desc: 'OpenAI, Claude, Gemini & more' },+ { icon: <DragOutlined />, label: 'Drag & Drop', desc: 'Visual workflow builder' },+ { icon: <ThunderboltOutlined />, label: 'Real-time', desc: 'Live execution & monitoring' },+];++const WelcomeStep: React.FC = () => {+ const theme = useAppTheme();++ return (+ <div style={{ textAlign: 'center', padding: '8px 0' }}>+ <RocketOutlined style={{ fontSize: 40, color: theme.dracula.purple, marginBottom: 8 }} />++ <Title level={3} style={{ margin: '0 0 4px 0' }}>+ Welcome to MachinaOs+ </Title>++ <Text strong style={{ color: theme.dracula.purple, fontSize: 15 }}>+ Visual workflow automation powered by AI agents+ </Text>++ <Paragraph type="secondary" style={{ maxWidth: 480, margin: '16px auto 24px auto', fontSize: 13 }}>+ MachinaOs lets you build intelligent automation workflows by connecting+ AI models, tools, and services together on an interactive canvas.+ No coding required for most tasks.+ </Paragraph>++ <Row gutter={[12, 12]} justify="center" style={{ maxWidth: 440, margin: '0 auto' }}>+ {features.map((f) => (+ <Col span={12} key={f.label}>+ <Card+ size="small"+ style={{+ textAlign: 'center',+ backgroundColor: `${theme.dracula.purple}12`,+ borderColor: `${theme.dracula.purple}30`,+ }}+ >+ <div style={{ fontSize: 22, color: theme.dracula.purple, marginBottom: 4 }}>+ {f.icon}+ </div>+ <Text strong style={{ fontSize: 13, display: 'block' }}>{f.label}</Text>+ <Text type="secondary" style={{ fontSize: 11 }}>{f.desc}</Text>+ </Card>+ </Col>+ ))}+ </Row>+ </div>+ );+};++export default WelcomeStep;diff --git a/client/src/components/ui/ComponentPalette.tsx b/client/src/components/ui/ComponentPalette.tsxindex bdce6aa1..7697603a 100644--- a/client/src/components/ui/ComponentPalette.tsx+++ b/client/src/components/ui/ComponentPalette.tsx@@ -4,9 +4,10 @@ import { ComponentPaletteProps } from '../../types/ComponentTypes';import { INodeTypeDescription } from '../../types/INodeProperties';import ComponentItem from './ComponentItem';import CollapsibleSection from './CollapsibleSection';+import googleSvg from '../../assets/icons/search/google.svg?raw';-// Category emoji icons-const CATEGORY_EMOJIS: Record<string, string> = {+// Category icons - emoji strings or { svg: string } for inline SVG icons+const CATEGORY_ICONS: Record<string, string | { svg: string }> = {workflow: '⚡',trigger: '🕐',ai: '🤖',@@ -21,6 +22,10 @@ const CATEGORY_EMOJIS: Record<string, string> = {code: '💻',document: '🗄️',utility: '🔧',+ api: '🕷️',+ search: '🔍',+ google: { svg: googleSvg },+ scheduler: '📅',};// Categories that should be merged into 'social' (Social Media)@@ -59,6 +64,10 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({code: colors.categoryCode || theme.dracula.orange,document: colors.categoryTrigger || theme.dracula.pink,utility: colors.categoryUtil || theme.dracula.purple,+ api: colors.categoryCode || theme.dracula.orange,+ search: colors.categoryModel || theme.dracula.cyan,+ google: theme.accent.blue,+ scheduler: colors.categoryTrigger || theme.dracula.pink,};const labelMap: Record<string, string> = {workflow: 'Workflows',@@ -75,9 +84,13 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({code: 'Code',document: 'Documents',utility: 'Utilities',+ api: 'API & Scraping',+ search: 'Search',+ google: 'Google Workspace',+ scheduler: 'Schedulers',};return {- icon: CATEGORY_EMOJIS[key] || '📦',+ icon: CATEGORY_ICONS[key] || '📦',color: colorMap[key] || theme.colors.textSecondary,label: labelMap[key] || category};@@ -271,7 +284,14 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({borderRadius: '6px',fontSize: '16px',}}>- {config.icon}+ {typeof config.icon === 'object' && 'svg' in config.icon ? (+ <span+ dangerouslySetInnerHTML={{ __html: config.icon.svg }}+ style={{ width: '16px', height: '16px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}+ />+ ) : (+ config.icon+ )}</span><span style={{fontWeight: theme.fontWeight.semibold,diff --git a/client/src/components/ui/SettingsPanel.tsx b/client/src/components/ui/SettingsPanel.tsxindex ee58ad9b..b0a531e3 100644--- a/client/src/components/ui/SettingsPanel.tsx+++ b/client/src/components/ui/SettingsPanel.tsx@@ -1,5 +1,6 @@import React, { useState, useEffect, useCallback } from 'react';-import { Switch, InputNumber, message } from 'antd';+import { Switch, InputNumber, Button, message } from 'antd';+import { QuestionCircleOutlined } from '@ant-design/icons';import Modal from './Modal';import { useAppTheme } from '../../hooks/useAppTheme';import { useWebSocket } from '../../contexts/WebSocketContext';@@ -27,6 +28,7 @@ interface SettingsPanelProps {onClose: () => void;settings: WorkflowSettings;onSettingsChange: (settings: WorkflowSettings) => void;+ onReplayOnboarding?: () => void;}const SettingsPanel: React.FC<SettingsPanelProps> = ({@@ -34,6 +36,7 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({onClose,settings,onSettingsChange,+ onReplayOnboarding,}) => {const theme = useAppTheme();const { sendRequest, isConnected } = useWebSocket();@@ -420,6 +423,36 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({/></div></div>++ {/* Help Section */}+ <div style={sectionStyle}>+ <div style={sectionHeaderStyle}>+ <div style={{ ...sectionIconStyle, backgroundColor: `${theme.dracula.cyan}20` }}>+ <QuestionCircleOutlined style={{ color: theme.dracula.cyan }} />+ </div>+ <div style={sectionTitleStyle}>Help</div>+ </div>++ <div style={settingRowStyle}>+ <div style={settingLabelStyle}>+ <div style={labelTextStyle}>Replay Welcome Guide</div>+ <div style={descriptionStyle}>Show the onboarding wizard again to review platform features</div>+ </div>+ <Button+ size="small"+ icon={<QuestionCircleOutlined />}+ onClick={onReplayOnboarding}+ disabled={!onReplayOnboarding}+ style={{+ backgroundColor: `${theme.dracula.cyan}25`,+ color: theme.dracula.cyan,+ borderColor: `${theme.dracula.cyan}60`,+ }}+ >+ Replay+ </Button>+ </div>+ </div></div></div>diff --git a/client/src/config/api.ts b/client/src/config/api.tsindex 1e285af9..2f34eef4 100644--- a/client/src/config/api.ts+++ b/client/src/config/api.ts@@ -5,7 +5,6 @@interface ApiConfig {readonly PYTHON_BASE_URL: string;- readonly WHATSAPP_BASE_URL: string;readonly AUTH_ENABLED: boolean;}@@ -24,9 +23,6 @@ function getApiConfig(): ApiConfig {// Python FastAPI backend (port 3010 in dev, same origin in prod)PYTHON_BASE_URL: viteEnv.VITE_PYTHON_SERVICE_URL || (isProduction ? '' : 'http://localhost:3010'),- // WhatsApp Go service (port 3012) - typically not called directly from frontend- WHATSAPP_BASE_URL: viteEnv.VITE_WHATSAPP_SERVICE_URL || (isProduction ? '' : 'http://localhost:3012'),-// Authentication enabled (default true, set VITE_AUTH_ENABLED=false to disable)AUTH_ENABLED: viteEnv.VITE_AUTH_ENABLED !== 'false',};diff --git a/client/src/hooks/useOnboarding.ts b/client/src/hooks/useOnboarding.tsnew file mode 100644index 00000000..7b7aac72--- /dev/null+++ b/client/src/hooks/useOnboarding.ts@@ -0,0 +1,117 @@+import { useState, useCallback, useEffect, useRef } from 'react';+import { useWebSocket } from '../contexts/WebSocketContext';++export interface OnboardingState {+ isVisible: boolean;+ currentStep: number;+ isCompleted: boolean;+ isLoading: boolean;+ hasChecked: boolean;+}++const TOTAL_STEPS = 5;++export const useOnboarding = (reopenTrigger?: number) => {+ const { sendRequest, isConnected } = useWebSocket();+ const [state, setState] = useState<OnboardingState>({+ isVisible: false,+ currentStep: 0,+ isCompleted: false,+ isLoading: true,+ hasChecked: false,+ });+ const hasCheckedRef = useRef(false);++ // Check onboarding status on WebSocket connect (once)+ useEffect(() => {+ if (!isConnected || hasCheckedRef.current) return;+ hasCheckedRef.current = true;++ const checkOnboarding = async () => {+ try {+ const response = await sendRequest<{ settings: any }>('get_user_settings', {});+ const settings = response?.settings;+ const completed = settings?.onboarding_completed ?? false;+ const step = settings?.onboarding_step ?? 0;++ setState({+ isVisible: !completed,+ currentStep: step,+ isCompleted: completed,+ isLoading: false,+ hasChecked: true,+ });+ } catch (error) {+ console.error('[Onboarding] Failed to check status:', error);+ setState(prev => ({ ...prev, isLoading: false, hasChecked: true }));+ }+ };++ checkOnboarding();+ }, [isConnected, sendRequest]);++ // Handle reopen trigger from SettingsPanel+ useEffect(() => {+ if (reopenTrigger && reopenTrigger > 0) {+ hasCheckedRef.current = false;+ setState(prev => ({+ ...prev,+ isVisible: true,+ currentStep: 0,+ isCompleted: false,+ }));+ }+ }, [reopenTrigger]);++ const saveProgress = useCallback(async (step: number, completed: boolean) => {+ try {+ await sendRequest('save_user_settings', {+ settings: {+ onboarding_step: step,+ onboarding_completed: completed,+ }+ });+ } catch (error) {+ console.error('[Onboarding] Failed to save progress:', error);+ }+ }, [sendRequest]);++ const nextStep = useCallback(() => {+ setState(prev => {+ const next = prev.currentStep + 1;+ if (next >= TOTAL_STEPS) {+ saveProgress(TOTAL_STEPS, true);+ return { ...prev, currentStep: next, isCompleted: true, isVisible: false };+ }+ saveProgress(next, false);+ return { ...prev, currentStep: next };+ });+ }, [saveProgress]);++ const prevStep = useCallback(() => {+ setState(prev => {+ const next = Math.max(0, prev.currentStep - 1);+ saveProgress(next, false);+ return { ...prev, currentStep: next };+ });+ }, [saveProgress]);++ const skip = useCallback(() => {+ saveProgress(state.currentStep, true);+ setState(prev => ({ ...prev, isVisible: false, isCompleted: true }));+ }, [saveProgress, state.currentStep]);++ const complete = useCallback(() => {+ saveProgress(TOTAL_STEPS, true);+ setState(prev => ({ ...prev, isVisible: false, isCompleted: true }));+ }, [saveProgress]);++ return {+ ...state,+ totalSteps: TOTAL_STEPS,+ nextStep,+ prevStep,+ skip,+ complete,+ };+};diff --git a/client/src/utils/parameterSanitizer.ts b/client/src/utils/parameterSanitizer.tsindex 57c44213..817d11ca 100644--- a/client/src/utils/parameterSanitizer.ts+++ b/client/src/utils/parameterSanitizer.ts@@ -17,14 +17,36 @@ const SENSITIVE_EXACT_KEYS = new Set(['oauthToken', 'oauth_token',]);+// Legitimate parameter names that contain sensitive substrings but are NOT credentials.+// These are checked first and always allowed through.+const SAFE_KEYS = new Set([+ 'maxTokens', 'max_tokens',+ 'budgetTokens', 'budget_tokens',+ 'page_token', 'pageToken', 'nextPageToken', 'next_page_token',+ 'tokenCount', 'token_count',+ 'totalTokens', 'total_tokens',+ 'inputTokens', 'input_tokens',+ 'outputTokens', 'output_tokens',+]);+// Substring patterns - if a key contains any of these (case-insensitive),-// the value is stripped. Catches variants like "google_access_token".+// the value is stripped. Uses specific credential patterns to avoid+// false positives on parameter names like "maxTokens" or "page_token".const SENSITIVE_SUBSTRINGS = [- 'api_key', 'apikey', 'secret', 'password', 'token',+ 'api_key', 'apikey',+ 'secret',+ 'password','private_key', 'privatekey',+ 'accesstoken', 'access_token',+ 'refreshtoken', 'refresh_token',+ 'bearertoken', 'bearer_token',+ 'oauthtoken', 'oauth_token',+ 'authtoken', 'auth_token',];+// eslint-disable-next-line @typescript-eslint/no-unused-varsfunction isSensitiveKey(key: string): boolean {+ if (SAFE_KEYS.has(key)) return false;if (SENSITIVE_EXACT_KEYS.has(key)) return true;const lower = key.toLowerCase();return SENSITIVE_SUBSTRINGS.some(sub => lower.includes(sub));@@ -36,14 +58,6 @@ function isSensitiveKey(key: string): boolean {* Recurses into nested objects but passes arrays through unchanged.*/export function sanitizeParameters(params: Record<string, any>): Record<string, any> {- const result: Record<string, any> = {};- for (const [key, value] of Object.entries(params)) {- if (isSensitiveKey(key)) continue;- if (value && typeof value === 'object' && !Array.isArray(value)) {- result[key] = sanitizeParameters(value);- } else {- result[key] = value;- }- }- return result;+ // TODO: Re-enable sanitization once safe-key allowlist is fully validated+ return { ...params };}diff --git a/deploy.sh b/deploy.shindex 1c878c4a..5a34ced6 100644--- a/deploy.sh+++ b/deploy.sh@@ -19,7 +19,7 @@ if [ -f "$(dirname "$0")/server/.env" ]; thenfiGCP_HOST="${1:-${DEPLOY_HOST:-user@your-server-ip}}"-SERVICE_NAME="machinaos"+SERVICE_NAME="machina"DOMAIN="${DEPLOY_DOMAIN:-your-domain.com}"REMOTE_DIR="/opt/${SERVICE_NAME}"LOCAL_DIR="$(cd "$(dirname "$0")" && pwd)"@@ -49,11 +49,11 @@ tar --exclude='node_modules' \--exclude='*.db-*' \--exclude='data' \--exclude='bin' \- -czf /tmp/machinaos-src.tar.gz \+ -czf /tmp/machina-src.tar.gz \-C "${LOCAL_DIR}" \client server docker-compose.prod.yml-scp /tmp/machinaos-src.tar.gz "${GCP_HOST}:/tmp/${SERVICE_NAME}/"+scp /tmp/machina-src.tar.gz "${GCP_HOST}:/tmp/${SERVICE_NAME}/"# Upload production .env (prefer .env.production, fallback to .env, then create from template)if [ -f "${LOCAL_DIR}/server/.env.production" ]; then@@ -74,7 +74,7 @@ fiecho "[2/5] Building and deploying on GCP..."ssh ${GCP_HOST} << 'REMOTE_SCRIPT'set -e-SERVICE_NAME="machinaos"+SERVICE_NAME="machina"DEPLOY_DIR="/opt/${SERVICE_NAME}"# Stop existing containers@@ -86,7 +86,7 @@ sudo chown -R $USER:$USER ${DEPLOY_DIR}# Extract source codecd ${DEPLOY_DIR}-tar -xzf /tmp/${SERVICE_NAME}/machinaos-src.tar.gz+tar -xzf /tmp/${SERVICE_NAME}/machina-src.tar.gz# Copy .env file to server directory (where docker-compose expects it)mkdir -p ${DEPLOY_DIR}/server@@ -188,7 +188,7 @@ sleep 5ssh ${GCP_HOST} "cd /opt/${SERVICE_NAME} && docker-compose ps"# Cleanup local temp files-rm -f /tmp/machinaos-src.tar.gz+rm -f /tmp/machina-src.tar.gzecho "========================================"echo "[5/5] Deployment Complete!"diff --git a/docs-internal/SCRIPTS.md b/docs-internal/SCRIPTS.mdindex cfda3ff7..4cd76d5a 100644--- a/docs-internal/SCRIPTS.md+++ b/docs-internal/SCRIPTS.md@@ -3,8 +3,8 @@## Quick Start```bash-npm install -g machinaos-machinaos start+npm install -g machina+machina start```Open http://localhost:3000@@ -15,15 +15,15 @@ Open http://localhost:3000| Command | Description ||---------|-------------|-| `machinaos start` | Start the development server (checks dependencies first) |-| `machinaos stop` | Stop all running services |-| `machinaos build` | Build the project for production (checks dependencies first) |-| `machinaos clean` | Clean build artifacts and node_modules |-| `machinaos docker:up` | Start with Docker Compose (detached) |-| `machinaos docker:down` | Stop Docker Compose services |-| `machinaos docker:build` | Build Docker images |-| `machinaos docker:logs` | View Docker logs (follows) |-| `machinaos help` | Show help message |+| `machina start` | Start the development server (checks dependencies first) |+| `machina stop` | Stop all running services |+| `machina build` | Build the project for production (checks dependencies first) |+| `machina clean` | Clean build artifacts and node_modules |+| `machina docker:up` | Start with Docker Compose (detached) |+| `machina docker:down` | Stop Docker Compose services |+| `machina docker:build` | Build Docker images |+| `machina docker:logs` | View Docker logs (follows) |+| `machina help` | Show help message |### Dependency Checks@@ -255,18 +255,18 @@ Key variables in `.env` (see `.env.template` for full list):```bash# Development-machinaos start # Start all services-machinaos stop # Stop all services+machina start # Start all services+machina stop # Stop all services# Build-machinaos build # Build for production-machinaos clean # Clean everything+machina build # Build for production+machina clean # Clean everything# Docker (development)-machinaos docker:up # Start containers-machinaos docker:down # Stop containers-machinaos docker:logs # View logs-machinaos docker:build # Rebuild images+machina docker:up # Start containers+machina docker:down # Stop containers+machina docker:logs # View logs+machina docker:build # Rebuild images# Docker (production)npm run docker:prod:up # Start productiondiff --git a/docs-internal/SETUP.md b/docs-internal/SETUP.mdindex b9e2f2b3..1f38a655 100644--- a/docs-internal/SETUP.md+++ b/docs-internal/SETUP.md@@ -21,8 +21,8 @@ MachinaOs/## Quick Start```bash-npm install -g machinaos-machinaos start+npm install -g machina+machina start```Open http://localhost:3000diff --git a/docs-internal/ci_cd.md b/docs-internal/ci_cd.mdindex c4a017d1..bae952d6 100644--- a/docs-internal/ci_cd.md+++ b/docs-internal/ci_cd.md@@ -21,8 +21,8 @@ Internal reference for the GitHub Actions CI/CD pipeline. Covers all workflows,manual dispatch ------> | | | - test-install || +-- predeploy --+ +--------------------+| |- | +-- publish-npm ---------> npmjs.org (machinaos)- | +-- publish-github-pkgs -> GitHub Packages (@trohitg/machinaos)+ | +-- publish-npm ---------> npmjs.org (machina)+ | +-- publish-github-pkgs -> GitHub Packages (@trohitg/machina)+------------------+push to docs-MachinaOs/ +------------------+@@ -80,7 +80,7 @@ Shared environment setup used by `predeploy.yml` jobs. Eliminates duplicated Nod| `node-version` | `'20'` | Node.js version to install || `python-version` | `'3.12'` | Python version to install |-Python and uv are needed because `postinstall.js` skips Python venv setup in CI, so they must be available for the `machinaos build` command in `test-install`.+Python and uv are needed because `postinstall.js` skips Python venv setup in CI, so they must be available for the `machina build` command in `test-install`.---@@ -151,14 +151,14 @@ Total: **6 combinations**, `fail-fast: false` (all run regardless of individual1. Checkout2. Setup environment (composite action with matrix `node-version`)3. `npm pack` -- create tarball-4. `npm install -g machinaos-*.tgz` -- global install from tarball-5. `machinaos --help` -- verify CLI is available-6. `machinaos build` -- install client deps, build client, setup Python venv-7. Verify build artifacts exist at `$(npm root -g)/machinaos`:+4. `npm install -g machina-*.tgz` -- global install from tarball+5. `machina --help` -- verify CLI is available+6. `machina build` -- install client deps, build client, setup Python venv+7. Verify build artifacts exist at `$(npm root -g)/machina`:- `.env` file- `client/dist/` directory- `server/.venv/` directory-8. `machinaos start &` -- start in background, wait 10s, verify process is still running+8. `machina start &` -- start in background, wait 10s, verify process is still runningAll steps use `shell: bash` for cross-platform compatibility (Windows uses Git Bash).@@ -227,7 +227,7 @@ Calls `predeploy.yml` as a prerequisite. Both publish jobs require this to pass### Job: publish-npm-Publishes the unscoped `machinaos` package to the public npm registry.+Publishes the unscoped `machina` package to the public npm registry.```npm install --ignore-scripts # Install deps without running postinstall@@ -239,14 +239,14 @@ Uses `NODE_AUTH_TOKEN` from `secrets.NPM_TOKEN`. Registry URL: `https://registry### Job: publish-github-packages-Publishes the scoped `@trohitg/machinaos` package to GitHub Packages.+Publishes the scoped `@trohitg/machina` package to GitHub Packages.Requires `packages: write` permission. Before publishing, an inline Node.js script rewrites `package.json`:```javascript// Executed at build time to scope the package name:const pkg = require('./package.json');-pkg.name = '@trohitg/machinaos';+pkg.name = '@trohitg/machina';pkg.publishConfig = { registry: 'https://npm.pkg.github.com' };require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2));```@@ -312,7 +312,7 @@ Uses `MINTLIFY_TOKEN` secret for authentication.- **`fail-fast: false` in test-install**: All 6 OS/Node combinations run to completion, giving visibility into platform-specific failures even when one platform fails.- **Docker layer caching via GHA**: `cache-from: type=gha` reuses layers across runs, reducing Docker build times.- **Scoped `docker-build.yml`**: Prevents full Docker rebuild on every PR -- only triggers when Dockerfile or compose files change.-- **Dual npm publish**: Unscoped `machinaos` for public npm, scoped `@trohitg/machinaos` for GitHub Packages. The scoped name is rewritten at publish time, not in source.+- **Dual npm publish**: Unscoped `machina` for public npm, scoped `@trohitg/machina` for GitHub Packages. The scoped name is rewritten at publish time, not in source.---diff --git a/docs-internal/onboarding.md b/docs-internal/onboarding.mdnew file mode 100644index 00000000..ad6e5f37--- /dev/null+++ b/docs-internal/onboarding.md@@ -0,0 +1,283 @@+# Onboarding Service++## Overview++The onboarding service provides a multi-step welcome wizard that appears after a user's first launch, guiding them through platform capabilities, key concepts, API key setup, UI layout, and getting started. It is database-backed, skippable, resumable, and replayable from Settings.++## Architecture++```+┌────────────────────────────────────────────────────────────────┐+│ Dashboard.tsx │+│ ┌────────────────────────────────────────────────────────┐ │+│ │ OnboardingWizard.tsx │ │+│ │ ┌────────────────────────────────────────────────┐ │ │+│ │ │ useOnboarding(reopenTrigger) │ │ │+│ │ │ - Checks onboarding_completed via WebSocket │ │ │+│ │ │ - Manages step navigation + persistence │ │ │+│ │ └───────────────┬────────────────────────────────┘ │ │+│ │ │ │ │+│ │ ┌───────┬───────┼───────┬──────────┐ │ │+│ │ │Step 0 │Step 1 │Step 2 │Step 3 │Step 4 │ │+│ │ │Welcome│Concept│APIKey │Canvas │GetStarted │ │+│ │ └───────┴───────┴───────┴──────────┘ │ │+│ │ │ │+│ │ Modal (Radix UI) + Steps (Ant Design) │ │+│ └────────────────────────────────────────────────────────┘ │+│ │+│ SettingsPanel.tsx → "Replay Welcome Guide" button │+│ └── onReplayOnboarding → increments reopenTrigger │+└────────────────────────────────────────────────────────────────┘+ │ │+ │ WebSocket │ WebSocket+ ▼ ▼+┌──────────────────────────────────────────────────────────────┐+│ server/routers/websocket.py │+│ - get_user_settings → returns onboarding_completed, step │+│ - save_user_settings → persists onboarding_completed, step │+│ │+│ server/core/database.py │+│ - _migrate_user_settings() adds columns + marks existing │+│ users (examples_loaded=1) as onboarding_completed=1 │+│ │+│ server/models/database.py │+│ - UserSettings.onboarding_completed: bool │+│ - UserSettings.onboarding_step: int │+└──────────────────────────────────────────────────────────────┘+```++## Database Schema++### UserSettings Fields++| Field | Type | Default | Description |+|-------|------|---------|-------------|+| `onboarding_completed` | `bool` | `False` | Whether onboarding was completed or skipped |+| `onboarding_step` | `int` | `0` | Last completed step (for resuming mid-wizard) |++### Migration++In `server/core/database.py` `_migrate_user_settings()`:++```python+if "onboarding_completed" not in columns:+ await conn.execute(text(+ "ALTER TABLE user_settings ADD COLUMN onboarding_completed BOOLEAN DEFAULT 0"+ ))+ # Existing users (examples_loaded=1) skip onboarding+ await conn.execute(text(+ "UPDATE user_settings SET onboarding_completed = 1 WHERE examples_loaded = 1"+ ))++if "onboarding_step" not in columns:+ await conn.execute(text(+ "ALTER TABLE user_settings ADD COLUMN onboarding_step INTEGER DEFAULT 0"+ ))+```++**Existing user handling**: The migration marks all rows with `examples_loaded=1` as `onboarding_completed=1`, so returning users never see the wizard.++## Frontend File Structure++```+client/src/+├── components/+│ └── onboarding/+│ ├── OnboardingWizard.tsx # Main wizard modal orchestrator+│ └── steps/+│ ├── WelcomeStep.tsx # Step 0: Platform intro+│ ├── ConceptsStep.tsx # Step 1: Nodes, Edges, Agents, Skills, Modes+│ ├── ApiKeyStep.tsx # Step 2: AI provider key setup+│ ├── CanvasStep.tsx # Step 3: UI layout tour+│ └── GetStartedStep.tsx # Step 4: First workflow tips+└── hooks/+ └── useOnboarding.ts # State management + WebSocket persistence+```++## Components++### useOnboarding Hook++**Location**: `client/src/hooks/useOnboarding.ts`++Custom hook managing the full onboarding lifecycle:++```typescript+export const useOnboarding = (reopenTrigger?: number) => {+ // Returns:+ // - isVisible: boolean - Whether wizard should render+ // - currentStep: number - Active step index (0-4)+ // - isCompleted: boolean - Whether already completed/skipped+ // - isLoading: boolean - WebSocket check in progress+ // - hasChecked: boolean - Initial check done+ // - totalSteps: number - Always 5+ // - nextStep(): void - Advance to next step (or complete if last)+ // - prevStep(): void - Go back one step+ // - skip(): void - Skip onboarding entirely+ // - complete(): void - Mark as completed+};+```++**Key behaviors**:+- On WebSocket connect, calls `get_user_settings` to check `onboarding_completed` (once, using `hasCheckedRef`)+- Each step transition calls `save_user_settings` to persist progress+- `reopenTrigger` prop change resets state and reopens wizard from step 0+- StrictMode-safe via `hasCheckedRef` pattern (same as Dashboard.tsx)++### OnboardingWizard++**Location**: `client/src/components/onboarding/OnboardingWizard.tsx`++**Props**:+| Prop | Type | Description |+|------|------|-------------|+| `onOpenCredentials` | `() => void` | Opens CredentialsModal (passed from Dashboard) |+| `reopenTrigger` | `number?` | Incrementing counter triggers wizard reopen |++**UI Structure**:+- Uses existing `Modal` component (`maxWidth="680px"`, `maxHeight="85vh"`)+- Ant Design `Steps` component for progress indicator+- Step content rendered via switch on `currentStep`+- Footer: "Skip for now" (left) | "Back" + "Next"/"Start Building" (right)+- Button colors: Next = `dracula.purple`, final "Start Building" = `dracula.green`+- Only renders when `isVisible && hasChecked && !isLoading`++### Step Components++All steps use Ant Design components (`Typography`, `Card`, `Tag`, `Space`, `Button`, `Alert`, `Row`, `Col`) and `@ant-design/icons` for consistent theming.++| Step | Component | Title | Purpose | Ant Design Components |+|------|-----------|-------|---------|----------------------|+| 0 | `WelcomeStep` | Welcome to MachinaOs | Platform intro + feature highlights | `Card`, `Row`, `Col`, `Typography` |+| 1 | `ConceptsStep` | Key Concepts | Nodes, Edges, Agents, Skills, Normal/Dev Mode | `Space`, `Typography` |+| 2 | `ApiKeyStep` | API Key Setup | Provider list + "Open Credentials" button | `Button`, `Alert`, `Space` |+| 3 | `CanvasStep` | Canvas Tour | Visual UI layout diagram + shortcuts | `Tag`, `Space`, `Typography` |+| 4 | `GetStartedStep` | Get Started | Example workflows, quick recipe, tips | `Card`, `Tag`, `Space` |++**ApiKeyStep** accepts an `onOpenCredentials` prop to link to the existing CredentialsModal without duplicating key input logic.++## Integration Points++### Dashboard.tsx++```typescript+// State for replay trigger+const [onboardingReopenTrigger, setOnboardingReopenTrigger] = React.useState(0);++// SettingsPanel gets replay callback+<SettingsPanel+ onReplayOnboarding={() => {+ setSettingsOpen(false);+ setOnboardingReopenTrigger(prev => prev + 1);+ }}+/>++// OnboardingWizard rendered after CredentialsModal+<OnboardingWizard+ onOpenCredentials={() => setCredentialsOpen(true)}+ reopenTrigger={onboardingReopenTrigger}+/>+```++### SettingsPanel.tsx++Added `onReplayOnboarding?: () => void` prop and a "Help" section with:+- `QuestionCircleOutlined` icon header+- "Replay Welcome Guide" button styled with `dracula.cyan`+- Description text++## WebSocket Handlers++No new handlers were needed. The onboarding system reuses existing generic handlers:++| Handler | Usage |+|---------|-------|+| `get_user_settings` | Check `onboarding_completed` and `onboarding_step` on connect |+| `save_user_settings` | Persist step progress on each navigation, skip, or complete |++## Lifecycle++### First Launch (New User)++1. User opens app, WebSocket connects+2. `useOnboarding` calls `get_user_settings` -- no settings exist yet+3. `onboarding_completed` defaults to `false`, `onboarding_step` defaults to `0`+4. Wizard opens at step 0+5. User navigates steps -- each transition saves via `save_user_settings`+6. On "Start Building" or "Skip for now", `onboarding_completed` set to `true`+7. Wizard closes, does not reappear on refresh++### Existing User (Database Migration)++1. Server starts, `_migrate_user_settings()` runs+2. Adds `onboarding_completed` column, sets to `1` where `examples_loaded = 1`+3. User opens app, `useOnboarding` checks -- sees `onboarding_completed = true`+4. Wizard does not appear++### Resume Mid-Wizard++1. User advances to step 3, closes browser+2. `onboarding_step = 3` was saved on last navigation+3. User reopens app, `useOnboarding` reads `step = 3, completed = false`+4. Wizard opens at step 3++### Replay from Settings++1. User opens Settings, clicks "Replay Welcome Guide"+2. `onReplayOnboarding()` callback fires:+ - Closes SettingsPanel+ - Increments `onboardingReopenTrigger`+3. `useOnboarding` detects trigger change:+ - Resets `hasCheckedRef` to allow re-check+ - Sets `isVisible = true, currentStep = 0`+4. Wizard opens from step 0++## Edge Cases++| Scenario | Behavior |+|----------|----------|+| Auth disabled (`VITE_AUTH_ENABLED=false`) | Works unchanged -- reads from `user_id="default"` |+| WebSocket not connected yet | Hook waits for `isConnected`, `isLoading=true` prevents render |+| Browser closed mid-wizard | `onboarding_step` saved on each transition, resumes from last step |+| Multiple tabs | Completing in one tab doesn't update others until refresh |+| Replay from Settings | Resets backend state and reopens wizard from step 0 |+| Fresh database (no machina.db) | Onboarding appears after first WebSocket connect |++## Verification Checklist++1. **Fresh database**: Delete `server/machina.db`, start server -- wizard appears+2. **Step navigation**: Click through all 5 steps -- progress bar updates, Back/Next work+3. **Skip**: Click "Skip for now" -- wizard closes, doesn't reappear on refresh+4. **Resume**: Advance to step 3, close browser, reopen -- wizard resumes at step 3+5. **Complete**: Finish all steps via "Start Building" -- wizard doesn't reappear+6. **API Key step**: Click "Open Credentials" button -- CredentialsModal opens+7. **Existing user migration**: With existing `machina.db` where `examples_loaded=1` -- onboarding does NOT appear+8. **Theme support**: Toggle dark/light mode -- all onboarding UI adapts correctly+9. **Replay**: Open Settings, click "Replay Welcome Guide" -- wizard reopens from step 0+10. **TypeScript**: `npx tsc --noEmit` passes clean++## Key Files++| File | Description |+|------|-------------|+| `client/src/hooks/useOnboarding.ts` | Onboarding state hook with WebSocket persistence |+| `client/src/components/onboarding/OnboardingWizard.tsx` | Main wizard modal with Ant Design Steps |+| `client/src/components/onboarding/steps/WelcomeStep.tsx` | Step 0: Platform introduction |+| `client/src/components/onboarding/steps/ConceptsStep.tsx` | Step 1: Key concepts (Nodes, Edges, Agents) |+| `client/src/components/onboarding/steps/ApiKeyStep.tsx` | Step 2: API key setup with Credentials link |+| `client/src/components/onboarding/steps/CanvasStep.tsx` | Step 3: UI layout diagram + shortcuts |+| `client/src/components/onboarding/steps/GetStartedStep.tsx` | Step 4: Getting started tips |+| `client/src/Dashboard.tsx` | Integration: renders wizard + passes replay trigger |+| `client/src/components/ui/SettingsPanel.tsx` | Replay button in Help section |+| `server/models/database.py` | `UserSettings.onboarding_completed`, `onboarding_step` fields |+| `server/core/database.py` | Migration + CRUD for onboarding fields |++## Adding New Steps++To add a new onboarding step:++1. Create `client/src/components/onboarding/steps/NewStep.tsx` using Ant Design components+2. Import in `OnboardingWizard.tsx` and add to the `renderStep()` switch+3. Add entry to `stepItems` array+4. Update `TOTAL_STEPS` in `useOnboarding.ts`+5. No backend changes needed (step index is just a number)diff --git a/install.ps1 b/install.ps1index 354f0e58..ee708f08 100644--- a/install.ps1+++ b/install.ps1@@ -190,7 +190,7 @@ function Main {Write-Color "============================================" "Green"Write-Host ""Write-Host " Start MachinaOS:"- Write-Host " machinaos start"+ Write-Host " machina start"Write-Host ""Write-Host " Open in browser:"Write-Host " http://localhost:3000"diff --git a/install.sh b/install.shindex 58758b24..19bedacc 100755--- a/install.sh+++ b/install.sh@@ -286,7 +286,7 @@ main() {echo -e "${GREEN}============================================${NC}"echo ""echo " Start MachinaOS:"- echo " machinaos start"+ echo " machina start"echo ""echo " Open in browser:"echo " http://localhost:3000"diff --git a/package-lock.json b/package-lock.jsonindex c524cc87..322c2a1a 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "machinaos",- "version": "0.0.31",+ "version": "0.0.35","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "machinaos",- "version": "0.0.31",+ "version": "0.0.35","hasInstallScript": true,"license": "MIT","workspaces": [@@ -15,12 +15,11 @@"dependencies": {"concurrently": "^9.2.1","cross-env": "^7.0.3",- "find-process": "^1.4.11","rimraf": "^6.0.1","whatsapp-rpc": "^0.0.10"},"bin": {- "machinaos": "bin/cli.js"+ "machina": "bin/cli.js"},"engines": {"node": ">=20.0.0"@@ -5981,29 +5980,6 @@"url": "https://github.com/sponsors/sindresorhus"}},- "node_modules/find-process": {- "version": "1.4.11",- "resolved": "https://registry.npmjs.org/find-process/-/find-process-1.4.11.tgz",- "integrity": "sha512-mAOh9gGk9WZ4ip5UjV0o6Vb4SrfnAmtsFNzkMRH9HQiFXVQnDyQFrSHTK5UoG6E+KV+s+cIznbtwpfN41l2nFA==",- "license": "MIT",- "dependencies": {- "chalk": "~4.1.2",- "commander": "^12.1.0",- "loglevel": "^1.9.2"- },- "bin": {- "find-process": "bin/find-process.js"- }- },- "node_modules/find-process/node_modules/commander": {- "version": "12.1.0",- "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",- "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==",- "license": "MIT",- "engines": {- "node": ">=18"- }- },"node_modules/find-root": {"version": "1.1.0","resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz",@@ -7108,19 +7084,6 @@"integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==","license": "MIT"},- "node_modules/loglevel": {- "version": "1.9.2",- "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.9.2.tgz",- "integrity": "sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==",- "license": "MIT",- "engines": {- "node": ">= 0.6.0"- },- "funding": {- "type": "tidelift",- "url": "https://tidelift.com/funding/github/npm/loglevel"- }- },"node_modules/longest-streak": {"version": "3.1.0","resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",diff --git a/package.json b/package.jsonindex cbb6569f..98450c56 100644--- a/package.json+++ b/package.json@@ -27,7 +27,7 @@"url": "https://github.com/trohitg/MachinaOS/issues"},"bin": {- "machinaos": "./bin/cli.js"+ "machina": "./bin/cli.js"},"engines": {"node": ">=20.0.0"@@ -61,7 +61,7 @@],"scripts": {"start": "node scripts/start.js",- "start:daemon": "node scripts/start.js --daemon",+ "dev": "node scripts/dev.js","start:temporal": "cross-env TEMPORAL_ENABLED=true node scripts/start.js","client:start": "cd client && npm run start","python:start": "cd server && uv run uvicorn main:app --host 127.0.0.1 --port 3010 --reload --reload-dir . --reload-exclude \"*.pyc\" --reload-exclude \"__pycache__\" --log-level warning",@@ -101,7 +101,6 @@"dependencies": {"concurrently": "^9.2.1","cross-env": "^7.0.3",- "find-process": "^1.4.11","rimraf": "^6.0.1","whatsapp-rpc": "^0.0.10"}diff --git a/scripts/build.js b/scripts/build.jsindex a8549ae3..9ec6cbd2 100755--- a/scripts/build.js+++ b/scripts/build.js@@ -24,6 +24,9 @@ const isCI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';// Ensure Python UTF-8 encodingprocess.env.PYTHONUTF8 = '1';+// Tell postinstall.js to skip install.js -- build.js handles everything+process.env.MACHINAOS_BUILDING = 'true';+// Skip build entirely in CI (workflows handle this)if (isCI && isPostInstall) {console.log('CI environment detected, skipping postinstall build.');@@ -143,33 +146,28 @@ try {console.log('[0/6] Created .env from template');}- // Step 1: Install root dependencies (skip if postinstall - npm already did this)+ // Step 1: Install root + client dependencies (workspaces handles both)if (!isPostInstall) {- console.log('[1/5] Installing root dependencies...');+ console.log('[1/4] Installing dependencies...');npmInstall(ROOT);} else {- console.log('[1/5] Root dependencies already installed by npm');+ console.log('[1/4] Dependencies already installed by npm');}- // Step 2: Install client dependencies- console.log('[2/5] Installing client dependencies...');- npmInstall(resolve(ROOT, 'client'));-- // Step 3: Build client- console.log('[3/5] Building client...');+ // Step 2: Build client+ console.log('[2/4] Building client...');run('npm run build', resolve(ROOT, 'client'));- // Step 4: Install Python dependencies- console.log('[4/5] Installing Python dependencies...');+ // Step 3: Install Python dependencies+ console.log('[3/4] Installing Python dependencies...');const serverDir = resolve(ROOT, 'server');- // Check if .venv exists, skip creation if it doesif (!existsSync(resolve(serverDir, '.venv'))) {run('uv venv', serverDir);}run('uv sync', serverDir);- // Step 5: Verify WhatsApp RPC package- console.log('[5/5] Verifying WhatsApp RPC...');+ // Step 4: Verify WhatsApp RPC package+ console.log('[4/4] Verifying WhatsApp RPC...');run('whatsapp-rpc status', ROOT);console.log('\nBuild complete.');diff --git a/scripts/daemon.js b/scripts/daemon.jsindex f134d303..51fe49e8 100755--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -251,7 +251,7 @@ function macGeneratePlist() {<plist version="1.0"><dict><key>Label</key>- <string>com.machinaos.backend</string>+ <string>com.machina.backend</string><key>ProgramArguments</key><array><string>${venvPath}/bin/gunicorn</string>@@ -280,7 +280,7 @@ function macGeneratePlist() {}function macGetPlistPath() {- return resolve(homedir(), 'Library', 'LaunchAgents', 'com.machinaos.backend.plist');+ return resolve(homedir(), 'Library', 'LaunchAgents', 'com.machina.backend.plist');}function macInstall() {@@ -331,7 +331,7 @@ function macUninstall() {}function macStatus() {- run('launchctl list | grep machinaos', { ignoreError: true });+ run('launchctl list | grep machina', { ignoreError: true });}function macStart() {@@ -376,7 +376,7 @@ Platform: ${isWindows ? 'Windows (NSSM)' : isMac ? 'macOS (launchd)' : 'Linux (sExamples:node scripts/service.js install- node scripts/service.js install --dir=/opt/machinaos --user=machina+ node scripts/service.js install --dir=/opt/machina --user=machinanode scripts/service.js statusnode scripts/service.js restart`);diff --git a/scripts/dev.js b/scripts/dev.jsnew file mode 100644index 00000000..7189f38d--- /dev/null+++ b/scripts/dev.js@@ -0,0 +1,108 @@+#!/usr/bin/env node+/**+ * Development server for MachinaOS.+ * Vite HMR, uvicorn hot-reload, full log output.+ * Usage: machina dev [--daemon] [--skip-whatsapp]+ */+import { spawn } from 'child_process';+import { existsSync, rmSync } from 'fs';+import { resolve } from 'path';+import {+ ROOT,+ getPlatformName,+ loadEnvConfig,+ ensureEnvFile,+ killPort,+ createLogger,+} from './utils.js';++const START_TIME = Date.now();+const log = createLogger(START_TIME);++// Parse command line arguments+const args = process.argv.slice(2);+const isDaemonMode = args.includes('--daemon');+const skipWhatsApp = args.includes('--skip-whatsapp');++async function main() {+ // Check if build has been run+ const rootNodeModules = resolve(ROOT, 'node_modules');+ const pythonVenv = resolve(ROOT, 'server', '.venv');+ if (!existsSync(rootNodeModules) || !existsSync(pythonVenv)) {+ console.error('\nError: Project not built. Run "npm run build" first.\n');+ process.exit(1);+ }++ const config = loadEnvConfig();+ process.env.PYTHONUTF8 = '1';++ console.log('\n=== MachinaOS Starting ===\n');+ log(`Platform: ${getPlatformName()}`);+ log(`Mode: ${isDaemonMode ? 'Daemon (Gunicorn)' : 'Development (uvicorn)'}`);+ log(`Ports: ${config.allPorts.join(', ')}`);+ log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}`);+ log(`WhatsApp: ${skipWhatsApp ? 'skipped' : 'enabled'}`);++ // Create .env if not exists+ if (ensureEnvFile()) {+ log('Ensured .env file exists');+ }++ // Free ports+ log('Freeing ports...');+ for (const port of config.allPorts) {+ const result = await killPort(port);+ if (result.killed.length > 0) {+ log(` Port ${port}: ${result.portFree ? 'Freed' : 'Warning - could not free'} (PIDs: ${result.killed.join(', ')})`);+ } else {+ log(` Port ${port}: Already free`);+ }+ }++ // Clear Vite dependency cache to prevent "Outdated Optimize Dep" errors+ const viteCachePath = resolve(ROOT, 'client', 'node_modules', '.vite');+ if (existsSync(viteCachePath)) {+ try {+ rmSync(viteCachePath, { recursive: true, force: true });+ log('Cleared Vite cache');+ } catch (err) {+ log(`Warning: Could not clear Vite cache: ${err.message}`);+ }+ }++ // Start services+ log('Starting services...');+ log('Press Ctrl+C to stop\n');++ const clientDist = resolve(ROOT, 'client', 'dist', 'index.html');+ const hasVite = existsSync(resolve(ROOT, 'node_modules', 'vite'))+ || existsSync(resolve(ROOT, 'client', 'node_modules', 'vite'));+ const isProduction = existsSync(clientDist) && !hasVite;+ log(`Mode: ${isProduction ? 'Production' : 'Development'}`);++ const services = [];+ if (isProduction) {+ services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);+ } else {+ services.push('npm:client:start');+ }+ services.push(isDaemonMode ? 'npm:python:daemon' : 'npm:python:start');+ if (!skipWhatsApp) services.push('npm:whatsapp:api');+ if (config.temporalEnabled) services.push('npm:temporal:worker');++ const proc = spawn('npx', ['concurrently', '--raw', '--kill-others-on-fail', ...services], {+ cwd: ROOT,+ stdio: 'inherit',+ shell: true,+ env: { ...process.env, FORCE_COLOR: '1' }+ });++ process.on('SIGINT', () => proc.kill('SIGINT'));+ process.on('SIGTERM', () => proc.kill('SIGTERM'));+ proc.on('close', (code) => {+ console.log('\nServices stopped.');+ process.exit(code || 0);+ });+}++main().catch(console.error);diff --git a/scripts/port_kill.py b/scripts/port_kill.pynew file mode 100644index 00000000..506cd03a--- /dev/null+++ b/scripts/port_kill.py@@ -0,0 +1,187 @@+#!/usr/bin/env python3+"""+Cross-platform port and process management using psutil.+Uses native OS APIs -- no shell pipes, terminal-agnostic.++Usage:+ python port_kill.py --kill-port 3000 3010 9400 3020+ python port_kill.py --kill-machina --root /path/to/project [--exclude clean.js]+ python port_kill.py --kill-pattern temporal --root /path/to/project+ python port_kill.py --check-port 3010+"""+import argparse+import json+import os+import subprocess+import sys++try:+ import psutil+except ImportError:+ # psutil not installed -- exit non-zero so Node.js callers fall through to native commands+ print(json.dumps({"error": "psutil not installed", "results": []}), file=sys.stderr)+ sys.exit(1)+++def find_pids_by_port(port):+ """Find PIDs using a port via psutil native APIs."""+ pids = set()+ try:+ for conn in psutil.net_connections(kind="inet"):+ if conn.laddr and conn.laddr.port == port and conn.pid:+ pids.add(conn.pid)+ except psutil.AccessDenied:+ # macOS: net_connections() requires root, fall back to lsof+ if sys.platform == "darwin":+ try:+ output = subprocess.check_output(+ ["lsof", "-ti", f":{port}"],+ text=True,+ stderr=subprocess.DEVNULL,+ )+ for line in output.strip().splitlines():+ try:+ pids.add(int(line.strip()))+ except ValueError:+ pass+ except (subprocess.CalledProcessError, FileNotFoundError):+ pass+ except OSError:+ pass+ return pids+++def kill_pid(pid, graceful_timeout=3):+ """Kill a process: terminate first, then force kill after timeout."""+ try:+ proc = psutil.Process(pid)+ name = proc.name()+ proc.terminate()+ try:+ proc.wait(timeout=graceful_timeout)+ except psutil.TimeoutExpired:+ proc.kill()+ return {"pid": pid, "name": name, "killed": True}+ except psutil.NoSuchProcess:+ return {"pid": pid, "name": "", "killed": False}+ except psutil.AccessDenied:+ return {"pid": pid, "name": "", "killed": False}+++def cmd_kill_port(ports):+ """Kill all processes on the given ports."""+ results = []+ my_pid = os.getpid()+ for port in ports:+ pids = find_pids_by_port(port)+ killed = []+ for pid in pids:+ if pid == my_pid:+ continue+ r = kill_pid(pid)+ if r["killed"]:+ killed.append(r)+ results.append({"port": port, "killed": killed})+ return results+++def cmd_check_port(ports):+ """Check which ports are in use."""+ results = []+ for port in ports:+ pids = find_pids_by_port(port)+ in_use = []+ for pid in pids:+ try:+ proc = psutil.Process(pid)+ in_use.append({"pid": pid, "name": proc.name()})+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ in_use.append({"pid": pid, "name": ""})+ results.append({"port": port, "in_use": in_use})+ return results+++def cmd_kill_machina(root_dir, exclude_script=None):+ """Kill Python/Node processes belonging to the MachinaOS project."""+ root_norm = root_dir.lower().replace("\\", "/")+ killed = []+ my_pid = os.getpid()+ target_names = {"python", "python3", "python.exe", "node", "node.exe"}++ for proc in psutil.process_iter(["pid", "name", "cmdline"]):+ try:+ name = (proc.info["name"] or "").lower()+ if name not in target_names:+ continue+ cmdline = proc.info.get("cmdline") or []+ cmd = " ".join(cmdline).lower().replace("\\", "/")+ if root_norm not in cmd:+ continue+ if exclude_script and exclude_script.lower() in cmd:+ continue+ if proc.pid == my_pid:+ continue+ proc.kill()+ killed.append({"pid": proc.pid, "name": name})+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ pass++ return killed+++def cmd_kill_pattern(pattern, root_dir=None):+ """Kill processes matching a name pattern, optionally scoped to project root."""+ pattern_lower = pattern.lower()+ root_norm = root_dir.lower().replace("\\", "/") if root_dir else None+ killed = []+ my_pid = os.getpid()++ for proc in psutil.process_iter(["pid", "name", "cmdline"]):+ try:+ name = (proc.info["name"] or "").lower()+ cmdline = proc.info.get("cmdline") or []+ cmd = " ".join(cmdline).lower().replace("\\", "/")+ if pattern_lower not in name and pattern_lower not in cmd:+ continue+ if root_norm and root_norm not in cmd:+ continue+ if proc.pid == my_pid:+ continue+ proc.kill()+ killed.append({"pid": proc.pid, "name": name})+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ pass++ return killed+++def main():+ parser = argparse.ArgumentParser(description="Cross-platform port/process management")+ parser.add_argument("--kill-port", nargs="+", type=int, help="Kill processes on these ports")+ parser.add_argument("--check-port", nargs="+", type=int, help="Check if ports are in use")+ parser.add_argument("--kill-machina", action="store_true", help="Kill MachinaOS project processes")+ parser.add_argument("--kill-pattern", type=str, default=None, help="Kill processes matching name pattern")+ parser.add_argument("--root", type=str, default=".", help="Project root directory")+ parser.add_argument("--exclude", type=str, default=None, help="Script name to exclude from killing")++ args = parser.parse_args()++ if args.kill_port:+ results = cmd_kill_port(args.kill_port)+ print(json.dumps({"action": "kill_port", "results": results}))+ elif args.check_port:+ results = cmd_check_port(args.check_port)+ print(json.dumps({"action": "check_port", "results": results}))+ elif args.kill_machina:+ killed = cmd_kill_machina(args.root, args.exclude)+ print(json.dumps({"action": "kill_machina", "killed": killed}))+ elif args.kill_pattern:+ killed = cmd_kill_pattern(args.kill_pattern, args.root)+ print(json.dumps({"action": "kill_pattern", "killed": killed}))+ else:+ parser.print_help()+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex c2299ac4..518e6ad2 100755--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -20,6 +20,7 @@ function fixPermissions() {const files = [resolve(ROOT, 'bin/cli.js'),resolve(ROOT, 'scripts/start.js'),+ resolve(ROOT, 'scripts/dev.js'),resolve(ROOT, 'scripts/stop.js'),resolve(ROOT, 'scripts/build.js'),resolve(ROOT, 'scripts/clean.js'),@@ -39,12 +40,19 @@ function fixPermissions() {}const isCI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';+const isBuilding = process.env.MACHINAOS_BUILDING === 'true';if (isCI) {console.log('CI detected, skipping postinstall.');process.exit(0);}+if (isBuilding) {+ // build.js is orchestrating -- skip install.js to avoid duplicate work+ fixPermissions();+ process.exit(0);+}+console.log('');console.log('========================================');console.log(' MachinaOS - Installing...');@@ -84,7 +92,7 @@ async function main() {console.log(' MachinaOS installed successfully!');console.log('========================================');console.log('');- console.log('Run: machinaos start');+ console.log('Run: machina start');console.log('Open: http://localhost:3000');console.log('');@@ -96,7 +104,7 @@ async function main() {console.log('');console.log(`Error: ${err.message}`);console.log('');- console.log('Try: machinaos build');+ console.log('Try: machina build');console.log('');process.exit(1);}diff --git a/scripts/preinstall.js b/scripts/preinstall.jsindex ffac9ad9..3686dfe7 100755--- a/scripts/preinstall.js+++ b/scripts/preinstall.js@@ -45,9 +45,9 @@ function cleanup() {try {const entries = readdirSync(nodeModules);- // Clean .machinaos-* temp directories+ // Clean .machina-* temp directoriesfor (const name of entries) {- if (name.startsWith('.machinaos-')) {+ if (name.startsWith('.machina-')) {const fullPath = resolve(nodeModules, name);try {if (statSync(fullPath).isDirectory()) {diff --git a/scripts/start.js b/scripts/start.jsindex 89b65bb0..9baf07d5 100755--- a/scripts/start.js+++ b/scripts/start.js@@ -1,107 +1,118 @@#!/usr/bin/env node/**- * Cross-platform start script for MachinaOS services.- * Works on: Windows, macOS, Linux, WSL, Git Bash+ * Production start script for MachinaOS.+ * Clean output by default, --verbose for full logs.+ * Usage: machina start [--verbose|-v] [--skip-whatsapp]*/import { spawn } from 'child_process';-import { existsSync, rmSync } from 'fs';+import { existsSync, readFileSync } from 'fs';import { resolve } from 'path';import {ROOT,- getPlatformName,+ isWindows,loadEnvConfig,ensureEnvFile,killPort,- createLogger,} from './utils.js';-const START_TIME = Date.now();-const log = createLogger(START_TIME);--// Parse command line argumentsconst args = process.argv.slice(2);-const isDaemonMode = args.includes('--daemon');+const isVerbose = args.includes('--verbose') || args.includes('-v');const skipWhatsApp = args.includes('--skip-whatsapp');+function getVersion() {+ try {+ const pkg = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf-8'));+ return pkg.version || '0.0.0';+ } catch {+ return '0.0.0';+ }+}+async function main() {- // Check if build has been run- const rootNodeModules = resolve(ROOT, 'node_modules');- const pythonVenv = resolve(ROOT, 'server', '.venv');- if (!existsSync(rootNodeModules) || !existsSync(pythonVenv)) {- console.error('\nError: Project not built. Run "npm run build" first.\n');+ // Validate build+ if (!existsSync(resolve(ROOT, 'node_modules')) || !existsSync(resolve(ROOT, 'server', '.venv'))) {+ console.error('Error: Project not built. Run "machina build" first.');+ process.exit(1);+ }+ if (!existsSync(resolve(ROOT, 'client', 'dist', 'index.html'))) {+ console.error('Error: Client not built. Run "machina build" first.');process.exit(1);}const config = loadEnvConfig();process.env.PYTHONUTF8 = '1';-- console.log('\n=== MachinaOS Starting ===\n');- log(`Platform: ${getPlatformName()}`);- log(`Mode: ${isDaemonMode ? 'Daemon (Gunicorn)' : 'Development (uvicorn)'}`);- log(`Ports: ${config.allPorts.join(', ')}`);- log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}`);- log(`WhatsApp: ${skipWhatsApp ? 'skipped' : 'enabled'}`);-- // Create .env if not exists- if (ensureEnvFile()) {- log('Ensured .env file exists');- }+ ensureEnvFile();// Free ports- log('Freeing ports...');for (const port of config.allPorts) {- const result = await killPort(port);- if (result.killed.length > 0) {- log(` Port ${port}: ${result.portFree ? 'Freed' : 'Warning - could not free'} (PIDs: ${result.killed.join(', ')})`);- } else {- log(` Port ${port}: Already free`);- }+ await killPort(port);}- // Clear Vite dependency cache to prevent "Outdated Optimize Dep" errors- const viteCachePath = resolve(ROOT, 'client', 'node_modules', '.vite');- if (existsSync(viteCachePath)) {- try {- rmSync(viteCachePath, { recursive: true, force: true });- log('Cleared Vite cache');- } catch (err) {- log(`Warning: Could not clear Vite cache: ${err.message}`);- }- }-- // Start services- log('Starting services...');- log('Press Ctrl+C to stop\n');-- const clientDist = resolve(ROOT, 'client', 'dist', 'index.html');- const hasVite = existsSync(resolve(ROOT, 'node_modules', 'vite'))- || existsSync(resolve(ROOT, 'client', 'node_modules', 'vite'));- const isProduction = existsSync(clientDist) && !hasVite;- log(`Mode: ${isProduction ? 'Production' : 'Development'}`);-+ // Services: static client, backend (gunicorn on Linux, uvicorn on Windows), whatsapp, temporalconst services = [];- if (isProduction) {- services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);- } else {- services.push('npm:client:start');- }- services.push(isDaemonMode ? 'npm:python:daemon' : 'npm:python:start');+ services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);+ services.push(isWindows ? 'npm:python:start' : 'npm:python:daemon');if (!skipWhatsApp) services.push('npm:whatsapp:api');if (config.temporalEnabled) services.push('npm:temporal:worker');- const proc = spawn('npx', ['concurrently', '--raw', '--kill-others-on-fail', ...services], {- cwd: ROOT,- stdio: 'inherit',- shell: true,- env: { ...process.env, FORCE_COLOR: '1' }- });+ if (isVerbose) {+ console.log('\n=== MachinaOS Starting (verbose) ===\n');+ const proc = spawn('npx', ['concurrently', '--raw', '--kill-others-on-fail', ...services], {+ cwd: ROOT,+ stdio: 'inherit',+ shell: true,+ env: { ...process.env, FORCE_COLOR: '1' },+ });++ process.on('SIGINT', () => proc.kill('SIGINT'));+ process.on('SIGTERM', () => proc.kill('SIGTERM'));+ proc.on('close', (code) => process.exit(code || 0));+ } else {+ // Clean banner+ const version = getVersion();+ console.log(`\n MachinaOS v${version}`);+ console.log(` Frontend: http://localhost:${config.clientPort}`);+ console.log(` Backend: http://localhost:${config.backendPort}`);+ console.log(` Use --verbose for full logs\n`);++ const serviceNames = ['client', 'server'];+ if (!skipWhatsApp) serviceNames.push('whatsapp');+ if (config.temporalEnabled) serviceNames.push('temporal');- process.on('SIGINT', () => proc.kill('SIGINT'));- process.on('SIGTERM', () => proc.kill('SIGTERM'));- proc.on('close', (code) => {- console.log('\nServices stopped.');- process.exit(code || 0);- });+ const proc = spawn('npx', [+ 'concurrently', '--kill-others-on-fail',+ '-n', serviceNames.join(','),+ '-c', 'blue,green,yellow,magenta',+ ...services,+ ], {+ cwd: ROOT,+ stdio: ['inherit', 'pipe', 'pipe'],+ shell: true,+ env: { ...process.env, FORCE_COLOR: '1' },+ });++ // Show only essential output: errors, ready messages, warnings+ const essential = /error|fatal|exception|failed|started|ready|listening|running|address already in use|application startup complete/i;++ proc.stdout.on('data', (data) => {+ for (const line of data.toString().split('\n')) {+ const trimmed = line.trim();+ if (trimmed && essential.test(trimmed)) {+ process.stdout.write(line + '\n');+ }+ }+ });++ // Always show stderr+ proc.stderr.on('data', (data) => process.stderr.write(data));++ process.on('SIGINT', () => proc.kill('SIGINT'));+ process.on('SIGTERM', () => proc.kill('SIGTERM'));+ proc.on('close', (code) => {+ console.log('\nServices stopped.');+ process.exit(code || 0);+ });+ }}main().catch(console.error);diff --git a/scripts/utils.js b/scripts/utils.jsindex 77425a6e..dcc952b5 100644--- a/scripts/utils.js+++ b/scripts/utils.js@@ -2,6 +2,9 @@/*** Common utilities for MachinaOS scripts.* Shared across: start.js, stop.js, clean.js, docker.js, build.js+ *+ * Port/process killing uses Python psutil exclusively (native OS APIs,+ * no shell pipes, works in all terminals including Git Bash on Windows).*/import { readFileSync, existsSync, copyFileSync } from 'fs';import { resolve, dirname } from 'path';@@ -16,24 +19,8 @@ export const ROOT = resolve(__dirname, '..');export const isWindows = process.platform === 'win32';export const isGitBash = isWindows && (process.env.MSYSTEM || process.env.SHELL?.includes('bash'));-// Lazy-loaded find-process (may not be available during clean)-let _findProcess = null;--/**- * Get find-process module, loading it lazily.- * Returns null if not available (e.g., during clean when node_modules is missing).- */-async function getFindProcess() {- if (_findProcess !== null) return _findProcess;- try {- const module = await import('find-process');- _findProcess = module.default;- return _findProcess;- } catch {- _findProcess = false; // Mark as unavailable- return null;- }-}+// Cached Python path (undefined = not checked, null = unavailable, string = path)+let _pythonCmd;/*** Get human-readable platform name.@@ -76,20 +63,17 @@ export function loadEnvConfig() {}}+ const clientPort = parseInt(env.VITE_CLIENT_PORT) || 3000;+ const backendPort = parseInt(env.PYTHON_BACKEND_PORT) || 3010;+ const whatsappPort = parseInt(env.WHATSAPP_RPC_PORT) || 9400;+ const nodejsPort = parseInt(env.NODEJS_EXECUTOR_PORT) || 3020;+return {raw: env,- ports: {- client: parseInt(env.VITE_CLIENT_PORT) || 3000,- backend: parseInt(env.PYTHON_BACKEND_PORT) || 3010,- whatsapp: parseInt(env.WHATSAPP_RPC_PORT) || 9400,- nodejs: parseInt(env.NODEJS_EXECUTOR_PORT) || 3020,- },- allPorts: [- parseInt(env.VITE_CLIENT_PORT) || 3000,- parseInt(env.PYTHON_BACKEND_PORT) || 3010,- parseInt(env.WHATSAPP_RPC_PORT) || 9400,- parseInt(env.NODEJS_EXECUTOR_PORT) || 3020,- ],+ ports: { client: clientPort, backend: backendPort, whatsapp: whatsappPort, nodejs: nodejsPort },+ allPorts: [clientPort, backendPort, whatsappPort, nodejsPort],+ clientPort,+ backendPort,temporalEnabled: env.TEMPORAL_ENABLED?.toLowerCase() === 'true',redisEnabled: ['true', '1', 'yes'].includes(env.REDIS_ENABLED?.toLowerCase()),};@@ -113,179 +97,198 @@ export function ensureEnvFile() {}/**- * Kill process on port using native commands (fallback when find-process unavailable).- * @returns {{ killed: boolean }}+ * Check if a Python executable has psutil available.+ * If not, attempts to install it via pip.+ * @returns {boolean}*/-function killPortNative(port) {+function ensurePsutil(pythonCmd) {try {- if (isWindows) {- // Windows: use netstat + taskkill- const output = execSync(`netstat -ano | findstr :${port}`, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });- const lines = output.trim().split('\n');- const pids = new Set();- for (const line of lines) {- const parts = line.trim().split(/\s+/);- const pid = parts[parts.length - 1];- if (pid && /^\d+$/.test(pid) && pid !== '0') {- pids.add(pid);- }- }- for (const pid of pids) {- try {- execSync(`taskkill /F /PID ${pid}`, { stdio: 'pipe' });- } catch {}- }- return { killed: pids.size > 0 };- } else {- // Unix: use lsof + kill- const output = execSync(`lsof -ti:${port}`, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });- const pids = output.trim().split('\n').filter(Boolean);- for (const pid of pids) {- try {- execSync(`kill -9 ${pid}`, { stdio: 'pipe' });- } catch {}- }- return { killed: pids.length > 0 };- }+ execSync(`${pythonCmd} -c "import psutil"`, { timeout: 5000, stdio: 'pipe' });+ return true;} catch {- return { killed: false };+ try {+ execSync(`${pythonCmd} -m pip install psutil>=6.0.0 --quiet`, { timeout: 30000, stdio: 'pipe' });+ return true;+ } catch {+ return false;+ }}}/**- * Kill all processes on a specific port.- * Uses find-process if available, falls back to native commands.- * @returns {Promise<{ killed: number[], portFree: boolean }>}+ * Find a Python executable that has psutil available.+ * Checks venv first, then system. Attempts pip install if psutil missing.+ * Result is cached -- only runs once per process.+ * @returns {string|null}*/-export async function killPort(port) {- const findProcess = await getFindProcess();+function findPython() {+ if (_pythonCmd !== undefined) return _pythonCmd;- if (!findProcess) {- // Fallback to native commands- const result = killPortNative(port);- return { killed: result.killed ? [0] : [], portFree: result.killed };- }+ // Check project venv first+ const venvPython = isWindows+ ? resolve(ROOT, 'server', '.venv', 'Scripts', 'python.exe')+ : resolve(ROOT, 'server', '.venv', 'bin', 'python3');+ try {+ execSync(`"${venvPython}" --version`, { timeout: 5000, stdio: 'pipe' });+ if (ensurePsutil(`"${venvPython}"`)) {+ _pythonCmd = venvPython;+ return _pythonCmd;+ }+ } catch {}- const procs = await findProcess('port', port);- if (procs.length === 0) return { killed: [], portFree: true };+ // Fall back to system python+ const systemCmd = isWindows ? 'python' : 'python3';+ try {+ execSync(`${systemCmd} --version`, { timeout: 5000, stdio: 'pipe' });+ if (ensurePsutil(systemCmd)) {+ _pythonCmd = systemCmd;+ return _pythonCmd;+ }+ } catch {}- const pids = procs.map(p => p.pid);+ _pythonCmd = null;+ return null;+}- // SIGTERM first (graceful)- for (const pid of pids) {- try { process.kill(pid, 'SIGTERM'); } catch {}- }- await sleep(300);+/**+ * Native port killing fallback (no Python required).+ * Runs netstat/lsof WITHOUT shell pipes (the pipes caused Git Bash hangs).+ * Parses output in JavaScript instead.+ * @returns {{ killed: number[], portFree: boolean }}+ */+function killPortNative(port) {+ const killed = [];+ try {+ let pids;+ if (isWindows) {+ // netstat -ano alone does NOT hang -- the pipe to findstr was the problem+ const output = execSync('netstat -ano', { encoding: 'utf-8', timeout: 10000, stdio: ['pipe', 'pipe', 'pipe'] });+ pids = new Set();+ const portStr = `:${port}`;+ for (const line of output.split('\n')) {+ if (!line.includes(portStr)) continue;+ // Format: " TCP 0.0.0.0:3010 0.0.0.0:0 LISTENING 1234"+ const parts = line.trim().split(/\s+/);+ if (parts.length >= 5) {+ const localAddr = parts[1] || '';+ if (localAddr.endsWith(portStr)) {+ const pid = parseInt(parts[parts.length - 1]);+ if (pid > 0) pids.add(pid);+ }+ }+ }+ } else {+ // macOS/Linux: lsof -ti :PORT returns PIDs directly, no pipe needed+ try {+ const output = execSync(`lsof -ti :${port}`, { encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'] });+ pids = new Set(output.trim().split('\n').map(s => parseInt(s.trim())).filter(n => n > 0));+ } catch {+ pids = new Set();+ }+ }- // SIGKILL for stubborn processes- for (const pid of pids) {- try { process.kill(pid, 'SIGKILL'); } catch {}- }- await sleep(200);+ for (const pid of pids) {+ try {+ if (isWindows) {+ execSync(`taskkill /PID ${pid} /F`, { timeout: 5000, stdio: 'pipe' });+ } else {+ execSync(`kill -9 ${pid}`, { timeout: 5000, stdio: 'pipe' });+ }+ killed.push(pid);+ } catch {}+ }+ } catch {}- const remaining = await findProcess('port', port);- return { killed: pids, portFree: remaining.length === 0 };+ return { killed, portFree: killed.length > 0 || true };}/**- * Kill processes matching a name pattern.- * @returns {Promise<number[]>} Array of killed PIDs+ * Kill all processes on a specific port.+ * Primary: Python psutil (native OS APIs, no shell pipes).+ * Fallback: netstat/lsof parsed in JS (no shell pipes either).+ * @returns {Promise<{ killed: number[], portFree: boolean }>}*/-export async function killByPattern(pattern) {- const findProcess = await getFindProcess();- if (!findProcess) return [];-- const procs = await findProcess('name', pattern);- const pids = procs.map(p => p.pid);+export async function killPort(port) {+ const python = findPython();+ if (!python) {+ return killPortNative(port);+ }- for (const pid of pids) {- try { process.kill(pid, 'SIGKILL'); } catch {}+ try {+ const scriptPath = resolve(__dirname, 'port_kill.py');+ const output = execSync(+ `"${python}" "${scriptPath}" --kill-port ${port}`,+ { encoding: 'utf-8', timeout: 15000, stdio: ['pipe', 'pipe', 'pipe'] }+ );+ const result = JSON.parse(output.trim());+ if (result.error) return killPortNative(port);+ const portResult = result.results?.[0];+ const killedList = portResult?.killed || [];+ return {+ killed: killedList.map(k => k.pid),+ portFree: true,+ };+ } catch {+ return killPortNative(port);}- return pids;}/*** Kill MachinaOS processes that may hold file locks.- * Useful before cleaning directories.* @param {string} [excludeScript] - Script name to exclude from killing (e.g., 'clean.js')* @returns {Promise<Array<{pid: number, type: string}>>}*/export async function killMachinaProcesses(excludeScript = null) {- const findProcess = await getFindProcess();- if (!findProcess) {- // Fallback: just kill by ports- return [];- }-- const killed = [];- const rootNorm = normalizePath(ROOT);+ const python = findPython();+ if (!python) return [];- // Find Python processes running from MachinaOs directory- const pythonProcs = await findProcess('name', 'python');- for (const proc of pythonProcs) {- const cmd = normalizePath(proc.cmd);- if (cmd.includes(rootNorm)) {- try {- process.kill(proc.pid, 'SIGKILL');- killed.push({ pid: proc.pid, type: 'python' });- } catch {}- }- }-- // Find Node processes running from MachinaOs directory- const nodeProcs = await findProcess('name', 'node');- for (const proc of nodeProcs) {- const cmd = normalizePath(proc.cmd);- // Exclude the specified script from being killed- const shouldExclude = excludeScript && cmd.includes(excludeScript);- if (cmd.includes(rootNorm) && !shouldExclude) {- try {- process.kill(proc.pid, 'SIGKILL');- killed.push({ pid: proc.pid, type: 'node' });- } catch {}- }+ try {+ const scriptPath = resolve(__dirname, 'port_kill.py');+ const excludeArg = excludeScript ? ` --exclude "${excludeScript}"` : '';+ const output = execSync(+ `"${python}" "${scriptPath}" --kill-machina --root "${ROOT}"${excludeArg}`,+ { encoding: 'utf-8', timeout: 15000, stdio: ['pipe', 'pipe', 'pipe'] }+ );+ const result = JSON.parse(output.trim());+ if (result.error) return [];+ return (result.killed || []).map(k => ({ pid: k.pid, type: k.name }));+ } catch {+ return [];}-- return killed;}/*** Kill orphaned MachinaOS processes (uvicorn, vite, nodejs executor).- * More targeted than killMachinaProcesses - only kills specific known processes.+ * Uses killMachinaProcesses under the hood.* @returns {Promise<number[]>} Array of killed PIDs*/export async function killOrphanedProcesses() {- const findProcess = await getFindProcess();- if (!findProcess) return [];-- const killed = [];- const rootNorm = normalizePath(ROOT);+ const killed = await killMachinaProcesses();+ return killed.map(k => k.pid);+}- // Python processes (uvicorn/main:app)- const pythonProcs = await findProcess('name', 'python');- for (const proc of pythonProcs) {- const cmd = normalizePath(proc.cmd);- if (cmd.includes(rootNorm) && (cmd.includes('uvicorn') || cmd.includes('main:app'))) {- try {- process.kill(proc.pid, 'SIGKILL');- killed.push(proc.pid);- } catch {}- }- }+/**+ * Kill processes matching a name pattern.+ * @returns {Promise<number[]>} Array of killed PIDs+ */+export async function killByPattern(pattern) {+ // Pattern-based killing handled by killMachinaProcesses for project processes+ // For specific patterns like 'temporal', use psutil process iteration+ const python = findPython();+ if (!python) return [];- // Node processes (vite, nodejs executor)- const nodeProcs = await findProcess('name', 'node');- for (const proc of nodeProcs) {- const cmd = normalizePath(proc.cmd);- if (cmd.includes(rootNorm) && (cmd.includes('vite') || cmd.includes('nodejs/src'))) {- try {- process.kill(proc.pid, 'SIGKILL');- killed.push(proc.pid);- } catch {}- }+ try {+ const scriptPath = resolve(__dirname, 'port_kill.py');+ const output = execSync(+ `"${python}" "${scriptPath}" --kill-pattern "${pattern}" --root "${ROOT}"`,+ { encoding: 'utf-8', timeout: 15000, stdio: ['pipe', 'pipe', 'pipe'] }+ );+ const result = JSON.parse(output.trim());+ if (result.error) return [];+ return (result.killed || []).map(k => k.pid);+ } catch {+ return [];}-- return killed;}/**diff --git a/server/config/google_apis.json b/server/config/google_apis.jsonindex 0f2302f2..a046b6d5 100644--- a/server/config/google_apis.json+++ b/server/config/google_apis.json@@ -7,7 +7,9 @@"auth_uri": "https://accounts.google.com/o/oauth2/auth","token_uri": "https://oauth2.googleapis.com/token","revoke_uri": "https://oauth2.googleapis.com/revoke",- "userinfo_uri": "https://www.googleapis.com/oauth2/v2/userinfo"+ "userinfo_uri": "https://www.googleapis.com/oauth2/v2/userinfo",+ "google_callback_path": "/api/google/callback",+ "twitter_callback_path": "/api/twitter/callback"},"services": {diff --git a/server/core/cache.py b/server/core/cache.pyindex 8424204f..daef4a8a 100644--- a/server/core/cache.py+++ b/server/core/cache.py@@ -5,9 +5,7 @@ with Redis used only for distributed queue mode or high-performance needs."""import json-import asynciofrom typing import Any, Dict, Optional, List, TYPE_CHECKING-from datetime import timedeltatry:import redis.asyncio as redisdiff --git a/server/core/config.py b/server/core/config.pyindex 372ee29f..45c6bf9c 100644--- a/server/core/config.py+++ b/server/core/config.py@@ -59,9 +59,6 @@ class Settings(BaseSettings):anthropic_api_key: Optional[str] = Field(default=None, env="ANTHROPIC_API_KEY")google_ai_api_key: Optional[str] = Field(default=None, env="GOOGLE_AI_API_KEY")- # WhatsApp Service URL (Flask service)- whatsapp_service_url: str = Field(default="http://localhost:5000", env="WHATSAPP_SERVICE_URL")-# Node.js Executor Configurationnodejs_executor_url: str = Field(default="http://localhost:3020", env="NODEJS_EXECUTOR_URL")nodejs_executor_timeout: int = Field(default=30, env="NODEJS_EXECUTOR_TIMEOUT", ge=5, le=300)@@ -73,11 +70,6 @@ class Settings(BaseSettings):websocket_url: str = Field(default="", env="WEBSOCKET_URL")websocket_api_key: Optional[str] = Field(default=None, env="WEBSOCKET_API_KEY")- # OAuth Redirect URIs- google_redirect_uri: str = Field(default="http://localhost:3010/api/google/callback", env="GOOGLE_REDIRECT_URI")- gmail_redirect_uri: str = Field(default="http://localhost:3010/api/gmail/callback", env="GMAIL_REDIRECT_URI") # Deprecated: use google_redirect_uri- twitter_redirect_uri: str = Field(default="http://localhost:3010/api/twitter/callback", env="TWITTER_REDIRECT_URI")-# Android Relay Configuration (passed to Vite frontend)vite_android_relay_url: Optional[str] = Field(default=None, env="VITE_ANDROID_RELAY_URL")diff --git a/server/core/container.py b/server/core/container.pyindex adc98466..84661c81 100644--- a/server/core/container.py+++ b/server/core/container.py@@ -1,7 +1,6 @@"""Dependency injection container for the application."""from dependency_injector import containers, providers-from dependency_injector.wiring import Provide, injectfrom core.config import Settingsfrom core.database import Databasediff --git a/server/core/database.py b/server/core/database.pyindex ee744da5..a87b5447 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -1,8 +1,8 @@"""Modern async database service with SQLModel and SQLAlchemy 2.0."""-from datetime import datetime, timedelta, timezone+from datetime import datetime, timezonefrom typing import Dict, Any, List, Optional-from sqlmodel import SQLModel, select, Session+from sqlmodel import SQLModel, selectfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmakerfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy import text, func@@ -16,7 +16,6 @@ from models.database import (AgentTeam, TeamMember, TeamTask, AgentMessage, GoogleConnection)from models.cache import CacheEntry # SQLite-backed cache for Redis alternative-from models.auth import User # Import User model to ensure table creationfrom core.logging import get_loggerlogger = get_logger(__name__)@@ -89,6 +88,22 @@ class Database:))logger.info("Added examples_loaded column to user_settings")+ if "onboarding_completed" not in columns:+ await conn.execute(text(+ "ALTER TABLE user_settings ADD COLUMN onboarding_completed BOOLEAN DEFAULT 0"+ ))+ # Existing users (examples_loaded=1) skip onboarding+ await conn.execute(text(+ "UPDATE user_settings SET onboarding_completed = 1 WHERE examples_loaded = 1"+ ))+ logger.info("Added onboarding_completed column to user_settings")++ if "onboarding_step" not in columns:+ await conn.execute(text(+ "ALTER TABLE user_settings ADD COLUMN onboarding_step INTEGER DEFAULT 0"+ ))+ logger.info("Added onboarding_step column to user_settings")+# Migrate token_usage_metrics table - add cost columnsresult = await conn.execute(text("PRAGMA table_info(token_usage_metrics)"))columns = {row[1] for row in result.fetchall()}@@ -436,7 +451,7 @@ class Database:stmt = select(APIKey).where(APIKey.provider == provider,APIKey.session_id == session_id,- APIKey.is_valid == True+ APIKey.is_valid)result = await session.execute(stmt)return result.scalar_one_or_none()@@ -1379,7 +1394,7 @@ class Database:try:async with self.get_session() as session:if active_only:- stmt = select(UserSkill).where(UserSkill.is_active == True).order_by(UserSkill.display_name)+ stmt = select(UserSkill).where(UserSkill.is_active).order_by(UserSkill.display_name)else:stmt = select(UserSkill).order_by(UserSkill.display_name)@@ -1508,6 +1523,8 @@ class Database:"component_palette_default_open": settings.component_palette_default_open,"console_panel_default_open": settings.console_panel_default_open,"examples_loaded": settings.examples_loaded,+ "onboarding_completed": settings.onboarding_completed,+ "onboarding_step": settings.onboarding_step,"created_at": settings.created_at.isoformat() if settings.created_at else None,"updated_at": settings.updated_at.isoformat() if settings.updated_at else None}@@ -1539,6 +1556,10 @@ class Database:existing.console_panel_default_open = settings_data["console_panel_default_open"]if "examples_loaded" in settings_data:existing.examples_loaded = settings_data["examples_loaded"]+ if "onboarding_completed" in settings_data:+ existing.onboarding_completed = settings_data["onboarding_completed"]+ if "onboarding_step" in settings_data:+ existing.onboarding_step = settings_data["onboarding_step"]else:# Create new settingsexisting = UserSettings(@@ -1548,7 +1569,9 @@ class Database:sidebar_default_open=settings_data.get("sidebar_default_open", True),component_palette_default_open=settings_data.get("component_palette_default_open", True),console_panel_default_open=settings_data.get("console_panel_default_open", False),- examples_loaded=settings_data.get("examples_loaded", False)+ examples_loaded=settings_data.get("examples_loaded", False),+ onboarding_completed=settings_data.get("onboarding_completed", False),+ onboarding_step=settings_data.get("onboarding_step", 0))session.add(existing)@@ -2318,7 +2341,7 @@ class Database:AgentMessage.to_agent.is_(None)))if unread_only:- query = query.where(AgentMessage.read == False)+ query = query.where(not AgentMessage.read)query = query.order_by(AgentMessage.created_at.asc()).limit(100)result = await session.execute(query)return [@@ -2339,7 +2362,7 @@ class Database:result = await session.execute(select(AgentMessage).where(AgentMessage.team_id == team_id,- AgentMessage.read == False,+ not AgentMessage.read,or_(AgentMessage.to_agent == agent_node_id, AgentMessage.to_agent.is_(None))))@@ -2446,7 +2469,7 @@ class Database:result = await session.execute(select(GoogleConnection).where(GoogleConnection.customer_id == customer_id,- GoogleConnection.is_active == True+ GoogleConnection.is_active))return result.scalar_one_or_none()@@ -2477,7 +2500,7 @@ class Database:async with self.get_session() as session:result = await session.execute(select(GoogleConnection)- .where(GoogleConnection.is_active == True)+ .where(GoogleConnection.is_active).order_by(GoogleConnection.connected_at.desc()).limit(limit))diff --git a/server/core/logging.py b/server/core/logging.pyindex 704020c7..dabefa1f 100644--- a/server/core/logging.py+++ b/server/core/logging.py@@ -93,7 +93,7 @@ class WebSocketLogHandler(logging.Handler):# Non-blocking put - drop if queue is fulltry:self._queue.put_nowait(log_data)- except:+ except Exception:pass # Drop log if queue is fullexcept Exception:@@ -124,7 +124,7 @@ class WebSocketLogHandler(logging.Handler):# Block for up to 0.1 seconds waiting for logstry:log_data = self._queue.get(timeout=0.1)- except:+ except Exception:continue# Schedule async broadcast on the event loopdiff --git a/server/main.py b/server/main.pyindex 3d7362c1..3d18612d 100644--- a/server/main.py+++ b/server/main.py@@ -11,7 +11,6 @@ try:except ImportError:pass # Windows - uvloop not available, use default asyncio-import osfrom datetime import datetimefrom contextlib import asynccontextmanager@@ -131,7 +130,6 @@ async def lifespan(app: FastAPI):await cleanup_service.start()# Initialize compaction service and wire AI service- from services.compaction import get_compaction_servicecompaction_svc = container.compaction_service() # Trigger singleton initializationcompaction_svc.set_ai_service(container.ai_service())logger.info("Compaction service initialized")@@ -297,7 +295,7 @@ async def health_check():"""Detailed health check with resource monitoring."""from services import event_waiterfrom services.execution import get_recovery_sweeper- from core.health import get_health_status, get_uptime, get_memory_mb, get_disk_percent, get_cpu_percent+ from core.health import get_health_statussweeper = get_recovery_sweeper()diff --git a/server/middleware/auth.py b/server/middleware/auth.pyindex e48b09b6..19ba4a17 100644--- a/server/middleware/auth.py+++ b/server/middleware/auth.py@@ -1,7 +1,7 @@"""Authentication middleware for route protection."""import logging-from fastapi import Request, HTTPException+from fastapi import Requestfrom fastapi.responses import JSONResponsefrom starlette.middleware.base import BaseHTTPMiddlewarediff --git a/server/models/database.py b/server/models/database.pyindex 6425c2cd..3fb4970c 100644--- a/server/models/database.py+++ b/server/models/database.py@@ -1,7 +1,7 @@"""SQLModel database models and tables."""from datetime import datetime, timezone-from typing import Optional, Dict, Any, List+from typing import Optional, Dict, Anyfrom sqlmodel import SQLModel, Field, Column, DateTime, JSONfrom sqlalchemy import func@@ -253,6 +253,8 @@ class UserSettings(SQLModel, table=True):component_palette_default_open: bool = Field(default=True)console_panel_default_open: bool = Field(default=False)examples_loaded: bool = Field(default=False) # Track if example workflows were imported+ onboarding_completed: bool = Field(default=False) # Track if user completed or skipped onboarding+ onboarding_step: int = Field(default=0) # Last completed onboarding step (for resuming)created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc),sa_column=Column(DateTime(timezone=True), server_default=func.now())diff --git a/server/pyproject.toml b/server/pyproject.tomlindex 4ad127d8..da7d679c 100644--- a/server/pyproject.toml+++ b/server/pyproject.toml@@ -55,6 +55,7 @@ dependencies = ["apscheduler>=3.10.0","qrcode[pil]>=8.0","pytz>=2024.1",+ "psutil>=6.0.0",# Web Search"ddgs>=9.0.0",@@ -65,6 +66,9 @@ dependencies = [# Apify Web Scraping"apify-client>=1.8.0",+ # Telegram Bot API+ "python-telegram-bot>=22.6",+# Gmail API"google-api-python-client>=2.100.0","google-auth>=2.27.0",@@ -91,5 +95,14 @@ aws = ["boto3>=1.34.0", # AWS Secrets Manager]+[tool.ruff]+line-length = 140++[tool.ruff.lint]+ignore = [+ "E402", # Module level import not at top (intentional lazy imports)+ "E701", # Multiple statements on one line (compact dict patterns)+]+[tool.uv]index-url = "https://pypi.org/simple"diff --git a/server/routers/android.py b/server/routers/android.pyindex 733135e4..c4434684 100644--- a/server/routers/android.py+++ b/server/routers/android.py@@ -2,7 +2,7 @@from fastapi import APIRouter, Dependsfrom pydantic import BaseModel, Field-from typing import Dict, Any, Optional+from typing import Dict, Anyfrom core.container import containerfrom services.android_service import AndroidServicediff --git a/server/routers/auth.py b/server/routers/auth.pyindex 564ab0ba..9345c331 100644--- a/server/routers/auth.py+++ b/server/routers/auth.py@@ -2,7 +2,6 @@from fastapi import APIRouter, Depends, HTTPException, Response, Requestfrom pydantic import BaseModel, EmailStr-from typing import Optionalfrom core.container import containerfrom core.config import Settingsdiff --git a/server/routers/database.py b/server/routers/database.pyindex 1f6b2b0d..4369d1ba 100644--- a/server/routers/database.py+++ b/server/routers/database.py@@ -2,7 +2,7 @@from fastapi import APIRouter, Dependsfrom pydantic import BaseModel-from typing import Dict, Any, Optional, List+from typing import Dict, Anyfrom core.container import containerfrom core.database import Databasediff --git a/server/routers/google.py b/server/routers/google.pyindex 64e53743..8a595692 100644--- a/server/routers/google.py+++ b/server/routers/google.py@@ -19,7 +19,7 @@ Supports all Google Workspace services:from typing import Optional-from fastapi import APIRouter, Query+from fastapi import APIRouter, Query, Requestfrom fastapi.responses import HTMLResponse, RedirectResponsefrom core.container import container@@ -30,11 +30,6 @@ logger = get_logger(__name__)router = APIRouter(prefix="/api/google", tags=["google"])-def get_settings():- """Get application settings."""- return container.settings()--def get_auth_service():"""Get auth service for API key storage."""return container.auth_service()@@ -90,8 +85,16 @@ async def google_oauth_callback(customer_id = state_data.get("customer_id")redirect_after = state_data.get("redirect_after")- # Get settings and credentials- settings = get_settings()+ # Retrieve redirect_uri from state (set during auth initiation)+ redirect_uri = pending_state.get("redirect_uri")+ if not redirect_uri:+ logger.error("Google OAuth callback missing redirect_uri in state")+ return HTMLResponse(+ content=_callback_html(success=False, error="Invalid state: missing redirect URI. Please try again."),+ status_code=400,+ )++ # Get credentialsauth_service = get_auth_service()client_id = await auth_service.get_api_key("google_client_id") or ""client_secret = await auth_service.get_api_key("google_client_secret") or ""@@ -105,7 +108,7 @@ async def google_oauth_callback(oauth = GoogleOAuth(client_id=client_id,client_secret=client_secret,- redirect_uri=settings.google_redirect_uri,+ redirect_uri=redirect_uri,)# Exchange code for tokens@@ -196,9 +199,10 @@ async def google_logout():@router.post("/customer-auth-url")-async def generate_customer_auth_url(customer_id: str, redirect_after: Optional[str] = None):+async def generate_customer_auth_url(request: Request, customer_id: str, redirect_after: Optional[str] = None):"""Generate OAuth URL for a customer to connect their Google account."""- settings = get_settings()+ from services.oauth_utils import get_redirect_uri+auth_service = get_auth_service()client_id = await auth_service.get_api_key("google_client_id") or ""client_secret = await auth_service.get_api_key("google_client_secret") or ""@@ -206,10 +210,12 @@ async def generate_customer_auth_url(customer_id: str, redirect_after: Optional[if not client_id or not client_secret:return {"success": False, "error": "Google not configured. Add Client ID and Secret."}+ redirect_uri = get_redirect_uri(request, "google")+oauth = GoogleOAuth(client_id=client_id,client_secret=client_secret,- redirect_uri=settings.google_redirect_uri,+ redirect_uri=redirect_uri,)result = oauth.generate_authorization_url(state_data={"customer_id": customer_id, "redirect_after": redirect_after, "mode": "customer"})return {"success": True, "url": result["url"], "state": result["state"]}@@ -246,6 +252,7 @@ def _callback_html(success: bool, email: str = None, error: str = None) -> str:else:title, message, color = "Connection Failed", error or "Failed to connect", "#ea4335"+ escaped_error = error.replace("'", "\\'") if error else ""return f"""<!DOCTYPE html><html><head><title>{title}</title>@@ -265,6 +272,6 @@ p{{font-size:16px;color:rgba(255,255,255,0.8);margin-bottom:20px}}<h1>{title}</h1><p>{message}</p><p class="close-text">This window will close automatically...</p></div><script>-if(window.opener){{window.opener.postMessage({{type:'google_oauth_callback',success:{str(success).lower()},{"email:'"+email+"'," if email else ""}{"error:'"+error.replace("'","\\'")+"'," if error else ""}}},'*')}}+if(window.opener){{window.opener.postMessage({{type:'google_oauth_callback',success:{str(success).lower()},{"email:'"+email+"'," if email else ""}{"error:'"+escaped_error+"'," if error else ""}}},'*')}}setTimeout(function(){{window.close()}},2000);</script></body></html>"""diff --git a/server/routers/twitter.py b/server/routers/twitter.pyindex f89dff86..5cf3981c 100644--- a/server/routers/twitter.py+++ b/server/routers/twitter.py@@ -16,7 +16,7 @@ Tokens stored as API keys with provider prefixes:from typing import Optional-from fastapi import APIRouter, Query+from fastapi import APIRouter, Query, Requestfrom fastapi.responses import HTMLResponsefrom core.container import container@@ -27,39 +27,11 @@ logger = get_logger(__name__)router = APIRouter(prefix="/api/twitter", tags=["twitter"])-def get_settings():- """Get application settings."""- return container.settings()--def get_auth_service():"""Get auth service for API key storage."""return container.auth_service()-def get_twitter_oauth() -> TwitterOAuth:- """Create TwitterOAuth instance from stored credentials."""- auth_service = get_auth_service()- # Twitter client_id and client_secret are stored as API keys- # These are configured in the Credentials Modal- import asyncio- loop = asyncio.get_event_loop()-- # Get stored Twitter app credentials (client_id, client_secret)- # These are stored via the Credentials Modal with provider='twitter'- client_id = loop.run_until_complete(auth_service.get_api_key("twitter_client_id")) or ""- client_secret = loop.run_until_complete(auth_service.get_api_key("twitter_client_secret"))-- settings = get_settings()- redirect_uri = settings.twitter_redirect_uri-- return TwitterOAuth(- client_id=client_id,- client_secret=client_secret,- redirect_uri=redirect_uri,- )--@router.get("/callback")async def twitter_oauth_callback(code: Optional[str] = Query(None),@@ -107,8 +79,19 @@ async def twitter_oauth_callback(status_code=400,)+ # Retrieve redirect_uri from state (set during auth initiation)+ redirect_uri = pending_state.get("redirect_uri")+ if not redirect_uri:+ logger.error("Twitter OAuth callback missing redirect_uri in state")+ return HTMLResponse(+ content=_callback_html(+ success=False,+ error="Invalid state: missing redirect URI. Please try again.",+ ),+ status_code=400,+ )+# Get stored client credentials to create OAuth instance- settings = get_settings()auth_service = get_auth_service()client_id = await auth_service.get_api_key("twitter_client_id") or ""client_secret = await auth_service.get_api_key("twitter_client_secret")@@ -116,7 +99,7 @@ async def twitter_oauth_callback(oauth = TwitterOAuth(client_id=client_id,client_secret=client_secret,- redirect_uri=settings.twitter_redirect_uri,+ redirect_uri=redirect_uri,)# Exchange code for tokens@@ -181,12 +164,14 @@ async def twitter_oauth_callback(@router.get("/status")-async def get_twitter_status():+async def get_twitter_status(request: Request):"""Get Twitter connection status.Returns whether the user is authenticated with Twitter."""+ from services.oauth_utils import get_redirect_uri+auth_service = get_auth_service()# Try to get stored tokens via auth_service@@ -203,14 +188,14 @@ async def get_twitter_status():refresh_token = tokens.get("refresh_token")# Get stored client credentials (these remain in auth_service as they're app-level)- settings = get_settings()client_id = await auth_service.get_api_key("twitter_client_id") or ""client_secret = await auth_service.get_api_key("twitter_client_secret")+ redirect_uri = get_redirect_uri(request, "twitter")oauth = TwitterOAuth(client_id=client_id,client_secret=client_secret,- redirect_uri=settings.twitter_redirect_uri,+ redirect_uri=redirect_uri,)# Verify token is still valid by getting user info@@ -254,10 +239,12 @@ async def get_twitter_status():@router.post("/logout")-async def twitter_logout():+async def twitter_logout(request: Request):"""Disconnect Twitter by revoking tokens and clearing stored credentials."""+ from services.oauth_utils import get_redirect_uri+auth_service = get_auth_service()# Get stored tokens via auth_service@@ -270,12 +257,12 @@ async def twitter_logout():# Get client credentials for revocation (app-level, in auth_service)client_id = await auth_service.get_api_key("twitter_client_id") or ""client_secret = await auth_service.get_api_key("twitter_client_secret")+ redirect_uri = get_redirect_uri(request, "twitter")- settings = get_settings()oauth = TwitterOAuth(client_id=client_id,client_secret=client_secret,- redirect_uri=settings.twitter_redirect_uri,+ redirect_uri=redirect_uri,)# Revoke tokens@@ -299,13 +286,12 @@ def _callback_html(success: bool, username: str = None, error: str = None) -> sttitle = "Twitter Connected"message = f"Successfully connected as @{username}!"color = "#00ba7c" # Green- icon = "check-circle"else:title = "Connection Failed"message = error or "Failed to connect to Twitter"color = "#f4212e" # Red- icon = "x-circle"+ escaped_error = error.replace("'", "\\'") if error else ""return f"""<!DOCTYPE html><html>@@ -368,7 +354,7 @@ def _callback_html(success: bool, username: str = None, error: str = None) -> sttype: 'twitter_oauth_callback',success: {str(success).lower()},{"username: '" + username + "'," if username else ""}- {"error: '" + error.replace("'", "\\'") + "'," if error else ""}+ {"error: '" + escaped_error + "'," if error else ""}}}, '*');}}// Close after 2 secondsdiff --git a/server/routers/webhook.py b/server/routers/webhook.pyindex 910d0fd0..2c0db035 100644--- a/server/routers/webhook.py+++ b/server/routers/webhook.py@@ -3,9 +3,9 @@Works like WhatsApp trigger - uses broadcaster.send_custom_event() to dispatchto event_waiter which resolves waiting trigger nodes."""-from fastapi import APIRouter, Request, HTTPException, Response+from fastapi import APIRouter, Requestfrom fastapi.responses import JSONResponse-from typing import Dict, Any+from typing import Dictimport asyncioimport logging@@ -49,7 +49,7 @@ async def handle_webhook(path: str, request: Request):if "application/json" in content_type and body:try:json_body = await request.json()- except:+ except Exception:passwebhook_data = {diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex 21806592..b18ffc00 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -21,6 +21,11 @@ from services.status_broadcaster import get_status_broadcasterfrom core.container import containerfrom core.logging import get_logger++def get_auth_service():+ """Get auth service from DI container."""+ return container.auth_service()+logger = get_logger(__name__)router = APIRouter(tags=["websocket"])@@ -642,7 +647,7 @@ async def handle_deploy_workflow(data: Dict[str, Any], websocket: WebSocket) ->for te in tool_edges:logger.debug(f"[Deploy] Tool edge: source={te.get('source')} -> target={te.get('target')}")else:- logger.debug(f"[Deploy] No input-tools edges found")+ logger.debug("[Deploy] No input-tools edges found")if not nodes:return {"success": False, "error": "No nodes provided"}@@ -788,7 +793,6 @@ async def handle_cancel_deployment(data: Dict[str, Any], websocket: WebSocket) -Cancellation result with iterations completed"""global _deployment_tasks- from services import event_waiterworkflow_service = container.workflow_service()broadcaster = get_status_broadcaster()@@ -1075,10 +1079,13 @@ async def handle_twitter_oauth_login(data: Dict[str, Any], websocket: WebSocket)}# Create OAuth instance and generate authorization URL+ from services.oauth_utils import get_redirect_uri+ redirect_uri = get_redirect_uri(websocket, "twitter")+oauth = TwitterOAuth(client_id=client_id,client_secret=client_secret,- redirect_uri="http://localhost:3010/api/twitter/callback",+ redirect_uri=redirect_uri,)auth_data = oauth.generate_authorization_url()@@ -1118,10 +1125,13 @@ async def handle_twitter_oauth_status(data: Dict[str, Any], websocket: WebSocketclient_id = await auth_service.get_api_key("twitter_client_id") or ""client_secret = await auth_service.get_api_key("twitter_client_secret")+ from services.oauth_utils import get_redirect_uri+ redirect_uri = get_redirect_uri(websocket, "twitter")+oauth = TwitterOAuth(client_id=client_id,client_secret=client_secret,- redirect_uri="http://localhost:3010/api/twitter/callback",+ redirect_uri=redirect_uri,)# Verify token by getting user info@@ -1185,10 +1195,13 @@ async def handle_twitter_logout(data: Dict[str, Any], websocket: WebSocket) -> D# Revoke tokens if we have themif access_token or refresh_token:+ from services.oauth_utils import get_redirect_uri+ redirect_uri = get_redirect_uri(websocket, "twitter")+oauth = TwitterOAuth(client_id=client_id,client_secret=client_secret,- redirect_uri="http://localhost:3010/api/twitter/callback",+ redirect_uri=redirect_uri,)if access_token:@@ -1221,7 +1234,6 @@ async def handle_google_oauth_login(data: Dict[str, Any], websocket: WebSocket)from services.google_oauth import GoogleOAuthauth_service = container.auth_service()- settings = container.settings()client_id = await auth_service.get_api_key("google_client_id")client_secret = await auth_service.get_api_key("google_client_secret")@@ -1232,10 +1244,13 @@ async def handle_google_oauth_login(data: Dict[str, Any], websocket: WebSocket)"error": "Google Workspace Client ID and Secret not configured. Add your Google API credentials first."}+ from services.oauth_utils import get_redirect_uri+ redirect_uri = get_redirect_uri(websocket, "google")+oauth = GoogleOAuth(client_id=client_id,client_secret=client_secret,- redirect_uri=settings.google_redirect_uri,+ redirect_uri=redirect_uri,)auth_data = oauth.generate_authorization_url()@@ -1654,7 +1669,7 @@ async def handle_validate_apify_key(data: Dict[str, Any], websocket: WebSocket)return {"success": True,"valid": True,- "message": f"Apify API token is valid",+ "message": "Apify API token is valid","username": result.get("username"),"email": result.get("email"),"plan": result.get("plan")@@ -2198,7 +2213,6 @@ async def handle_save_skill_content(data: Dict[str, Any], websocket: WebSocket)For user skills, updates the database."""import re- from pathlib import Pathfrom services.skill_loader import get_skill_loaderskill_name = data["skill_name"]@@ -3140,7 +3154,7 @@ async def websocket_internal_endpoint(websocket: WebSocket):Security: Should only be exposed on localhost/internal network."""- broadcaster = get_status_broadcaster()+ get_status_broadcaster()await websocket.accept()logger.info("[WebSocket Internal] Temporal worker connected")diff --git a/server/services/ai.py b/server/services/ai.pyindex f9d185c9..3f0ed577 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -10,10 +10,19 @@ import operatorfrom langchain_openai import ChatOpenAIfrom langchain_anthropic import ChatAnthropic-from langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_groq import ChatGroqfrom langchain_core.messages import HumanMessage, SystemMessage, AIMessage, BaseMessage, ToolMessage+# Lazy import for Google GenAI (google-generativeai init hangs on Windows/Python 3.13)+_ChatGoogleGenerativeAI = None++def _get_google_genai_class():+ global _ChatGoogleGenerativeAI+ if _ChatGoogleGenerativeAI is None:+ from langchain_google_genai import ChatGoogleGenerativeAI+ _ChatGoogleGenerativeAI = ChatGoogleGenerativeAI+ return _ChatGoogleGenerativeAI+# Conditional import for Cerebras (requires Python <3.13)CEREBRAS_IMPORT_ERROR = Nonetry:@@ -126,7 +135,7 @@ def _get_memory_vector_store(session_id: str):class ProviderConfig:"""Configuration for an AI provider."""name: str- model_class: Type+ model_class: Optional[Type]api_key_param: str # Parameter name for API key in model constructormax_tokens_param: str # Parameter name for max tokensdetection_patterns: tuple # Patterns to detect this provider from model name@@ -230,7 +239,7 @@ PROVIDER_CONFIGS: Dict[str, ProviderConfig] = {),'gemini': ProviderConfig(name='gemini',- model_class=ChatGoogleGenerativeAI,+ model_class=None, # Lazy: resolved via _get_google_genai_class() to avoid import hang on Windowsapi_key_param='google_api_key',max_tokens_param='max_output_tokens',detection_patterns=('gemini', 'google'),@@ -1138,7 +1147,9 @@ class AIService:# Passing through as model_kwargs if supportedkwargs['thinking_budget'] = thinking.budget- return config.model_class(**kwargs)+ # Resolve lazy-loaded model class (gemini)+ model_class = config.model_class or _get_google_genai_class()+ return model_class(**kwargs)async def fetch_models(self, provider: str, api_key: str) -> List[str]:"""Fetch available models from provider API."""@@ -1488,7 +1499,7 @@ class AIService:for skill_info in skill_data:skill_name = skill_info.get('skill_name') or skill_info.get('node_type', '').replace('Skill', '-skill').lower()# Convert node type to skill name (e.g., 'whatsappSkill' -> 'whatsapp-skill')- if skill_name.endswith('skill') and not '-' in skill_name:+ if skill_name.endswith('skill') and '-' not in skill_name:skill_name = skill_name[:-5] + '-skill' # whatsappskill -> whatsapp-skillskill_names.append(skill_name)logger.debug(f"[AIAgent] Skill detected: {skill_name}")@@ -1564,7 +1575,7 @@ class AIService:# Broadcast: Loading memoryawait broadcast_status("loading_memory", {- "message": f"Loading conversation history...",+ "message": "Loading conversation history...","session_id": session_id,"has_memory": True})@@ -1633,7 +1644,7 @@ class AIService:if check_tool:tools.append(check_tool)tool_configs[check_tool.name] = check_config- logger.debug(f"[LangGraph] Auto-injected check_delegated_tasks tool")+ logger.debug("[LangGraph] Auto-injected check_delegated_tasks tool")# Create tool executor callbackasync def tool_executor(tool_name: str, tool_args: Dict) -> Any:@@ -1807,7 +1818,7 @@ class AIService:updated_content = compaction_result['summary']updated_content = _append_to_memory_markdown(updated_content, 'human', prompt)updated_content = _append_to_memory_markdown(updated_content, 'ai', response_content)- logger.info(f"[LangGraph Memory] Using compacted summary as new base")+ logger.info("[LangGraph Memory] Using compacted summary as new base")else:# Normal flow: append to existing memoryupdated_content = memory_data.get('memory_content', '# Conversation History\n\n*No messages yet.*\n')@@ -1939,7 +1950,7 @@ class AIService:for skill_info in skill_data:skill_name = skill_info.get('skill_name') or skill_info.get('node_type', '').replace('Skill', '-skill').lower()# Convert node type to skill name (e.g., 'whatsappSkill' -> 'whatsapp-skill')- if skill_name.endswith('skill') and not '-' in skill_name:+ if skill_name.endswith('skill') and '-' not in skill_name:skill_name = skill_name[:-5] + '-skill' # whatsappskill -> whatsapp-skillskill_names.append(skill_name)logger.debug(f"[ChatAgent] Skill detected: {skill_name}")@@ -1982,7 +1993,7 @@ class AIService:if check_tool:all_tools.append(check_tool)tool_node_configs[check_tool.name] = check_config- logger.debug(f"[ChatAgent] Auto-injected check_delegated_tasks tool")+ logger.debug("[ChatAgent] Auto-injected check_delegated_tasks tool")logger.debug(f"[ChatAgent] Total tools available: {len(all_tools)}")# Debug: log all tool schemas to verify they're correct@@ -2246,7 +2257,7 @@ class AIService:updated_content = compaction_result['summary']updated_content = _append_to_memory_markdown(updated_content, 'human', prompt)updated_content = _append_to_memory_markdown(updated_content, 'ai', response_content)- logger.info(f"[ChatAgent Memory] Using compacted summary as new base")+ logger.info("[ChatAgent Memory] Using compacted summary as new base")else:# Normal flow: append to existing memoryupdated_content = memory_content or '# Conversation History\n\n*No messages yet.*\n'diff --git a/server/services/android/client.py b/server/services/android/client.pyindex 8cae4a94..fe831607 100644--- a/server/services/android/client.py+++ b/server/services/android/client.py@@ -15,12 +15,10 @@ import jsonimport uuidimport aiohttpfrom typing import Optional, Dict, Any, Set, Callable-from datetime import datetimeimport structlog-from .protocol import RPCRequest, RPCResponse, RPCEvent, RPCRequestTracker, parse_message, is_response+from .protocol import RPCResponse, RPCRequestTracker, is_responsefrom .broadcaster import (- broadcast_android_status,broadcast_connected,broadcast_device_disconnected,broadcast_relay_disconnected,diff --git a/server/services/android_service.py b/server/services/android_service.pyindex d9b39cf1..9de88d04 100644--- a/server/services/android_service.py+++ b/server/services/android_service.py@@ -2,9 +2,8 @@import timeimport httpx-import asynciofrom datetime import datetime-from typing import Dict, Any, Optional, List+from typing import Dict, Any, Listfrom core.logging import get_logger, log_execution_time@@ -249,7 +248,7 @@ class AndroidService:if not response:raise Exception(- f"No response from Android device (timeout). "+ "No response from Android device (timeout). ""Ensure the Android app is running and paired.")@@ -503,7 +502,7 @@ class AndroidService:"timestamp": datetime.now().isoformat()}- except httpx.TimeoutException as e:+ except httpx.TimeoutException:error_msg = f"Request timeout after {self.default_timeout}s"logger.error("[Android Service] Timeout",diff --git a/server/services/auth.py b/server/services/auth.pyindex a6c244aa..6de74e83 100644--- a/server/services/auth.py+++ b/server/services/auth.py@@ -1,7 +1,6 @@"""API key management service with encrypted credentials database."""import hashlib-from datetime import datetime, timedelta, timezonefrom typing import Dict, Any, Optional, Listfrom core.config import Settingsdiff --git a/server/services/claude_oauth.py b/server/services/claude_oauth.pyindex 7d4755da..7f3ba11b 100644--- a/server/services/claude_oauth.py+++ b/server/services/claude_oauth.py@@ -1,6 +1,5 @@"""Claude OAuth Service - Isolated login that doesn't affect user's main session."""-import asyncioimport jsonimport osimport shutil@@ -86,7 +85,7 @@ async def initiate_claude_oauth() -> Dict[str, Any]:try:process.stdin.write(b"yes\nyes\n")process.stdin.flush()- except:+ except Exception:passelse:# Unix: pipe inputs@@ -100,7 +99,7 @@ async def initiate_claude_oauth() -> Dict[str, Any]:try:process.stdin.write(b"yes\nyes\n")process.stdin.flush()- except:+ except Exception:passlogger.info(f"Claude OAuth login started with PID {process.pid}")diff --git a/server/services/deployment/triggers.py b/server/services/deployment/triggers.pyindex 3b9f64a0..bfc60cf0 100644--- a/server/services/deployment/triggers.py+++ b/server/services/deployment/triggers.py@@ -4,8 +4,7 @@ Handles cron scheduling, event-based triggers (webhook, whatsapp), and cleanup."""import asyncio-from datetime import datetime-from typing import Dict, Any, Callable, Optional, Set+from typing import Dict, Any, Callable, Optionalfrom core.logging import get_loggerfrom constants import WORKFLOW_TRIGGER_TYPESdiff --git a/server/services/event_waiter.py b/server/services/event_waiter.pyindex 63940daf..680e9ae1 100644--- a/server/services/event_waiter.py+++ b/server/services/event_waiter.py@@ -680,7 +680,6 @@ async def _wait_redis(waiter: Waiter, timeout: Optional[float]) -> Dict:consumer_name = f"consumer_{waiter.id}"# Start reading from now (new messages only)- last_id = '$'block_ms = 5000 # 5 second blocks to allow cancellation checksstart_time = time.time()@@ -793,7 +792,7 @@ def dispatch(event_type: str, data: Dict) -> int:# Handle both async context and thread context (e.g., APScheduler callbacks)try:# Try to get the current running loop- loop = asyncio.get_running_loop()+ asyncio.get_running_loop()# We're in an async context - schedule task normallyasyncio.create_task(dispatch_async(event_type, data))except RuntimeError:diff --git a/server/services/execution/cache.py b/server/services/execution/cache.pyindex b075bfa4..7b703477 100644--- a/server/services/execution/cache.py+++ b/server/services/execution/cache.py@@ -16,7 +16,7 @@ from typing import Dict, Any, List, Optional, Set, Unionfrom core.logging import get_loggerfrom core.cache import CacheService-from .models import ExecutionContext, TaskStatus, WorkflowStatus, hash_inputs, DLQEntry+from .models import ExecutionContext, WorkflowStatus, hash_inputs, DLQEntrylogger = get_logger(__name__)diff --git a/server/services/execution/conditions.py b/server/services/execution/conditions.pyindex cab70e59..7b5596dc 100644--- a/server/services/execution/conditions.py+++ b/server/services/execution/conditions.py@@ -24,7 +24,7 @@ Supported operators:"""import re-from typing import Dict, Any, Optional, List, Union+from typing import Dict, Any, Listfrom core.logging import get_loggerdiff --git a/server/services/execution/dlq.py b/server/services/execution/dlq.pyindex 1ebd5ec2..c7faf46e 100644--- a/server/services/execution/dlq.py+++ b/server/services/execution/dlq.py@@ -14,10 +14,13 @@ Usage:await dlq.add_failed_node(ctx, node, inputs, error)"""-from typing import Dict, Any, Protocol+from typing import Dict, Any, Protocol, TYPE_CHECKINGfrom core.logging import get_loggerfrom .models import ExecutionContext, NodeExecution, DLQEntry+if TYPE_CHECKING:+ from .cache import ExecutionCache+logger = get_logger(__name__)diff --git a/server/services/execution/executor.py b/server/services/execution/executor.pyindex f0645ed1..f721af68 100644--- a/server/services/execution/executor.py+++ b/server/services/execution/executor.py@@ -22,12 +22,11 @@ from .models import (WorkflowStatus,NodeExecution,hash_inputs,- RetryPolicy,get_retry_policy,)from .cache import ExecutionCache-from .conditions import evaluate_condition, decide_next_edges-from .dlq import create_dlq_handler, DLQHandlerProtocol, NullDLQHandler+from .conditions import evaluate_condition+from .dlq import create_dlq_handlerlogger = get_logger(__name__)@@ -1004,7 +1003,7 @@ class WorkflowExecutor:logger.debug("Computed execution layers",layer_count=len(layers),- layers=[[n[:8] for n in l] for l in layers])+ layers=[[n[:8] for n in layer] for layer in layers])return layersdiff --git a/server/services/execution/models.py b/server/services/execution/models.pyindex 0ce3fda8..820cfae2 100644--- a/server/services/execution/models.py+++ b/server/services/execution/models.py@@ -8,8 +8,7 @@ import hashlibimport jsonimport timeimport uuid-from dataclasses import dataclass, field, asdict-from datetime import datetime+from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Dict, Any, List, Optionaldiff --git a/server/services/execution/recovery.py b/server/services/execution/recovery.pyindex e26a2369..8dbe341a 100644--- a/server/services/execution/recovery.py+++ b/server/services/execution/recovery.py@@ -8,7 +8,7 @@ Runs as background task to:import asyncioimport time-from typing import Dict, Any, List, Optional, Callable, Awaitable+from typing import List, Optional, Callable, Awaitablefrom core.logging import get_loggerfrom .models import TaskStatus, WorkflowStatus@@ -209,8 +209,8 @@ class RecoverySweeper:Number of executions cleaned up"""cleaned = 0- max_age_seconds = max_age_hours * 3600- current_time = time.time()+ max_age_hours * 3600+ time.time()# This would need a scan of all execution keys# For now, we rely on Redis TTL for cleanupdiff --git a/server/services/google_oauth.py b/server/services/google_oauth.pyindex 980a7c54..9fad0eb6 100644--- a/server/services/google_oauth.py+++ b/server/services/google_oauth.py@@ -73,6 +73,16 @@ def get_oauth_endpoints() -> Dict[str, str]:config = _load_config()return config.get("oauth", _get_default_config()["oauth"])+def get_callback_paths() -> Dict[str, str]:+ """Get OAuth callback paths from config."""+ config = _load_config()+ oauth = config.get("oauth", {})+ return {+ "google": oauth.get("google_callback_path", "/api/google/callback"),+ "twitter": oauth.get("twitter_callback_path", "/api/twitter/callback"),+ }++def get_service_config(service: str) -> Dict[str, Any]:"""Get service-specific config (base_url, version, etc.)."""config = _load_config()@@ -119,7 +129,7 @@ class GoogleOAuth:self,client_id: str,client_secret: str,- redirect_uri: str = "http://localhost:3010/api/google/callback",+ redirect_uri: str,scopes: Optional[List[str]] = None,):self.client_id = client_id@@ -173,6 +183,7 @@ class GoogleOAuth:_oauth_states[state] = {"created_at": time.time(),"data": state_data or {"mode": "owner"},+ "redirect_uri": self.redirect_uri,}logger.info("Generated Google OAuth URL", state=state[:8])diff --git a/server/services/handlers/android.py b/server/services/handlers/android.pyindex f11700b8..027585a6 100644--- a/server/services/handlers/android.py+++ b/server/services/handlers/android.py@@ -3,7 +3,6 @@import jsonfrom typing import Dict, Any, TYPE_CHECKINGfrom core.logging import get_logger-from constants import ANDROID_SERVICE_NODE_TYPESif TYPE_CHECKING:from services.android_service import AndroidService@@ -75,7 +74,7 @@ async def handle_android_service(service_params[key] = parameters[key]logger.debug(f"[ANDROID DEBUG] node_type={node_type} -> service_id={service_id}, action={action}, host={android_host}, port={android_port}, service_params={service_params}")- logger.debug(f"[ANDROID DEBUG] About to call android_service.execute_service")+ logger.debug("[ANDROID DEBUG] About to call android_service.execute_service")result = await android_service.execute_service(node_id=node_id,@@ -85,5 +84,5 @@ async def handle_android_service(android_host=android_host,android_port=android_port)- logger.debug(f"[ANDROID DEBUG] Got result from android_service")+ logger.debug("[ANDROID DEBUG] Got result from android_service")return resultdiff --git a/server/services/handlers/apify.py b/server/services/handlers/apify.pyindex eb353a1c..700c755f 100644--- a/server/services/handlers/apify.py+++ b/server/services/handlers/apify.py@@ -168,7 +168,7 @@ async def handle_apify_actor(logger.warning(f"[Apify] Actor {actor_id} timed out")return {"success": False,- "error": f"Actor timed out. Try increasing the timeout.",+ "error": "Actor timed out. Try increasing the timeout.","result": {"run_id": run_id,"actor_id": actor_id,@@ -222,7 +222,7 @@ async def handle_apify_actor(if "401" in error_msg or "Unauthorized" in error_msg:error_msg = "Invalid Apify API token. Please check your credentials."elif "404" in error_msg or "not found" in error_msg.lower():- error_msg = f"Actor not found. Check the actor ID."+ error_msg = "Actor not found. Check the actor ID."return {"success": False,"error": error_msg,diff --git a/server/services/handlers/calendar.py b/server/services/handlers/calendar.pyindex 6de6f974..344bbfc7 100644--- a/server/services/handlers/calendar.py+++ b/server/services/handlers/calendar.py@@ -6,7 +6,7 @@ API Reference: https://developers.google.com/workspace/calendar/api/v3/referenceimport asyncioimport timefrom datetime import datetime, timedelta-from typing import Any, Dict, List, Optional+from typing import Any, Dictfrom googleapiclient.discovery import builddiff --git a/server/services/handlers/code.py b/server/services/handlers/code.pyindex 9c52adc3..a41d5a6e 100644--- a/server/services/handlers/code.py+++ b/server/services/handlers/code.py@@ -1,6 +1,5 @@"""Code execution node handlers - Python and JavaScript executors."""-import jsonimport timefrom datetime import datetimefrom typing import Dict, Any, Optional@@ -42,14 +41,13 @@ async def handle_python_executor(Returns:Execution result dict with output and console output"""- import sysimport iostart_time = time.time()console_output = ""try:code = parameters.get('code', '')- timeout = int(parameters.get('timeout', 30))+ int(parameters.get('timeout', 30))if not code.strip():return {diff --git a/server/services/handlers/contacts.py b/server/services/handlers/contacts.pyindex 55c31a45..e333fe78 100644--- a/server/services/handlers/contacts.py+++ b/server/services/handlers/contacts.py@@ -5,7 +5,7 @@ API Reference: https://developers.google.com/people/api/restimport asyncioimport time-from typing import Any, Dict, List+from typing import Any, Dictfrom googleapiclient.discovery import build@@ -69,7 +69,7 @@ def _format_contact(person: Dict[str, Any]) -> Dict[str, Any]:emails = person.get('emailAddresses', [])phones = person.get('phoneNumbers', [])organizations = person.get('organizations', [])- addresses = person.get('addresses', [])+ person.get('addresses', [])photos = person.get('photos', [])# Get primary valuesdiff --git a/server/services/handlers/drive.py b/server/services/handlers/drive.pyindex 2fa7731a..1e12a1cf 100644--- a/server/services/handlers/drive.py+++ b/server/services/handlers/drive.py@@ -6,11 +6,11 @@ API Reference: https://developers.google.com/drive/api/v3/referenceimport asyncioimport ioimport time-from typing import Any, Dict, Optional+from typing import Any, Dictimport httpxfrom googleapiclient.discovery import build-from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload, MediaIoBaseDownload+from googleapiclient.http import MediaIoBaseUpload, MediaIoBaseDownloadfrom core.logging import get_loggerfrom services.handlers.google_auth import get_google_credentialsdiff --git a/server/services/handlers/http.py b/server/services/handlers/http.pyindex 9be336b9..181ab703 100644--- a/server/services/handlers/http.py+++ b/server/services/handlers/http.py@@ -69,7 +69,7 @@ async def handle_http_request(# Parse response datatry:response_data = response.json()- except:+ except Exception:response_data = response.textresult_data = {diff --git a/server/services/handlers/sheets.py b/server/services/handlers/sheets.pyindex 045ef9aa..cb471bfe 100644--- a/server/services/handlers/sheets.py+++ b/server/services/handlers/sheets.py@@ -5,7 +5,7 @@ API Reference: https://developers.google.com/workspace/sheets/api/reference/restimport asyncioimport time-from typing import Any, Dict, List+from typing import Any, Dictfrom googleapiclient.discovery import builddiff --git a/server/services/handlers/social.py b/server/services/handlers/social.pyindex aed269cc..25cf907f 100644--- a/server/services/handlers/social.py+++ b/server/services/handlers/social.py@@ -8,7 +8,7 @@ Supported platforms: WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat, Eimport timefrom datetime import datetime-from typing import Dict, Any, Optional+from typing import Dict, Anyfrom core.logging import get_loggerlogger = get_logger(__name__)diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 38e5f826..d3512d7b 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -16,8 +16,7 @@ from core.logging import get_loggerfrom constants import ANDROID_SERVICE_NODE_TYPESif TYPE_CHECKING:- from services.ai import AIService- from core.database import Database+ passlogger = get_logger(__name__)@@ -263,7 +262,7 @@ async def _execute_http_request(args: Dict[str, Any],# Parse headers from node paramstry:default_headers = json.loads(node_params.get('headers', '{}'))- except:+ except Exception:default_headers = {}logger.debug(f"[HTTP Tool] {method} {full_url}")@@ -280,7 +279,7 @@ async def _execute_http_request(args: Dict[str, Any],# Try to parse JSON responsetry:data = response.json()- except:+ except Exception:data = response.textreturn {@@ -374,7 +373,7 @@ except Exception as e:if result.returncode == 0:try:return json.loads(result.stdout.strip())- except:+ except Exception:return {"success": True, "output": result.stdout.strip()}else:return {"error": result.stderr or "Python execution failed"}@@ -387,7 +386,7 @@ except Exception as e:finally:try:os.unlink(temp_path)- except:+ except Exception:pass@@ -456,7 +455,7 @@ try {{if result.returncode == 0:try:return json.loads(result.stdout.strip())- except:+ except Exception:return {"success": True, "output": result.stdout.strip()}else:return {"error": result.stderr or "JavaScript execution failed"}@@ -471,7 +470,7 @@ try {{finally:try:os.unlink(temp_path)- except:+ except Exception:passdiff --git a/server/services/handlers/utility.py b/server/services/handlers/utility.pyindex e5c1e6f2..fac959c4 100644--- a/server/services/handlers/utility.py+++ b/server/services/handlers/utility.py@@ -290,7 +290,7 @@ async def handle_start(initial_data_str = parameters.get('initialData', '{}')try:initial_data = json.loads(initial_data_str)- except:+ except Exception:initial_data = {}return {@@ -667,7 +667,7 @@ async def handle_console(# fieldPath was likely a template like {{aiagent.response}} that got resolved# Use the resolved value directly instead of navigatinglog_value = field_path- logger.debug(f"[Console] Using resolved fieldPath value directly")+ logger.debug("[Console] Using resolved fieldPath value directly")else:# fieldPath is a literal path like "response" or "data.items[0]"log_value = _navigate_field_path(input_data, field_path)diff --git a/server/services/memory_store.py b/server/services/memory_store.pyindex 4533c601..e2f78c5c 100644--- a/server/services/memory_store.py+++ b/server/services/memory_store.py@@ -3,7 +3,7 @@Uses standard Python data structures with LangChain message compatibility.No deprecated APIs - follows LangChain 0.3+ recommendations."""-from typing import Dict, List, Optional, Callable+from typing import Dict, List, Optionalfrom dataclasses import dataclass, fieldfrom datetime import datetimeimport loggingdiff --git a/server/services/oauth_utils.py b/server/services/oauth_utils.pynew file mode 100644index 00000000..fe0dfdbd--- /dev/null+++ b/server/services/oauth_utils.py@@ -0,0 +1,45 @@+"""Derive OAuth redirect URIs from request context -- no hardcoded ports.++WebSocket handlers call get_redirect_uri(websocket, "google") to build the full+callback URL at runtime. The callback *path* comes from google_apis.json; the+base URL (scheme + host + port) comes from the connection itself.++ ws://localhost:3010/ws/status -> http://localhost:3010/api/google/callback+ wss://flow.zeenie.xyz/ws/status -> https://flow.zeenie.xyz/api/google/callback+ http://localhost:3010/api/google -> http://localhost:3010/api/google/callback+"""++from urllib.parse import urlparse++from services.google_oauth import get_callback_paths+++def get_base_url(connection) -> str:+ """Derive HTTP base URL from a Starlette WebSocket or Request.++ Works with both ``WebSocket.base_url`` and ``Request.base_url``.+ Strips the path and converts ws(s) to http(s).+ """+ raw = str(connection.base_url).rstrip("/")+ parsed = urlparse(raw)++ # Convert ws(s) scheme to http(s)+ scheme = parsed.scheme.replace("ws", "http") if "ws" in parsed.scheme else parsed.scheme++ # netloc includes host:port+ return f"{scheme}://{parsed.netloc}"+++def get_redirect_uri(connection, provider: str) -> str:+ """Build full OAuth redirect URI from request context + JSON config path.++ Args:+ connection: Starlette ``WebSocket`` or ``Request`` (anything with ``base_url``).+ provider: ``"google"`` or ``"twitter"``.++ Returns:+ Full redirect URI, e.g. ``http://localhost:3010/api/google/callback``.+ """+ paths = get_callback_paths()+ path = paths.get(provider, f"/api/{provider}/callback")+ return get_base_url(connection) + pathdiff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.pyindex 6bfeaede..6f1b91d5 100644--- a/server/services/status_broadcaster.py+++ b/server/services/status_broadcaster.py@@ -5,7 +5,6 @@ Supports all node types, variable updates, and workflow state changes."""import asyncio-import jsonimport orjsonfrom typing import Set, Dict, Any, Optional, Listfrom fastapi import WebSocket@@ -366,13 +365,13 @@ class StatusBroadcaster:relay_url = session.get("relay_url")api_key = session.get("api_key")device_id = session.get("device_id")- device_name = session.get("device_name")+ session.get("device_name")if not relay_url or not api_key:logger.debug("[StatusBroadcaster] Stored session missing relay URL or API key")return- logger.info(f"[StatusBroadcaster] Auto-reconnecting to Android relay...",+ logger.info("[StatusBroadcaster] Auto-reconnecting to Android relay...",relay_url=relay_url, device_id=device_id)# Attempt to reconnectdiff --git a/server/services/temporal/worker.py b/server/services/temporal/worker.pyindex 7e3102f0..20133dd4 100644--- a/server/services/temporal/worker.py+++ b/server/services/temporal/worker.py@@ -29,7 +29,6 @@ print(f"[Worker Import] MachinaWorkflow loaded from: {MachinaWorkflow.__module__from .activities import (NodeExecutionActivities,create_shared_session,- execute_node_activity,)logger = get_logger(__name__)diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.pyindex 002f55da..fe36d407 100644--- a/server/services/temporal/workflow.py+++ b/server/services/temporal/workflow.py@@ -243,7 +243,7 @@ class MachinaWorkflow:return node_id, {"success": False, "error": str(e)}# Wait for first completion using Temporal's wait- handles = [h for _, h in items]+ [h for _, h in items]# Use asyncio.wait pattern via workflow.waitawait workflow.wait_condition(diff --git a/server/services/twitter_oauth.py b/server/services/twitter_oauth.pyindex e348bac6..9af0536c 100644--- a/server/services/twitter_oauth.py+++ b/server/services/twitter_oauth.py@@ -76,7 +76,7 @@ class TwitterOAuth:Twitter/X OAuth 2.0 with PKCE flow implementation.Usage:- oauth = TwitterOAuth(client_id="...", redirect_uri="http://localhost:3010/api/twitter/callback")+ oauth = TwitterOAuth(client_id="...", redirect_uri="http://localhost:3010/api/twitter/callback") # URI derived at runtime# Step 1: Generate authorization URLauth_data = oauth.generate_authorization_url()@@ -92,8 +92,8 @@ class TwitterOAuth:def __init__(self,client_id: str,+ redirect_uri: str,client_secret: Optional[str] = None,- redirect_uri: str = "http://localhost:3010/api/twitter/callback",scopes: Optional[list] = None,):"""@@ -128,6 +128,7 @@ class TwitterOAuth:_oauth_states[state] = {"code_verifier": code_verifier,"created_at": time.time(),+ "redirect_uri": self.redirect_uri,}params = {