Skip to content

feat: analytics tracing, billing accuracy, and admin navigation fixes (+ streaming demo & Copilot docs) - #591

Merged
maxtechera merged 7 commits into
productionfrom
staging
Oct 10, 2025
Merged

feat: analytics tracing, billing accuracy, and admin navigation fixes (+ streaming demo & Copilot docs)#591
maxtechera merged 7 commits into
productionfrom
staging

Conversation

@ct3685

@ct3685 ct3685 commented Oct 10, 2025

Copy link
Copy Markdown

Title

feat: analytics tracing, billing accuracy, and admin navigation fixes (+ streaming demo & Copilot docs)

Description

Motivation & Scope

  • Introduces robust analytics tracing via Langfuse with environment-based overrides, node-level spans, and safe serialization.
  • Improves admin navigation and chatflow canvas linking under /sidekick-studio.
  • Hardens follow-up prompts when credentials are unavailable.
  • Corrects billing calculations and ownership attribution using platform node detection.
  • Adds a direct SSE streaming demo and Copilot auto-deploy documentation.
  • Synchronizes embed packages with latest versions.
  • Includes staging merges reflected in server and component interfaces.

UI — Admin & Org Credentials

  • packages-answers/ui/src/Admin/Chatflows/index.tsx
    • Removed react-router-dom Link usage for certain elements; now uses absolute paths and window.open / anchor tags:
      • getCanvasFullUrl(chatflow) centralizes URL generation with /sidekick-studio prefix.
      • Template “View” now opens getCanvasFullUrl(...).
      • Chatflow name is rendered as <Typography component="a" href=... target="_blank">.
    • Replaced full page reload on rollback with refreshChatflows() for smoother UX.
    • “Back to admin” now navigates to /sidekick-studio/admin via window.location.href.
  • packages-answers/ui/src/OrgCredentials/OrgCredentialsManager.tsx
    • Adds a “Back to admin” button pointing to /sidekick-studio/admin.

DevEx — Copilot

  • .gitignore: track scripts/copilot-auto-readme.md.
  • copilot/scripts/copilot-auto-readme.md: install & usage for pnpm copilot:auto.

Components — Agentflow/LLM/ConditionAgent

  • Common Enhancements
    • Import additionalCallbacks and wire Langfuse through options._llmCallOptions.callbacks.
    • Introduce options._llmCallOptions to pass signal and callbacks consistently to invoke/stream.
    • Streaming handlers now accept options instead of raw AbortController.
    • Summary buffer & history helpers accept options and use shared call options.
  • Agent/Agent.ts
    • Import LangfuseSpanClient; attach options._parentToolSpan.
    • Create per-tool Langfuse spans (createToolSpan) and finalize with finishToolSpan on success/error.
    • Route all LLM calls through options._llmCallOptions; propagate spans during tool loops.
  • ConditionAgent/ConditionAgent.ts & LLM/LLM.ts
    • Same callback + call-option wiring as Agent.
    • Token-limit summary paths now use llmCallOptions.

Components — Utilities & Exports

  • src/flowCredentialExtractor.ts
    • Adds category?, visibility?, and hasPlatformAINodes detection for AAI nodes (Chat Models, Embeddings).
    • Returned type ExtractionResult now includes hasPlatformAINodes.
  • src/followUpPrompts.ts
    • Defensive credential fetch with try/catch; skip generation if missing/empty.
  • src/handler.ts
    • New helpers:
      • applyEnvAnalyticsOverrides() – env-first analytics config (e.g., LANGFUSE_*).
      • isAnalyticsEnabled() – centralized enablement check.
    • additionalCallbacks() honors parent trace/span; toggles handler activity flags.
    • AnalyticHandler:
      • Tracks whether callback-based spans are active; supports node-level spans.
      • Safe JSON serialization for trace payloads.
      • Tool span helpers: createToolSpan / finishToolSpan.
      • Reads env overrides and supports provider config precedence.
    • Exports: re-exports flowCredentialExtractor.
  • src/index.ts
    • Exports flowCredentialExtractor.

Server — Billing, Interfaces, Predictions, Build

  • Billing
    • aai-utils/billing/config.ts: default credit price set to $0.00004 (base: $20 / 500k).
    • core/BillingService.ts: reads BILLING_CONFIG.CREDIT_TO_USD for credit calculations.
    • langfuse/LangfuseProvider.ts:
      • Determines aiCredentialsOwnership using extractCredentialsAndModels + DB check for AAI nodes.
      • Caches platform-node detection per chatflow during a sync; clears afterward.
      • Includes ownership flag in cost breakdown and credit conversion.
  • Interfaces
    • server/src/Interface.ts: IExecuteFlowParams.user made optional.
  • Predictions
    • services/predictions/index.ts: user now optional when building chatflow.
  • Agentflow/Chatflow Build
    • utils/buildAgentflow.ts
      • Accepts optional user.
      • Uses isAnalyticsEnabled(); initializes AnalyticHandler with useNodeLevelLangfuseSpans.
      • Creates per-node Langfuse spans (spanName=node label/name), attaches inputs/outputs, status, timings.
      • Propagates parentLangfuseTrace/span through recursive and iteration paths.
      • Updates parent trace metadata (final output, status, node count).
    • utils/buildChatflow.ts: user optional during util build.

Demos

  • streaming-demo.html: Browser-only SSE demo to connect directly to /api/v1/prediction/:chatflowId with live token streaming, node progress, event counters, and structured result rendering.

Embed Packages

  • Submodule packages/embedfa836ede40e0e74fd7df445e367aeaaa2b3d8cfc.
  • packages/embed-react/package.json
    • Version 1.0.7 → 3.0.10.
    • Peer dep aai-embed ^3.0.0 → ^3.0.10.

Expected Impact

  • Observability: End-to-end tracing with parent trace/span chaining; per-tool spans; safer payloads.
  • UX: Faster admin rollback refresh; consistent /sidekick-studio routing; explicit external links.
  • Stability: Follow-up prompts no longer fail hard on missing creds.
  • Billing Accuracy: Correct platform vs user ownership attribution; configurable credit pricing.
  • DX: Turnkey SSE demo; environment-driven analytics setup.

Breaking Changes

  • Type changes: user is now optional in multiple server interfaces (IExecuteFlowParams, execute paths). Callers relying on non-null assertions may need adjustments.
  • Routing: Admin links now favor absolute /sidekick-studio/... paths and direct navigation; any components expecting react-router-dom Link wrapping those elements may need review.
  • Analytics Behavior: Environment variables can override UI analytics settings (Langfuse). Deployments should verify envs to avoid unintended tracing.

Config / Env

  • New/Updated:
    • LANGFUSE_SECRET_KEY, LANGFUSE_PUBLIC_KEY, LANGFUSE_HOST, LANGFUSE_RELEASE, GIT_COMMIT_HASH (env override support).
    • BILLING_CREDIT_PRICE_USD default now 0.00004.
    • BILLING_MARGIN_MULTIPLIER (existing).
  • No DB schema changes apparent.

Tests / Validation

  • Admin UI
    • Verify canvas links open correct paths for AGENTFLOW, MULTIAGENT, and default types.
    • Confirm rollback uses refreshChatflows() without full reload.
    • Check “Back to admin” buttons in Admin & Org Credentials navigate to /sidekick-studio/admin.
  • Analytics
    • With Langfuse envs set, confirm callbacks activate and node/tool spans appear with inputs/outputs and statuses.
    • Validate parent trace updates on flow completion, including node count and final output.
  • Billing
    • Run Langfuse sync with traces from chatflows containing AAI nodes; ensure aiCredentialsOwnership resolves to platform and credits compute via BILLING_CONFIG.
  • Follow-up Prompts
    • Remove/invalid credential → generation skipped without throwing; logs warning.
  • Streaming Demo
    • Use streaming-demo.html against /api/v1/prediction/:id with streaming: true and confirm live tokens, events, and structured results render.
  • Embed
    • Build aai-embed-react@3.0.10 with aai-embed@^3.0.10; smoke test mounting.

ct3685 added 3 commits October 8, 2025 17:36
…ndency (#588)

chore: bump version of aai-embed-react to 3.0.10 and update peer
dependency
- Simplified URL generation for chatflows by consolidating logic in
`getCanvasFullUrl` and `getCanvasRoute`.
- Updated the back navigation button to use the new
`/sidekick-studio/admin` path.
- Enhanced data refresh mechanism to avoid full page reloads, improving
user experience.
@vercel

vercel Bot commented Oct 10, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
answerai-docs Ready Ready Preview Oct 10, 2025 6:42pm
the-answerai Ready Ready Preview Oct 10, 2025 6:42pm

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting

Comment on lines +173 to +179
}
}

const getCanvasFullUrl = (chatflow: any) => {
// Alias for getCanvasRoute for backward compatibility
// Both now return the same full URL with /sidekick-studio prefix
return getCanvasRoute(chatflow)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid hard-coding sidekick-studio in chatflow routes

The new getCanvasRoute now prepends /sidekick-studio to every chatflow canvas URL and getCanvasFullUrl simply delegates to it. The admin UI’s router defines canvas paths at /canvas/:id and /admin/... (see packages-answers/ui/src/Admin/index.tsx), so when the admin module is served at the default root (e.g., Flowise’s /admin/chatflows), clicking a chatflow or opening a default template now navigates to /sidekick-studio/..., which has no matching route and results in a 404. Consider deriving the prefix from the router’s basename or keeping the relative /canvas paths so both deployments continue working.

Useful? React with 👍 / 👎.

@ct3685 ct3685 changed the title Staging chore: improve admin dashboard routing and add Copilot auto-deploy readme Oct 10, 2025
@ct3685 ct3685 added bug Something isn't working hotfix minor-update patch labels Oct 10, 2025
maxtechera and others added 3 commits October 10, 2025 16:03
…ath optimization (#548)

## Summary
Improves credential ownership detection for billing by adding
intelligent caching and fast-path optimization for AAI platform nodes.

## Changes
- Added `hasPlatformAINodes` detection to quickly identify AAI platform
AI nodes
- Implemented caching mechanism (`platformNodeCache`) to reduce database
queries
- Added validation layer in `calculateCosts` to double-check ownership
- Exported `flowCredentialExtractor` for reusability

## Performance Improvements
- **Fast-path optimization**: AAI platform nodes are detected early,
skipping unnecessary credential lookups
- **Smart caching**: Flow platform status cached during sync operations,
auto-clears after completion
- **Reduced DB queries**: Cache prevents redundant database calls for
the same chatflow

## Technical Details
- Cache lifecycle managed per sync operation (clears after each sync)
- Graceful fallback when chatflow data unavailable
- No breaking changes to existing interfaces

## Testing
- [x] Verified credential detection works correctly
- [x] Tested caching behavior across multiple traces
- [x] Confirmed fallback behavior when chatflow not found

---------

Co-authored-by: Claude <noreply@anthropic.com>
…ges (#593)

## Problem
Multiple navigation issues in admin pages:
1. **Admin Chatflows**: Mixed usage of React Router and window.open() in
Next.js environment caused:
- Default template view button creating
`/sidekick-studio/sidekick-studio/admin` (double prefix)
- Chatflow name links generating `/canvas/{id}` instead of
`/sidekick-studio/canvas/{id}` (404s)
   - Inconsistent routing behavior
2. **Organization Credentials**: Missing "Back to admin" button for
navigation consistency

## Solution
**Admin Chatflows Navigation**
(`packages-answers/ui/src/Admin/Chatflows/index.tsx`):
- ✅ Standardized all navigation to use absolute URLs with full
`/sidekick-studio` prefix
- ✅ Replaced React Router `<Link>` with native anchor tags and
`window.location`
- ✅ Fixed default template view button to use `getCanvasFullUrl()`
- ✅ Converted chatflow name link to use `href` with full absolute path
- ✅ Updated back-to-admin button to use `window.location.href`
- ✅ Removed unused React Router dependency

**Organization Credentials**
(`packages-answers/ui/src/OrgCredentials/OrgCredentialsManager.tsx`):
- ✅ Added "Back to admin" button for consistent navigation UX

## Testing
Verified all navigation points correctly route to:
- Regular chatflows: `/sidekick-studio/canvas/{id}` ✅
- Multi-agent v1: `/sidekick-studio/agentcanvas/{id}` ✅
- Agent flows v2: `/sidekick-studio/v2/agentcanvas/{id}` ✅
- Admin dashboard: `/sidekick-studio/admin` ✅
- Organization credentials: `/sidekick-studio/admin/org-credentials` ✅

## Impact
- Fixes AAI-682 completely
- No more double prefixes or 404 errors
- Consistent navigation experience across all admin pages
- Improved user experience with back buttons on all admin subpages
## Summary

Implements centralized analytics configuration via environment
variables, enabling Langfuse (and future providers) to be enabled
globally without UI configuration. This provides platform-wide
observability without requiring per-chatflow/agentflow setup.

### Problem
- Previously, analytics providers (like Langfuse) could only be
configured per-chatflow/agentflow via UI
- No way to enable analytics globally across all flows for platform-wide
observability
- Code duplication between `additionalCallbacks()` and `AnalyticHandler`
for env var handling
- Agentflows didn't respect environment variable overrides

### Solution
- Added `applyEnvAnalyticsOverrides()` helper function for DRY env var
handling
- Added `isAnalyticsEnabled()` to properly gate analytics initialization
- Fixed `AnalyticHandler` to respect env overrides in agentflows
- Fixed `AnalyticHandler.initializeProvider()` to use `providerConfig`
values
- Refactored `additionalCallbacks()` to use shared helper

### Changes

#### `packages/components/src/handler.ts`
- Added `applyEnvAnalyticsOverrides()` - centralized logic for applying
env var overrides
- Added `isAnalyticsEnabled()` - checks if analytics is enabled via UI
or env vars
- Refactored `additionalCallbacks()` to use helper (13 lines → 2 lines)
- Updated `AnalyticHandler.init()` to apply env overrides
- Updated `AnalyticHandler.constructor()` to store processed config
- Fixed `AnalyticHandler.initializeProvider()` to respect
`providerConfig` values

#### `packages/server/src/utils/buildAgentflow.ts`
- Fixed gating condition to use `isAnalyticsEnabled()` instead of
`chatflow.analytic` check
- Ensures agentflows work with env vars only (previously broken)

### Environment Variables

When `LANGFUSE_SECRET_KEY` is set, Langfuse will be automatically
enabled for **all** chatflows and agentflows:

- `LANGFUSE_SECRET_KEY` - Required to enable Langfuse
- `LANGFUSE_PUBLIC_KEY` - Optional, Langfuse public key
- `LANGFUSE_HOST` - Optional, defaults to `https://cloud.langfuse.com`
- `LANGFUSE_RELEASE` - Optional, version/release tag for traces

Environment variables take precedence over UI configuration.

### Benefits

✅ Platform-wide observability without UI configuration  
✅ Single source of truth for env var handling  
✅ Works for chatflows, agentflows, and multi-agent graphs  
✅ Extensible pattern for adding more providers (LangSmith, Arize, etc.)
✅ Eliminated 100+ lines of code duplication  

### Testing

- [x] Chatflows with env vars only
- [x] Agentflows with env vars only (previously broken)
- [x] Chatflows with UI config only
- [x] Agentflows with UI config only
- [x] Both env + UI (env wins)
- [x] Cache invalidation when config changes

## Test plan

- [ ] Deploy to staging
- [ ] Set `LANGFUSE_SECRET_KEY` env var
- [ ] Execute chatflow - verify trace appears in Langfuse
- [ ] Execute agentflow - verify trace appears in Langfuse
- [ ] Execute multi-agent graph - verify trace appears in Langfuse

---------

Co-authored-by: Brad Taylor <bradtaylorsf@gmail.com>
Comment thread streaming-demo.html Dismissed
refactor: remove unused getCanvasRoute function
@ct3685 ct3685 changed the title chore: improve admin dashboard routing and add Copilot auto-deploy readme feat: analytics tracing, billing accuracy, and admin navigation fixes (+ streaming demo & Copilot docs) Oct 10, 2025
@ct3685 ct3685 added the enhancement New feature or request label Oct 10, 2025
@ct3685

ct3685 commented Oct 10, 2025

Copy link
Copy Markdown
Author

@codex please re-review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting

Comment thread packages/components/src/handler.ts
@maxtechera
maxtechera merged commit 604e6ad into production Oct 10, 2025
8 of 9 checks passed
@maxtechera
maxtechera temporarily deployed to staging - aai-unified2-flowise-moonstruck October 10, 2025 20:05 — with Render Inactive
maxtechera added a commit that referenced this pull request Oct 23, 2025
## 📦 Release Summary

This release includes updates from staging to production, bringing
multiple improvements, fixes, and new features.

## 🎯 Key Changes

### Recent Updates
- **HOTFIX**: Remove metadata from Stripe events
- **fix**: Handle Stripe 35-day limitation for historical billing data
(#624)
- **chore**: Updates to fix publish automation (#623)
- **feat**: Added automation for publishing aai-embed-react (#616)
- **feat**: Comprehensive export/import functionality enhancement
(AAI-501) (#469)

### Previous Releases Included
- Billing Metadata Filtering - 22.10.2025 (#622)
- Chat Drawer Pagination - 22.10.2025 (#621)
- Billing Tag Self-Healing and Optimized Trace Fetching (#617)
- Facebook Pixel Tracking Fixes (#608)
- JLINC audit log, env overrides, and partnership page updates (#597)
- Analytics tracing, billing accuracy, and admin navigation fixes (#591)

## 📊 Impact Summary
- **Files changed**: 2956 files
- **Additions**: 312,083 lines
- **Deletions**: 25,803 lines

## ✅ Pre-Release Checklist

- [ ] All tests passing on staging environment
- [ ] No critical errors in staging logs
- [ ] Database migrations reviewed and tested
- [ ] Environment variables documented
- [ ] Monitoring alerts configured
- [ ] Rollback plan documented

## 🚀 Deployment Notes

This is a standard release from staging to production. Please ensure all
pre-release checks are completed before approving.

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

---------

Co-authored-by: DiegoC <diecoscai@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Cameron Taylor <50385537+ct3685@users.noreply.github.com>
Co-authored-by: Jaime Morales <jaime.raul.morales@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working enhancement New feature or request hotfix minor-update patch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants