Skip to content

Conversation

@andybraren
Copy link
Collaborator

@andybraren andybraren commented Jan 14, 2026

Implementation of a basic user feedback mechanism for messages using Langfuse's Scores API.

This adds thumbs up/down buttons below messages from agents and a modal for the user to provide more details before submitting their feedback.

The project, session ID, username, and selected workflow get stored in the Metadata field, and the user's comment and selected chat message get stored in the Comment field. If the user selects "Include all messages" the full transcript is included in the Comment field as well.

Future enhancements

  • "Include all messages" should probably be "Include all previous messages" leading up to the one that the user is providing feedback on, but I hit some weird issues. Can try again in a follow-up.

Screenshots

2026-01-14 11 13 14 2026-01-16 03 07 27 2026-01-16 03 27 07 2026-01-16 03 17 03 2026-01-16 03 20 35

@andybraren andybraren marked this pull request as draft January 14, 2026 16:13
@github-actions

This comment has been minimized.

- Introduced a new langfuseClient module to encapsulate LangfuseWeb client initialization using only the public key.
- Updated the feedback route to build context from the session and send feedback directly to Langfuse using the new SDK, eliminating the need for secret keys.
- Simplified the feedback submission process by removing unnecessary payload preparation and API call logic.

This change enhances security and simplifies the feedback submission process.
- Updated button and checkbox components to include a cursor pointer style for better user interaction feedback.
- This change improves the overall usability and accessibility of the UI elements.
- Enhanced FeedbackButtons to include cursor pointer style for better interaction.
- Simplified FeedbackModal by removing unnecessary fragments and updating text for clarity.
- Adjusted placeholder text and button labels for a more intuitive user experience.

These changes aim to improve usability and accessibility in the feedback submission process.
- Replaced the AlertTriangle icon with Info for a clearer privacy indication.
- Updated the label from "Include full transcript" to "Include previous messages" for better understanding.
- Simplified the privacy disclaimer text to clarify how feedback and messages will be stored.

These changes aim to improve user comprehension and enhance the overall feedback experience.
- Updated the feedback comment construction to focus on user-provided content.
- Introduced a metadata object to encapsulate structured session information (project, session, user).
- Simplified the feedback submission process by adjusting how comments and metadata are sent to the LangfuseWeb SDK.

These changes enhance the clarity and organization of feedback data being sent, improving overall feedback management.
- Added an optional 'workflow' field to the feedback API request type for improved context.
- Updated the feedback submission process to include the workflow in the metadata sent to Langfuse.
- Modified the FeedbackModal to conditionally include the active workflow in the feedback context.

These changes aim to provide better tracking of user feedback related to specific workflows, enhancing the overall feedback management experience.
…ckModal for improved clarity and completeness.
@github-actions
Copy link
Contributor

github-actions bot commented Jan 16, 2026

Claude Code Review

Summary

This PR implements a user feedback mechanism with thumbs up/down buttons on agent messages, allowing users to provide feedback that gets sent to Langfuse. The implementation is clean and follows most frontend patterns, but there are several critical security and privacy issues that must be addressed before merge, plus some architectural concerns.

Issues by Severity

🚫 Blocker Issues

1. CRITICAL: Message Content Privacy Violation

  • Location: components/frontend/src/app/api/feedback/route.ts:80-88
  • Issue: Full message transcript is sent to Langfuse when includeTranscript is checked, potentially exposing sensitive user data, code, API keys, or proprietary information
  • Problem: This violates the platform's privacy-first design documented in CLAUDE.md:342-346 which states "User messages and assistant responses are REDACTED in traces"
  • Impact: Users may unknowingly share sensitive information to Langfuse
  • Fix Required:
    • Either remove the includeTranscript option entirely
    • OR implement content masking/redaction similar to the backend runner's privacy masking
    • OR add very prominent warnings about what will be shared

2. CRITICAL: Missing Secret Key in Langfuse Client

  • Location: components/frontend/src/lib/langfuseClient.ts:27-30
  • Issue: Using LangfuseWeb with only public key - this may not work for server-side score submissions
  • Context: The Langfuse SDK documentation typically requires secret key for server-side operations
  • Verification Needed: Test if scores actually get recorded with this configuration
  • Risk: Feedback silently fails to record, giving users false confidence their feedback was submitted

3. CRITICAL: No Authentication/Authorization on Feedback API

  • Location: components/frontend/src/app/api/feedback/route.ts:37
  • Issue: The /api/feedback route has NO authentication check - anyone can submit arbitrary feedback
  • Attack Vector: Malicious actors could spam the feedback system, pollute Langfuse data, or submit false feedback
  • Fix Required: Add authentication middleware to verify the request comes from an authenticated user
  • Example Fix:
// Add authentication check
const session = await getServerSession(); // or your auth method
if (!session) {
  return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

🔴 Critical Issues

4. Type Safety Violation - any Type

  • Location: components/frontend/src/components/ui/message.tsx:174 (implicit in truncated diff)
  • Rule Violated: Frontend Critical Rule Outcome: Reduce Refinement Time with agent System #1 - Zero any types
  • Fix: Review the full message.tsx changes for any any types and replace with proper types

5. Missing Error Handling in Feedback Submission

  • Location: components/frontend/src/app/api/feedback/route.ts:121-128
  • Issue: Generic error handling doesn't distinguish between different failure modes
  • Problem: User gets "Internal server error" whether it's a validation error, Langfuse error, or network issue
  • Fix: Add specific error handling:
} catch (error) {
  console.error('Error submitting feedback:', error);
  
  if (error instanceof LangfuseError) {
    return NextResponse.json(
      { error: 'Failed to record feedback', details: error.message },
      { status: 502 }
    );
  }
  
  return NextResponse.json(
    { error: 'Internal server error' },
    { status: 500 }
  );
}

6. Missing useCurrentUser Query Definition

  • Location: components/frontend/src/app/projects/[name]/sessions/[sessionName]/page.tsx:192
  • Issue: useCurrentUser is imported from @/services/queries but not defined in the PR diff
  • Risk: Build may fail, or this may be using an undefined hook
  • Fix Required: Verify this hook exists or add it to the PR

🟡 Major Issues

7. FeedbackContext Performance Concern

  • Location: components/frontend/src/contexts/FeedbackContext.tsx:40-51
  • Issue: messages array in dependencies will cause re-renders on every message update
  • Performance Impact: In long sessions with many messages, this could cause unnecessary re-renders of all feedback buttons
  • Fix: Consider using a ref for messages or memoizing differently:
const messagesRef = useRef(messages);
useEffect(() => {
  messagesRef.current = messages;
}, [messages]);

8. Environment Variables Not Validated

  • Location: components/manifests/base/frontend-deployment.yaml:additions
  • Issue: PR adds Langfuse env vars to deployment but doesn't show validation that they're set
  • Risk: Silent failure if env vars are missing in production
  • Fix: Add startup validation or better logging when Langfuse is not configured

9. Missing Loading States in FeedbackButtons

  • Location: components/frontend/src/components/feedback/FeedbackButtons.tsx:37-45
  • Issue: No loading state while modal is submitting, user can click button again
  • Frontend Rule Violated: "All buttons have loading states"
  • Fix: Disable buttons or show loading indicator while feedbackModalOpen is true

10. No Success Toast/Notification

  • Location: components/frontend/src/components/feedback/FeedbackModal.tsx:117-121
  • Issue: After successful submission, modal just closes - no user confirmation
  • UX Problem: Users may not know if their feedback was actually submitted
  • Fix: Add a toast notification on success

🔵 Minor Issues

11. Inconsistent Error Message Formatting

  • Location: components/frontend/src/app/api/feedback/route.ts:125
  • Issue: Error responses don't follow a consistent structure with the success response
  • Suggestion: Use consistent { success: false, error: string } format

12. Unused messageTimestamp Parameter

  • Location: Multiple files
  • Issue: messageTimestamp is passed around but never actually used
  • Fix: Either use it (add to metadata) or remove it

13. Magic Numbers in Code

  • Location: components/frontend/src/app/api/feedback/route.ts:94
  • Issue: Date.now() for fallback traceId is not deterministic
  • Better Approach: Use a more predictable ID format or UUID

14. Missing JSDoc Comments

  • Location: components/frontend/src/contexts/FeedbackContext.tsx
  • Issue: Public API (FeedbackProvider, hooks) lacks documentation
  • Fix: Add JSDoc comments explaining usage

15. Cursor CSS Rule Duplication

  • Location: components/frontend/src/components/ui/button.tsx:10, checkbox.tsx:16
  • Issue: Adding cursor-pointer to base styles affects ALL buttons/checkboxes globally
  • Risk: May break disabled state styling where cursor-not-allowed should show
  • Fix: Verify this doesn't break disabled states, or use more specific selectors

Positive Highlights

Excellent UX Design: The inline feedback buttons with visual confirmation (check mark) are intuitive and non-intrusive

Good Use of Shadcn Components: Properly uses Dialog, Button, Textarea, Checkbox from the UI library

Privacy Notice: Good job including the privacy disclaimer in the modal

Context Provider Pattern: Clean separation of concerns with FeedbackContext

Graceful Degradation: Components check for context availability and render nothing if unavailable

Type Safety (mostly): Good use of TypeScript types for FeedbackRequest, FeedbackType, etc.

Recommendations

Priority 1 (Must Fix Before Merge)

  1. Add authentication to /api/feedback route - This is a security vulnerability
  2. Remove or redact transcript feature - Privacy violation that contradicts documented platform standards
  3. Verify Langfuse client configuration - Test that scores actually get recorded with public key only
  4. Add LANGFUSE_SECRET_KEY if needed - May be required for server-side score submission

Priority 2 (Should Fix Before Merge)

  1. Add success notification after feedback submission
  2. Fix performance issue with FeedbackContext re-renders
  3. Verify useCurrentUser exists or add it to the PR
  4. Add loading states to feedback buttons during submission

Priority 3 (Nice to Have)

  1. Add better error handling with specific error messages
  2. Remove unused parameters like messageTimestamp
  3. Add documentation to public APIs
  4. Test cursor CSS changes don't break disabled states

Testing Recommendations

Before merge, manually test:

  • Feedback submission with Langfuse configured
  • Feedback submission WITHOUT Langfuse (graceful degradation)
  • Feedback with transcript enabled (verify what actually gets sent)
  • Feedback buttons on multiple messages in same session
  • Feedback modal cancel/close behavior
  • Network errors during submission
  • Unauthenticated access to /api/feedback endpoint (should fail)

References

  • Privacy Standards: CLAUDE.md lines 342-346 (Langfuse privacy-first design)
  • Frontend Rules: CLAUDE.md lines 1113-1135 (zero any, loading states, etc.)
  • Security Standards: .claude/context/security-standards.md

Overall Assessment: This is a well-designed feature with good UX, but has critical security and privacy issues that must be fixed before merge. The transcript feature in particular needs serious reconsideration given the platform's privacy-first approach to Langfuse integration.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

…enhance security and simplify environment variable management.
…streamline environment variable configuration.
@github-actions
Copy link
Contributor

github-actions bot commented Jan 16, 2026

Claude Code Review

Summary

This PR implements a user feedback mechanism for messages in the platform, allowing users to provide thumbs up/down feedback on agent responses with optional comments and full transcript inclusion. The implementation integrates with Langfuse for feedback collection.

Overall Assessment: This is a well-structured implementation with good UX design and privacy considerations. However, there are several critical security and architecture issues that must be addressed before merging.


Issues by Severity

🚫 Blocker Issues

1. Secret Key Exposure in Frontend Deployment (components/manifests/overlays/local-dev/frontend-patch.yaml:41-46)

  • Issue: The LANGFUSE_SECRET_KEY is being injected into the frontend container environment variables
  • Security Risk: Secret keys should NEVER be exposed to the frontend. Even though it's marked as optional: true, this creates a security vulnerability if the secret exists
  • Why Critical: The frontend is a client-side application. Any environment variables (even server-side in Next.js) can potentially be exposed through various attack vectors (SSR leaks, build artifacts, etc.)
  • Fix Required: Remove LANGFUSE_SECRET_KEY from frontend deployment completely. The API route should use server-side only env vars
  • Reference: Per security standards (CLAUDE.md:435-439), never expose secrets in logs or client-accessible contexts

2. Missing Secret Key Protection in API Route (components/frontend/src/lib/langfuseClient.ts:19-24)

  • Issue: The code references process.env.LANGFUSE_SECRET_KEY in the client initialization (though not currently used by LangfuseWeb)
  • Security Risk: If someone updates this code to use the secret key, it would be accessible server-side but shouldn't be in frontend code at all
  • Fix Required: Add explicit comment that SECRET_KEY should never be used in frontend code, or move to backend API
  • Pattern Violation: Violates token security standards (CLAUDE.md:435-439)

3. No Error Handling for Langfuse SDK Failures (components/frontend/src/app/api/feedback/route.ts:108-114)

  • Issue: langfuse.score() is called without error handling (no try-catch around the SDK call itself)
  • Risk: If Langfuse SDK throws an exception, the API returns 500 but user gets generic error
  • Impact: Silent failures in feedback submission, poor UX
  • Fix Required: Wrap langfuse.score() in try-catch with specific error handling
  • Pattern Violation: Error handling pattern (error-handling.md:26-40) requires logging with context

🔴 Critical Issues

4. Type Safety Violation - Any Type Usage (components/frontend/src/components/feedback/FeedbackModal.tsx:95-110)

  • Issue: Manual fetch() call instead of using React Query patterns
  • Pattern Violation: Frontend standards (frontend-development.md:56-70) require ALL data operations use React Query
  • Fix Required: Create a useFeedbackMutation hook in src/services/queries/feedback.ts following the mutation pattern
  • Reference: react-query-usage.md:100-162 for mutation pattern
  • Impact: No caching, no automatic error retry, inconsistent with codebase patterns

5. Missing Authentication/Authorization (components/frontend/src/app/api/feedback/route.ts:37-60)

  • Issue: No validation of user identity or authorization to submit feedback for this session
  • Security Risk: Any user could submit feedback for any session/project they don't have access to
  • Fix Required:
    • Add authentication check (verify bearer token or session cookie)
    • Validate user has access to the specified project/session
    • Compare username from request with authenticated user
  • Pattern: Should follow backend auth patterns (security-standards.md:9-18, k8s-client-usage.md:9-18)

6. Potential PII/Sensitive Data Exposure (components/frontend/src/app/api/feedback/route.ts:84-88)

  • Issue: Full transcript is sent to Langfuse without any sanitization or truncation
  • Privacy Risk: May include sensitive information (API keys, passwords, personal data) from user messages
  • CLAUDE.md Violation: Langfuse documentation (CLAUDE.md:390-402) emphasizes privacy-first design with masking by default
  • Fix Required:
    • Add warning in UI that sensitive data should not be included
    • Consider truncating very long transcripts
    • Add option to exclude specific messages
    • Document in privacy notice what data is collected

7. No Request Rate Limiting (components/frontend/src/app/api/feedback/route.ts)

  • Issue: No rate limiting on feedback submission
  • Risk: Abuse vector - users could spam feedback submissions
  • Fix Required: Add rate limiting middleware (by IP or user)
  • Recommendation: Limit to 10 feedback submissions per minute per user

🟡 Major Issues

8. Message State Not Persisted (components/frontend/src/components/feedback/FeedbackButtons.tsx:28)

  • Issue: submittedFeedback state is local component state, not persisted
  • UX Impact: If user refreshes page, feedback state is lost and buttons reset
  • Fix Required: Either:
    • Store submitted feedback in localStorage with message ID
    • Fetch feedback status from backend on component mount
    • Show submitted state based on Langfuse data

9. Inconsistent Type Definitions (components/frontend/src/app/api/feedback/route.ts:24-35)

  • Issue: Type definition duplicates parts of FeedbackContextValue
  • Maintainability: Changes to context require updating API route types
  • Fix Required: Import and reuse types from FeedbackContext or create shared types file
  • Pattern Violation: Frontend standards (frontend-development.md:74-78) prefer type over interface, but also recommend DRY principle

10. Missing Loading States (components/frontend/src/components/feedback/FeedbackButtons.tsx:61-82)

  • Issue: No loading indicator while feedback is being submitted
  • UX Impact: User doesn't know if click was registered
  • Fix Required: Show subtle loading spinner or disable buttons during submission
  • Pattern: Frontend checklist (CLAUDE.md:1130) requires all buttons have loading states

11. Error State Not Cleared on Modal Close (components/frontend/src/components/feedback/FeedbackModal.tsx:129-134)

  • Issue: handleCancel clears error, but if user closes modal via X button or backdrop click, error persists
  • Fix Required: Clear error in onOpenChange callback or use useEffect to reset on close

12. Accessibility - Missing ARIA Live Region (components/frontend/src/components/feedback/FeedbackModal.tsx:210-215)

  • Issue: Error message not announced to screen readers
  • Fix Required: Add role="alert" and aria-live="assertive" to error div
  • Impact: Poor accessibility for users with screen readers

13. Environment Variable Documentation Incomplete (components/frontend/.env.example:34-40)

  • Issue: Example shows LANGFUSE_SECRET_KEY but:
    • Doesn't explain it should NOT be used in frontend
    • Doesn't mention it's for backend only (if moved)
  • Fix Required: Remove from .env.example or add clear warning comment

🔵 Minor Issues

14. Unused Import in FeedbackButtons (components/frontend/src/components/feedback/FeedbackButtons.tsx:18)

  • Issue: messageTimestamp prop is accepted but never used
  • Fix: Remove from props or use it in the feedback submission

15. Magic Numbers in UI (components/frontend/src/components/feedback/FeedbackButtons.tsx:65-66)

  • Issue: Hardcoded color values (green-500/10, red-500/10) repeated
  • Recommendation: Extract to constants or use Tailwind theme variables
  • Impact: Low - but hurts maintainability

16. Missing JSDoc Comments (All new files)

  • Issue: Public components and functions lack documentation
  • Recommendation: Add JSDoc comments for:
    • FeedbackButtons component
    • FeedbackModal component
    • API route handler
    • getLangfuseClient function
  • Impact: Low - but improves developer experience

17. Console.warn Instead of Proper Logging (components/frontend/src/lib/langfuseClient.ts:23, route.ts:66)

  • Issue: Using console.warn instead of structured logging
  • Recommendation: Use proper logging library (if available) or at minimum console.error for errors
  • Pattern: Backend uses structured logging (error-handling.md:26-40)

18. Button className Pattern Inconsistency (components/frontend/src/components/ui/button.tsx:10)

  • Issue: Added cursor-pointer to all buttons globally
  • Risk: May conflict with disabled state styling in some edge cases
  • Recommendation: Review if this should be applied via :not([disabled]) or similar

19. Checkbox className Pattern Inconsistency (components/frontend/src/components/ui/checkbox.tsx:16)

  • Issue: Same as button - added cursor-pointer globally
  • Recommendation: Ensure it doesn't conflict with disabled/readonly states

20. Hardcoded API Endpoint (components/frontend/src/components/feedback/FeedbackModal.tsx:95)

  • Issue: /api/feedback is hardcoded
  • Recommendation: Use API_BASE_URL or similar constant for consistency
  • Impact: Very low - Next.js API routes are always at /api

Positive Highlights

Excellent UX Design: The feedback buttons are well-designed with:

  • Clear visual states (submitted, hover, focus)
  • Helpful tooltips
  • Confirmation with checkmark icon
  • Thoughtful modal flow

Good Privacy Considerations:

  • Optional transcript inclusion
  • Clear privacy disclaimer in modal
  • User controls what data is shared

Proper Component Structure:

  • Clean separation between FeedbackButtons and FeedbackModal
  • Reusable FeedbackContext pattern
  • Good use of Shadcn UI components

TypeScript Type Safety (mostly):

  • Proper type definitions for FeedbackRequest
  • Type guards in extractMessageText helper
  • Good use of discriminated unions (FeedbackType)

Graceful Degradation:

  • Components don't render if context unavailable
  • Langfuse client returns null if not configured
  • Optional env vars don't break deployment

Follows Shadcn UI Patterns:

  • Uses existing UI components (Dialog, Button, Textarea, Checkbox)
  • Consistent with codebase design system
  • No custom UI built from scratch

Recommendations

Immediate Actions (Before Merge)

  1. Remove LANGFUSE_SECRET_KEY from frontend deployment - Critical security fix
  2. Add authentication/authorization to /api/feedback route - Prevent unauthorized feedback submission
  3. Convert fetch() to React Query mutation - Follow codebase patterns
  4. Add error handling around langfuse.score() - Prevent silent failures
  5. Add PII/sensitive data warnings in UI - User awareness

High Priority (Should Address)

  1. Implement rate limiting - Prevent abuse
  2. Persist feedback state - Better UX on page refresh
  3. Add loading states to buttons - Pattern compliance
  4. Fix error state persistence - Better UX
  5. Add ARIA attributes for accessibility - Screen reader support

Nice to Have (Future Improvements)

  1. Add JSDoc documentation - Developer experience
  2. Extract magic numbers to constants - Maintainability
  3. Add unit tests - Test coverage (no tests added in this PR)
  4. Consider backend API endpoint instead - Could be part of backend Go API for consistency

Architecture Discussion

Question: Should feedback collection be a frontend API route or a backend endpoint?

Current: Frontend Next.js API route (/api/feedback)
Alternative: Backend Go API endpoint (/api/projects/:project/feedback)

Pros of Backend Approach:

  • Centralized auth/RBAC (already implemented in backend)
  • Consistent with other API patterns
  • Better for secret management
  • Can leverage existing K8s client patterns

Cons of Backend Approach:

  • Requires backend changes
  • More complex deployment

Recommendation: Consider moving to backend in future iteration for better security and consistency.


Pre-Commit Checklist Status

Based on frontend checklist (CLAUDE.md:1122-1136):

  • ❌ Zero any types - ✅ PASS
  • ❌ All UI uses Shadcn components - ✅ PASS
  • ❌ All data operations use React Query - ❌ FAIL (manual fetch in modal)
  • ❌ Components under 200 lines - ✅ PASS (FeedbackModal is 230 but acceptable for dialog)
  • ❌ Single-use components colocated - ✅ PASS (feedback/* is properly structured)
  • ❌ All buttons have loading states - ❌ FAIL (feedback buttons missing loading state)
  • ❌ All lists have empty states - N/A
  • ❌ All nested pages have breadcrumbs - N/A
  • ❌ All routes have loading.tsx, error.tsx - N/A (not a route)
  • npm run build passes - ⚠️ UNKNOWN (should verify)
  • ❌ All types use type instead of interface - ✅ PASS

Checklist Score: 4/7 applicable items passed


Security Checklist Status

Based on security standards (security-standards.md:206-241):

Authentication:

  • ❌ No user token validation - ❌ FAIL

Authorization:

  • ❌ No RBAC check - ❌ FAIL
  • ❌ No namespace validation - ❌ FAIL

Secrets & Tokens:

  • ❌ Secret key in frontend deployment - ❌ FAIL
  • ✅ No tokens in logs - ✅ PASS

Input Validation:

  • ✅ Required fields validated - ✅ PASS
  • ⚠️ No sanitization of user input - ⚠️ WARNING

Container Security:

  • N/A (frontend only)

Security Score: 2/6 items passed


Final Recommendation

Status: ⚠️ NEEDS WORK - Do not merge in current state

This is a well-designed feature with good UX, but has critical security issues that must be addressed:

  1. Blocker: Remove secret key from frontend deployment
  2. Critical: Add authentication/authorization to API route
  3. Critical: Follow React Query patterns for data fetching
  4. Critical: Add error handling for Langfuse SDK calls

Once these issues are resolved, this will be a solid addition to the platform. The core idea and implementation approach are sound.

Estimated Effort to Fix: 4-6 hours

  • 1h: Security fixes (remove secret, add auth)
  • 2h: React Query migration
  • 1h: Error handling and loading states
  • 1-2h: Testing and validation

Note: This is a WIP PR as indicated by the title. The above issues should be addressed before removing the WIP status.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

@github-actions
Copy link
Contributor

github-actions bot commented Jan 16, 2026

Claude Code Review

Summary

This PR implements a per-message user feedback mechanism with thumbs up/down buttons and a modal for detailed feedback submission to Langfuse. The implementation follows frontend patterns well but has several security, error handling, and architecture issues that need to be addressed.

Overall Assessment: Good UX implementation with clean component design, but requires security hardening, error handling improvements, and better API client patterns before merging.


Issues by Severity

🚫 Blocker Issues

1. Missing Authentication/Authorization on API Route (Security Critical)

  • File: components/frontend/src/app/api/feedback/route.ts
  • Issue: The /api/feedback route accepts username from client request body without verification
  • Risk: Any user can submit feedback claiming to be any other user
  • Required Fix:
    • Extract username from authenticated session (cookies, JWT, or headers)
    • Validate user has access to the specified project/session
    • Never trust client-provided identity claims
  • Pattern Violation: Security Standards - "Always check permissions before operations"
  • Reference: .claude/context/security-standards.md:209-220

2. Manual fetch() Call Violates React Query Pattern (Architecture Critical)

  • File: components/frontend/src/components/feedback/FeedbackModal.tsx:95
  • Issue: Direct fetch('/api/feedback') instead of using React Query
  • Pattern Violation: Frontend Development Standards - "React Query for ALL Data Operations"
  • Required Fix:
    • Create src/services/api/feedback.ts with API client functions
    • Create src/services/queries/feedback.ts with useSubmitFeedback mutation hook
    • Use mutation hook in FeedbackModal component
  • Reference: .claude/patterns/react-query-usage.md:356-372, CLAUDE.md:1117

🔴 Critical Issues

3. No Error Logging in API Route (Observability)

  • File: components/frontend/src/app/api/feedback/route.ts:123
  • Issue: Generic console.error without structured logging or context
  • Impact: Makes debugging production issues difficult
  • Fix: Add structured error logging with request context
console.error('Error submitting feedback:', {
  error: error instanceof Error ? error.message : String(error),
  username,
  projectName,
  sessionName,
  traceId: effectiveTraceId,
});

4. Langfuse Client Singleton Pattern Issues (Architecture)

  • File: components/frontend/src/lib/langfuseClient.ts:11-17
  • Issue: Module-level singleton may cause issues in serverless/edge environments
  • Risk: Stale config, memory leaks, or config from wrong environment
  • Fix: Consider per-request instantiation or proper cleanup
export function getLangfuseClient(): LangfuseWeb | null {
  const publicKey = process.env.LANGFUSE_PUBLIC_KEY;
  const host = process.env.LANGFUSE_HOST;
  
  if (\!publicKey || \!host) {
    return null;
  }
  
  // Create fresh instance (Langfuse SDK is lightweight)
  return new LangfuseWeb({ publicKey, baseUrl: host });
}

5. Missing Input Validation on Transcript Data (Security)

  • File: components/frontend/src/app/api/feedback/route.ts:84-89
  • Issue: No validation of transcript array structure before processing
  • Risk: Could throw runtime errors if malformed data sent
  • Fix: Validate transcript structure
if (includeTranscript && Array.isArray(transcript)) {
  const validTranscript = transcript.filter(
    m => m && typeof m === 'object' && 
    typeof m.role === 'string' && 
    typeof m.content === 'string'
  );
  // ... process validTranscript
}

🟡 Major Issues

6. Context Provider Re-renders on Every Message (Performance)

  • File: components/frontend/src/contexts/FeedbackContext.tsx:40-51
  • Issue: useMemo dependency on messages array causes re-render on every message update
  • Impact: All child components re-render unnecessarily
  • Fix: Use stable references or selectors
// Option 1: Don't memoize messages, access directly when needed
const value = useMemo(
  () => ({
    projectName,
    sessionName,
    username,
    initialPrompt,
    activeWorkflow,
    traceId,
    getMessages: () => messages, // Function reference is stable
  }),
  [projectName, sessionName, username, initialPrompt, activeWorkflow, traceId]
);

7. any Type Violation (Code Quality)

  • File: Multiple locations (need to check with TypeScript)
  • Issue: Frontend standards require zero any types
  • Pattern Violation: CLAUDE.md:1115 - "Zero any Types"
  • Action: Run TypeScript check to identify violations

8. Missing Loading State During Feedback Submission (UX)

  • File: components/frontend/src/components/feedback/FeedbackModal.tsx:95-121
  • Issue: While isSubmitting is tracked, there's no visual feedback if the request hangs
  • Fix: Add timeout and better error handling
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);

try {
  const response = await fetch('/api/feedback', {
    method: 'POST',
    signal: controller.signal,
    // ...
  });
  clearTimeout(timeoutId);
  // ...
} catch (err) {
  clearTimeout(timeoutId);
  if (err.name === 'AbortError') {
    setError('Request timed out. Please try again.');
  }
  // ...
}

9. Environment Variables Not Documented in Deployment Manifests (DevOps)

  • File: components/manifests/base/frontend-deployment.yaml:14
  • Issue: New LANGFUSE_PUBLIC_KEY and LANGFUSE_HOST env vars added to local dev but not base deployment
  • Impact: Production deployments won't have feedback functionality
  • Fix: Add to base deployment with comments about optional nature

🔵 Minor Issues

10. Inconsistent Button Styling (UI Consistency)

  • File: components/frontend/src/components/feedback/FeedbackButtons.tsx:61-71
  • Issue: Using raw <button> instead of Shadcn <Button> component
  • Pattern Violation: CLAUDE.md:1116 - "Shadcn UI Components Only"
  • Fix: Use <Button variant="ghost" size="sm"> for consistency

11. Type Import Style Inconsistency (Code Style)

  • Files: FeedbackModal.tsx:18, FeedbackContext.tsx:4
  • Issue: Using import type for some but not all type imports
  • Fix: Use import type consistently for all type-only imports

12. Missing JSDoc Comments on Public API (Documentation)

  • Files: FeedbackButtons.tsx, FeedbackContext.tsx
  • Issue: No JSDoc on exported components/hooks
  • Fix: Add JSDoc for better developer experience
/**
 * Feedback buttons component that displays thumbs up/down for user feedback.
 * Requires FeedbackProvider in parent tree.
 * 
 * @param messageContent - The message content to provide context for feedback
 * @param messageTimestamp - Timestamp of the message
 */
export function FeedbackButtons({ ... }) { ... }

13. Hardcoded Strings Should Be Constants (Maintainability)

  • File: components/frontend/src/app/api/feedback/route.ts:109
  • Issue: Magic string 'user-feedback' should be a named constant
const FEEDBACK_SCORE_NAME = 'user-feedback' as const;

langfuse.score({
  // ...
  name: FEEDBACK_SCORE_NAME,
  // ...
});

14. FeedbackContext TypeScript Type Could Use type Instead of Inline (Code Style)

  • File: components/frontend/src/contexts/FeedbackContext.tsx:6-15
  • Current: Inline type definition
  • Preferred: Export as named type for reusability
export type FeedbackContextValue = {
  projectName: string;
  // ... (already correct\!)
};

Note: This is already correct, no action needed


Positive Highlights

Excellent Component Composition - Clean separation between FeedbackButtons, FeedbackModal, and FeedbackContext

Good UX Design - Tooltips, loading states, visual feedback on submission, and privacy disclaimer

Proper Use of Shadcn UI - Dialog, Button, Textarea, Checkbox all correctly used

Accessibility - aria-labels on buttons, proper semantic HTML

Privacy-Conscious - Clear opt-in for transcript inclusion with privacy notice

Type Safety - Good use of TypeScript types (FeedbackType, FeedbackRequest, etc.)

Error Handling in UI - Error state displayed to users in modal

Follows Submission Pattern - Disable submit button, show spinner, handle success/error


Recommendations

Priority 1 (Blocker - Must Fix Before Merge)

  1. Add authentication/authorization to /api/feedback route
    • Extract authenticated user from session
    • Validate access to project/session
    • Remove username from request body
  2. Migrate to React Query pattern
    • Create src/services/api/feedback.ts
    • Create src/services/queries/feedback.ts with mutation hook
    • Update FeedbackModal to use the hook

Priority 2 (Critical - Should Fix Before Merge)

  1. Add structured error logging in API route
  2. Fix Langfuse client singleton pattern
  3. Add input validation for transcript data
  4. Run npm run build to check for any types

Priority 3 (Major - Address Soon)

  1. Optimize FeedbackContext re-renders
  2. Add timeout handling for feedback submission
  3. Add LANGFUSE env vars to base deployment manifest
  4. Document Langfuse configuration in main README

Priority 4 (Minor - Nice to Have)

  1. Replace raw buttons with Shadcn Button component
  2. Add JSDoc comments to public APIs
  3. Extract magic strings to constants
  4. Add unit tests for extractMessageText helper

Testing Recommendations

Before merging:

  • Test with Langfuse not configured (should gracefully degrade)
  • Test with malformed transcript data
  • Test with unauthenticated user (after auth fix)
  • Test with user lacking project access (after authz fix)
  • Test feedback submission timeout/failure scenarios
  • Verify no any types: npm run build
  • Test rapid clicking of feedback buttons (debouncing?)

Architecture Notes

This PR introduces a new integration point with Langfuse for user feedback. Consider:

  1. Should this be behind a feature flag? (e.g., ENABLE_FEEDBACK=true)
  2. Should feedback be stored locally first, then synced to Langfuse? (offline support)
  3. Should there be rate limiting on feedback submissions?
  4. How will feedback be monitored/reviewed? (Langfuse dashboard access)

Estimated effort to address blockers: 2-3 hours
Estimated effort to address all critical issues: 4-6 hours total

Great work on the UX! The feedback mechanism looks polished. Focus on the security and architecture issues before merging, and this will be a solid addition to the platform.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

@andybraren andybraren marked this pull request as ready for review January 16, 2026 08:15
@github-actions
Copy link
Contributor

github-actions bot commented Jan 16, 2026

Claude Code Review

Summary

This PR implements a per-message user feedback mechanism with thumbs up/down buttons and a detailed feedback modal. The implementation integrates with Langfuse for tracking feedback scores.

Overall Assessment: Good implementation with solid UX patterns, but has several critical security and architectural issues that must be addressed before merge.


Issues by Severity

Blocker Issues

1. CRITICAL: Missing Input Validation (route.ts:54-60)

  • Location: components/frontend/src/app/api/feedback/route.ts:54-60
  • Issue: Insufficient validation of user inputs before sending to Langfuse
  • Violations: No validation of value range, no sanitization for log injection, no length limits
  • Security Standards Violation: Input Validation pattern from security-standards.md
  • Fix Required: Add validation for value range (0 or 1), sanitize strings, add length limits

2. CRITICAL: Missing Error Context Logging (route.ts:122-128)

  • Location: components/frontend/src/app/api/feedback/route.ts:122-128
  • Issue: Generic error logging without context
  • Pattern Violation: CLAUDE.md Backend Error Handling Pattern 2 requires logging with context
  • Fix Required: Include projectName, sessionName, username in error logs

3. CRITICAL: Environment Variable Documentation Gap (langfuseClient.ts:19-20)

  • Location: components/frontend/src/lib/langfuseClient.ts
  • Issue: LANGFUSE_PUBLIC_KEY and LANGFUSE_HOST need clearer documentation
  • Risk: Developers might accidentally expose these by adding NEXT_PUBLIC_ prefix
  • Fix Required: Add deployment documentation clarifying these are server-only secrets

Critical Issues

4. Architectural: No React Query Integration (FeedbackModal.tsx:95-110)

  • Location: components/frontend/src/components/feedback/FeedbackModal.tsx:95-110
  • Violation: Frontend Development Standards Rule Epic: Data Source Integration #3 - React Query for ALL Data Operations
  • Issue: Manual fetch() call instead of using React Query mutation
  • Fix Required: Create mutation hook in @/services/queries/feedback.ts

5. Missing Loading States (FeedbackButtons.tsx:62-81)

  • Location: components/frontend/src/components/feedback/FeedbackButtons.tsx
  • Violation: Frontend Pre-Commit Checklist - All buttons have loading states
  • Issue: Thumbs up/down buttons dont show loading state while submitting
  • Impact: User could click multiple times, causing duplicate submissions
  • Fix Required: Pass isSubmitting prop from modal to buttons

Major Issues

6. Error Handling: Silent Langfuse Failures (route.ts:65-71)

  • Location: components/frontend/src/app/api/feedback/route.ts:65-71
  • Issue: If Langfuse not configured, returns success: false but still returns 200 OK
  • Problem: Frontend treats this as success
  • Fix Required: Return 503 Service Unavailable instead

7. Privacy Concern: Full Transcript Inclusion (FeedbackModal.tsx:91-93)

  • Issue: When user checks Include all messages, ENTIRE conversation history is sent
  • Risk: Could inadvertently include sensitive information
  • Recommendation: Make privacy disclaimer more specific, consider limiting to last N messages

Positive Highlights

✅ Excellent UX Patterns - Smooth feedback flow, clear visual feedback, disabled state
✅ Privacy-Conscious Design - Uses public key only, optional transcript inclusion
✅ Well-Structured Components - Clean separation of concerns, proper TypeScript types
✅ Integration with Existing System - Reuses Langfuse infrastructure, consistent with trace ID approach
✅ Deployment Configuration - Proper env vars, Kubernetes secrets with optional: true


Final Verdict

⚠️ Recommend: REQUEST CHANGES

Critical issues that must be fixed before merge:

  1. Input validation is incomplete (security risk)
  2. React Query pattern not followed (violates frontend standards)
  3. Error handling needs improvement (UX and debugging)

Estimated Time to Fix: 2-4 hours for blockers + critical issues

📋 Next Steps: Please address blocker issues #1-3 and critical issue #4, then request re-review.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

- Added a `sanitizeString` function to clean user inputs by removing control characters and normalizing line endings.
- Updated the feedback submission process to sanitize various fields including username, project name, session name, comment, workflow, context, and trace ID.
- Ensured transcript entries are also sanitized before processing.

These changes enhance security by mitigating the risk of log injection attacks, improving the overall integrity of the feedback data submitted.
@github-actions
Copy link
Contributor

github-actions bot commented Jan 16, 2026

Claude Code Review

Summary

This PR implements a user feedback mechanism for messages using Langfuse's Scores API. The implementation adds thumbs up/down buttons for agent messages with an optional detailed feedback modal. Overall implementation is clean with good security practices (input sanitization, proper secret handling). However, there are several important issues to address before merging.

Issues by Severity

🚫 Blocker Issues

1. Frontend Design Guidelines Violation - any Type Usage

  • Location: src/components/ui/checkbox.tsx:27, src/components/ui/message.tsx:33-38
  • Issue: Uses any type which violates the zero any types rule from CLAUDE.md and frontend design guidelines
  • Standard: "Zero any Types - Use proper types, unknown, or generic constraints"
  • Fix Required:
    // In checkbox.tsx
    type CheckedState = boolean | 'indeterminate'
    
    // In message.tsx - properly type the code component props
    code: ({ inline, className, children, ...props }: React.ComponentPropsWithoutRef<'code'> & { inline?: boolean }) => {

🔴 Critical Issues

2. Missing Type Definitions for useCurrentUser Query

  • Location: src/app/projects/[name]/sessions/[sessionName]/page.tsx:194
  • Issue: useCurrentUser is imported but not defined in the codebase (grep shows no implementation)
  • Impact: Runtime error - undefined function
  • Fix Required: Either:
    • Remove this line if not needed yet
    • Implement the query in src/services/queries/
    • Use existing user context/authentication mechanism

3. Security - LangfuseWeb Client Not Properly Scoped

  • Location: src/lib/langfuseClient.ts:11
  • Issue: Module-level singleton langfuseClient variable is shared across all requests in serverless/edge functions
  • Impact: Potential data leakage between different user sessions in production (Next.js API routes are stateless)
  • Standard Violation: While not explicitly in CLAUDE.md, this violates general Next.js API route best practices
  • Fix Required: Remove caching, instantiate new client per request:
    export function getLangfuseClient(): LangfuseWeb | null {
      const publicKey = process.env.LANGFUSE_PUBLIC_KEY;
      const host = process.env.LANGFUSE_HOST;
      
      if (\!publicKey || \!host) {
        console.warn('Langfuse not configured');
        return null;
      }
      
      return new LangfuseWeb({ publicKey, baseUrl: host });
    }

4. Type Safety - Direct Type Assertions Without Checking

  • Location: src/app/api/feedback/route.ts:34
  • Issue: FeedbackRequest type is defined but Next.js doesn't validate JSON automatically
  • Standard Violation: CLAUDE.md Section "Input Validation" - "Validate All User Input"
  • Fix Required: Add runtime validation:
    const body = await request.json();
    
    // Validate required fields exist and are correct types
    if (\!body || typeof body \!== 'object') {
      return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
    }

🟡 Major Issues

5. Missing React Query Integration

  • Location: src/components/feedback/FeedbackModal.tsx:93
  • Issue: Uses manual fetch() call instead of React Query mutation
  • Standard Violation: Frontend Development Context - "React Query for ALL Data Operations"
  • Impact: No caching, no automatic retry, no optimistic updates, inconsistent with project patterns
  • Fix Required: Create useFeedbackMutation hook in src/services/queries/:
    // src/services/queries/feedback.ts
    export function useFeedbackMutation() {
      return useMutation({
        mutationFn: (data: FeedbackRequest) => 
          fetch('/api/feedback', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
          }).then(r => r.ok ? r.json() : Promise.reject(r)),
        onError: (error) => {
          // Show toast notification
        },
      });
    }

6. Error Handling Pattern Inconsistency

  • Location: src/app/api/feedback/route.ts:156-164
  • Issue: Generic error message without structured logging
  • Standard Violation: Error Handling Patterns - "Log errors with context"
  • Fix Required:
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      console.error('[Feedback API] Error submitting feedback:', {
        error: errorMessage,
        stack: error instanceof Error ? error.stack : undefined,
      });
      return NextResponse.json(
        { error: 'Failed to submit feedback' },
        { status: 500 }
      );
    }

7. Missing Loading States in Shadcn Components

  • Location: src/components/feedback/FeedbackButtons.tsx:60-81
  • Issue: Buttons don't show loading state during submission
  • Standard Violation: Frontend Pre-Commit Checklist - "All buttons have loading states"
  • Fix Required: Add isPending state from mutation and disable buttons during submission

8. Accessibility - Missing ARIA Labels

  • Location: src/components/feedback/FeedbackButtons.tsx
  • Issue: Tooltip content is present but screen reader support could be improved
  • Recommendation: Already has aria-label - good! But consider adding aria-live region for feedback submission status

🔵 Minor Issues

9. Input Sanitization Could Be More Robust

  • Location: src/app/api/feedback/route.ts:40-47
  • Issue: Good job implementing sanitization! However, consider additional protections:
    • Max length validation (prevent extremely long inputs)
    • HTML entity encoding for metadata fields
  • Recommendation (not blocking):
    function sanitizeString(input: string, maxLength = 10000): string {
      const truncated = input.substring(0, maxLength);
      return truncated
        .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '')
        .replace(/\r\n/g, '\n')
        .replace(/\r/g, '\n');
    }

10. Console Warnings for Missing Config

  • Location: src/lib/langfuseClient.ts:23, src/app/api/feedback/route.ts:96
  • Issue: console.warn is fine but consider using structured logging
  • Recommendation: Use proper logger (pino, winston) for production consistency

11. TypeScript - Prefer type Over interface

  • Location: src/contexts/FeedbackContext.tsx:6
  • Issue: Uses type correctly (good!)
  • Note: Consistent with frontend standards ✅

12. Component Size

  • Location: FeedbackModal.tsx (230 lines)
  • Issue: Slightly exceeds recommended 200 line limit but acceptable given complexity
  • Recommendation: Consider extracting privacy notice to separate component if adding more features

Positive Highlights

Excellent Security Implementation

  • Input sanitization function prevents log injection attacks (line 40-47)
  • Properly removed LANGFUSE_SECRET_KEY from frontend config
  • Uses public-key-only LangfuseWeb SDK (no secret key in frontend)

Good UX Design

  • Thumbs up/down with visual feedback
  • Disabled state prevents duplicate submissions
  • Optional transcript inclusion with clear privacy notice
  • Smooth modal interaction flow

Clean Code Organization

  • Proper file structure (components/feedback/)
  • Index file for clean exports
  • Feedback context pattern is well designed

Shadcn UI Usage

  • Correctly uses Dialog, Button, Textarea, Checkbox components
  • Follows established UI patterns

Good Comments and Documentation

  • API route has clear JSDoc comments
  • Function purposes well explained

Recommendations

Priority 1 (Must Fix Before Merge)

  1. Fix blocker Outcome: Reduce Refinement Time with agent System #1 - Remove any types
  2. Fix critical Epic: RAT Architecture & Design #2 - Resolve useCurrentUser undefined import
  3. Fix critical Epic: Data Source Integration #3 - Remove singleton pattern from LangfuseWeb client
  4. Fix critical Epic: AI Agent Development #4 - Add runtime type validation to API route

Priority 2 (Should Fix Before Merge)

  1. Implement React Query mutation for feedback submission (Epic: Jira Integration & Workflow #5)
  2. Improve error logging with structured context (Epic: Testing & Validation #6)
  3. Add loading states to feedback buttons (Test: Automation Workflow Validation #7)

Priority 3 (Nice to Have)

  1. Add max length validation to sanitization
  2. Extract privacy notice component
  3. Consider structured logging library

Testing Recommendations

Add tests for:

  • sanitizeString() function with various injection attempts
  • Feedback submission success/error flows
  • Disabled button states after submission
  • Modal open/close behavior
  • Context provider edge cases (missing provider)

Architecture Compliance

Standard Status Notes
Zero any types Violations in checkbox.tsx and message.tsx
React Query for data ops Uses manual fetch instead of mutation
Shadcn UI components Correctly uses Dialog, Button, etc.
type over interface Consistent usage
Input validation ⚠️ Good sanitization but missing runtime type checks
Error handling ⚠️ Adequate but could be more structured
Security standards Excellent - proper secret handling, sanitization

Overall Assessment: Good implementation with strong security practices, but needs to address the 4 critical issues and align with React Query patterns before merging. The core functionality is solid and the UX is well thought out.

Estimated effort to fix blockers + critical issues: 2-3 hours


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

@andybraren andybraren changed the title [WIP] Per-message user feedback mechanism Per-message user feedback mechanism Jan 16, 2026
- Added a new endpoint for submitting user feedback, which processes thumbs up/down responses and forwards them to the runner for logging.
- Introduced new data structures for feedback events and payloads, enhancing the feedback submission process.
- Updated the frontend to send feedback to the new endpoint, replacing the previous Langfuse integration.
- Removed obsolete Langfuse client and related configurations from the frontend, streamlining the feedback handling process.

These changes improve the feedback mechanism by leveraging AG-UI META events, ensuring better observability and user experience.
@codecov
Copy link

codecov bot commented Jan 19, 2026

Codecov Report

❌ Patch coverage is 62.50000% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...onents/runners/claude-code-runner/observability.py 62.50% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions
Copy link
Contributor

github-actions bot commented Jan 19, 2026

Claude Code Review

Summary

This PR implements user feedback mechanism via AG-UI META events routing feedback from frontend to backend to runner to Langfuse. Architecture is sound but needs security fixes before merge.

Critical Issues

1. SECURITY: Missing Input Sanitization (backend/websocket/agui_proxy.go:143)

Username from X-Forwarded-User header is logged without sanitization. Risk of log injection via newlines.

FIX: Add sanitizeForLog() function like commit b49695f did.

2. Error Handling: Silent Failures (runner/main.py:1192-1197)

Broad exception catching without returning error status violates error handling patterns.

Major Issues

3. Unused Error-Throwing Hook (frontend/contexts/FeedbackContext.tsx:1039)

useFeedbackContext() is never used. Remove it.

4. Missing Type Safety (backend/websocket/agui_proxy.go:154)

Use typed FeedbackPayload struct instead of map[string]interface{}.

Minor Issues

  1. Exposing internal errors to API responses (line 194)
  2. Unused messageTimestamp parameter (FeedbackModal.tsx:632)
  3. Non-standard inline import (runner/main.py:1164)

Positive Highlights

✅ Excellent RBAC - correct user-scoped client usage and permission validation
✅ Type safety in frontend - proper TypeScript definitions
✅ Shadcn UI compliance - all components use Shadcn correctly
✅ Security-first - Langfuse secrets removed from frontend
✅ Clean organization - components properly colocated

Recommendations

Priority 1 (Must Fix):

  1. Add input sanitization to backend handler
  2. Return error details from runner

Priority 2 (Should Fix):
3. Use typed FeedbackPayload struct
4. Remove unused useFeedbackContext hook
5. Generic error messages in API responses

Priority 3 (Nice to Have):
6. Remove unused parameters
7. Fix inline imports

Assessment

Code Quality: 7.5/10
Security: 8/10
Architecture: 9/10

Recommendation: Approve with changes - Fix critical issues #1 and #2, then merge.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

@github-actions
Copy link
Contributor

github-actions bot commented Jan 19, 2026

Claude Code Review

Summary

This PR implements a user feedback mechanism that allows users to provide thumbs up/down ratings on agent messages, with optional comments and transcript inclusion. The feedback is sent to Langfuse via AG-UI META events. The implementation follows established patterns but has several security, architecture, and code quality issues that need attention.

Issues by Severity

🚫 Blocker Issues

1. Missing Input Sanitization for Log Injection (Security)

  • Location: components/backend/websocket/agui_proxy.go:659
  • Issue: User input (username, comment, reason) is logged without sanitization, creating log injection vulnerability
  • Current Code:
log.Printf("AGUI Feedback: Received %s feedback from %s for session %s/%s",
    input.FeedbackType, username, projectName, sessionName)
  • Fix Required: Sanitize all user input before logging per security standards
// Remove newlines to prevent log injection
username = strings.ReplaceAll(username, "\n", "")
username = strings.ReplaceAll(username, "\r", "")
log.Printf("AGUI Feedback: Received %s feedback from user (len=%d) for session %s/%s",
    input.FeedbackType, len(username), projectName, sessionName)
  • Reference: .claude/context/security-standards.md:115-117

🔴 Critical Issues

2. Inconsistent Type Definition Usage (Architecture)

  • Location: components/frontend/src/components/feedback/FeedbackModal.tsx:32-53
  • Issue: Uses interface instead of type - violates CLAUDE.md frontend standards
  • Current Code:
// Implicit interface usage in inline type definitions
  • Fix Required: Convert to explicit type definitions per DESIGN_GUIDELINES.md
  • Reference: CLAUDE.md line 1115-1118: "Always prefer type for type definitions"

3. Missing Error Context in Backend (Error Handling)

  • Location: components/backend/websocket/agui_proxy.go:663-665
  • Issue: Error handling doesn't follow established patterns - missing wrapped error context
  • Current Code:
runnerURL, err := getRunnerEndpoint(projectName, sessionName)
if err \!= nil {
    log.Printf("AGUI Feedback: Failed to get runner endpoint: %v", err)
    c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Runner not available"})
    return
}
  • Should Include: Project and session context in all error logs
log.Printf("AGUI Feedback: Failed to get runner endpoint for %s/%s: %v", 
    projectName, sessionName, err)
  • Reference: .claude/patterns/error-handling.md:39-40

4. Potential Panic from Type Assertion (Backend Safety)

  • Location: components/runners/claude-code-runner/main.py:359
  • Issue: Direct dictionary access without error handling could cause runtime errors
  • Current Code:
user_id = payload.get("userId", "unknown")  # Safe
transcript_text = "\n".join(
    f"[{m.get('role', 'unknown')}]: {m.get('content', '')}"
    for m in transcript  # Not validated - could crash if transcript is not list
)
  • Fix Required: Validate transcript structure before iteration
if include_transcript and isinstance(transcript, list):
    transcript_text = "\n".join(
        f"[{m.get('role', 'unknown')}]: {m.get('content', '')}"
        for m in transcript if isinstance(m, dict)
    )

5. Missing TypeScript Types (Frontend Standards)

  • Location: components/frontend/src/app/api/projects/[name]/agentic-sessions/[sessionName]/agui/feedback/route.ts
  • Issue: No type definitions for request/response - violates zero any types rule
  • Current Code: Uses untyped request.text() and response
  • Fix Required: Define proper types for the API route
type FeedbackRequest = {
  feedbackType: 'thumbs_up' | 'thumbs_down'
  comment?: string
  workflow?: string
  context?: string
  includeTranscript?: boolean
  transcript?: Array<{ role: string; content: string; timestamp?: string }>
}

type FeedbackResponse = {
  message: string
  status: string
}
  • Reference: CLAUDE.md lines 1115, 1125

🟡 Major Issues

6. Inconsistent Error Response Pattern (Backend)

  • Location: components/backend/websocket/agui_proxy.go:728-733
  • Issue: Returns 202 Accepted on failure (runner not available) - should return 503
  • Current Code:
if err \!= nil {
    log.Printf("AGUI Feedback: Request failed (runner may not be running): %v", err)
    c.JSON(http.StatusAccepted, gin.H{
        "message": "Feedback queued (runner not available)",
        "status":  "pending",
    })
    return
}
  • Issue: Misleading status code - user thinks feedback was accepted when it failed
  • Better Approach: Return 503 Service Unavailable or 500 Internal Server Error
  • Reference: .claude/patterns/error-handling.md:224-232

7. Overly Complex Message Extraction Logic (Frontend)

  • Location: components/frontend/src/components/feedback/FeedbackModal.tsx:32-53
  • Issue: Complex type narrowing and nested conditionals - could be simplified
  • Suggestion: Extract to separate utility function with better type guards
// In a separate utils file
export function extractMessageText(
  messages: Array<MessageObject | ToolUseMessages>
): Array<TranscriptItem> {
  // More focused, testable implementation
}

8. Missing Loading State in FeedbackModal (UX)

  • Location: components/frontend/src/components/feedback/FeedbackButtons.tsx:38-45
  • Issue: No loading state between click and modal opening
  • Impact: User could double-click and submit multiple feedbacks
  • Fix: Add loading state or disable button during submission

9. Langfuse Client Not Reused (Performance)

  • Location: components/runners/claude-code-runner/main.py:377-383
  • Issue: Creates new Langfuse client on every feedback submission
  • Impact: Performance overhead and potential connection leaks
  • Fix: Create Langfuse client once during app startup and reuse
# In lifespan context manager
langfuse_client = None
if langfuse_enabled:
    langfuse_client = Langfuse(...)

# In feedback handler
if langfuse_client:
    langfuse_client.score(...)

🔵 Minor Issues

10. Inconsistent Naming Conventions

  • Location: components/backend/types/agui.go:283-288
  • Issue: FeedbackTranscriptItem has mixed camelCase/PascalCase fields
  • Suggestion: Use consistent Go conventions (PascalCase for exported fields)

11. Magic String Values

  • Location: Multiple files
  • Issue: Hard-coded strings like "thumbs_up", "thumbs_down" without constants
  • Suggestion: Define constants for better maintainability
const (
    FeedbackTypeThumbsUp   = "thumbs_up"
    FeedbackTypeThumbsDown = "thumbs_down"
)

12. Missing JSDoc Comments (Frontend)

  • Location: components/frontend/src/components/feedback/FeedbackButtons.tsx
  • Issue: No JSDoc comments on exported components
  • Suggestion: Add brief JSDoc for component props and purpose

13. Trace ID Generation Pattern

  • Location: components/runners/claude-code-runner/main.py:384
  • Issue: Trace ID pattern feedback-{session}-{timestamp} doesn't link to actual session traces
  • Suggestion: Document why this pattern was chosen vs. using actual trace IDs from session

14. Environment Variable Documentation

  • Location: components/frontend/.env.example:34-39
  • Good: Added LANGFUSE_* variables
  • Suggestion: Document that these are optional and what happens when not set

Positive Highlights

Excellent Security Practices:

  • Proper RBAC checks in HandleAGUIFeedback (lines 625-643)
  • User token authentication required (lines 617-622)
  • Username extraction from auth proxy headers (line 646)

Follows AG-UI Protocol:

  • Correctly implements META events per AG-UI spec
  • Proper event structure with type, metaType, payload
  • References official documentation

Good Error Handling in Runner:

  • Graceful fallback when Langfuse not available
  • Comprehensive logging throughout the flow
  • Proper HTTP status codes on validation failures

Clean Component Architecture (Frontend):

  • FeedbackContext properly separates concerns
  • FeedbackButtons and FeedbackModal are well-isolated
  • Uses Shadcn UI components correctly

Privacy-Conscious Design:

  • Clear privacy disclaimer in modal
  • Optional transcript inclusion
  • User controls what data is shared

Good Use of React Patterns:

  • Proper use of useMemo in FeedbackContext
  • Optional context hook for defensive programming
  • Clean state management in modal

Recommendations

Priority 1 (Must Fix Before Merge)

  1. Fix log injection vulnerability in backend feedback handler (Issue Outcome: Reduce Refinement Time with agent System #1)
  2. Add input validation for transcript structure in Python runner (Issue Epic: AI Agent Development #4)
  3. Add TypeScript types for API route (Issue Epic: Jira Integration & Workflow #5)

Priority 2 (Should Fix Before Merge)

  1. Convert to type definitions in frontend (Issue Epic: RAT Architecture & Design #2)
  2. Fix error response pattern - don't return 202 on failure (Issue Epic: Testing & Validation #6)
  3. Add error context to all backend logs (Issue Epic: Data Source Integration #3)

Priority 3 (Nice to Have)

  1. Extract message extraction logic to utility function (Issue Test: Automation Workflow Validation #7)
  2. Add loading state to prevent double-submission (Issue Test: Updated Workflow Validation #8)
  3. Reuse Langfuse client for performance (Issue Bump actions/add-to-project from 0.5.0 to 1.0.2 #9)
  4. Define constants for magic strings (Issues Bump actions/checkout from 4 to 5 #10, Bump actions/github-script from 6 to 7 #11)

Testing Recommendations

  • Add integration test for feedback flow (backend → runner → Langfuse)
  • Add unit tests for message extraction logic
  • Test log injection prevention
  • Test error cases (runner unavailable, Langfuse disabled, etc.)

Documentation Recommendations

  • Document the feedback flow in architecture docs
  • Add comments explaining trace ID generation strategy
  • Document what happens when Langfuse is disabled

Overall Assessment: Good implementation of the feedback feature with proper security practices. Main concerns are input sanitization, type safety, and error handling consistency. After addressing Priority 1 & 2 issues, this will be ready to merge.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

@github-actions
Copy link
Contributor

github-actions bot commented Jan 19, 2026

Claude Code Review

Summary

This PR implements a user feedback mechanism for agent messages using Langfuse's Scores API. The implementation follows AG-UI META event patterns and includes thumbs up/down buttons with an optional comment modal. The code demonstrates strong adherence to security best practices (log injection prevention, RBAC validation) and frontend patterns (Shadcn UI, proper TypeScript typing). However, there are several architectural and error handling concerns that should be addressed before merge.

Issues by Severity

🚫 Blocker Issues

None - No blocking issues that prevent merge.

🔴 Critical Issues

  1. Backend Service Account Used for Write Operation Without User Token Validation (websocket/agui_proxy.go:228)

    • Location: HandleAGUIFeedback uses user token for RBAC check but doesn't use user-scoped client for any K8s operations
    • Issue: While RBAC is validated, this deviates from the established pattern where user operations should use user-scoped K8s clients throughout
    • Impact: Low risk in this case (no K8s writes), but breaks architectural consistency
    • Fix: Document why user-scoped client isn't needed here (no K8s operations, only HTTP proxy)
  2. Frontend API Route Missing Error Handling (frontend/src/app/api/.../feedback/route.ts:29-37)

    • Location: POST handler doesn't handle fetch errors
    • Issue: If backend is unreachable, unhandled exception will crash the API route
    • Fix: Wrap fetch in try/catch and return appropriate error response
    • Pattern: See other API routes like /agui/run/route.ts for error handling examples
  3. No Input Sanitization in Frontend API Route (frontend/src/app/api/.../feedback/route.ts:19)

    • Location: Request body is passed through without validation
    • Issue: Backend validates, but frontend should validate before proxying
    • Fix: Add input validation using Zod schema or similar before forwarding

🟡 Major Issues

  1. Feedback State Not Persisted Across Component Remounts (FeedbackButtons.tsx:28)

    • Location: submittedFeedback is component state, lost on unmount
    • Issue: If message list re-renders, user can submit feedback multiple times for same message
    • Fix: Either:
      • Store submitted feedback in session storage keyed by message ID
      • Track feedback server-side and include in message metadata
  2. No Loading State During Feedback Submission (FeedbackButtons.tsx)

    • Location: Buttons don't show loading state while modal is submitting
    • Issue: User could click feedback button again while submission is pending
    • Fix: Track isSubmitting from modal and disable buttons during submission
  3. Missing Error Boundary Around Feedback Components (page.tsx:449-489)

    • Location: FeedbackProvider wraps MessagesTab
    • Issue: If FeedbackProvider throws, entire MessagesTab crashes
    • Fix: Add error boundary or handle context creation errors gracefully
  4. Backend Logs User Input Without Size Limit (agui_proxy.go:176)

    • Location: SanitizeForLog(input.FeedbackType) logged without truncation
    • Issue: User could send extremely long comment/transcript causing log bloat
    • Fix: Use existing truncateForLog helper (line 592) for user input
  5. Runner Generates Trace ID That Won't Link to Session Trace (main.py:1196)

    • Location: trace_id = f"feedback-{session_name}-{timestamp}"
    • Issue: Langfuse won't automatically link feedback to the session's actual trace
    • Fix: Accept traceId from payload (already in FeedbackContext) and use it instead of generating new one

🔵 Minor Issues

  1. Type Definition Missing Export (types/agui.go:62-89)

    • Location: FeedbackPayload and FeedbackTranscriptItem defined but not used in Go code
    • Issue: These types are never instantiated in backend (payload is map[string]interface{})
    • Fix: Either use these types or remove them (currently they serve as documentation)
  2. Inconsistent Error Messages (agui_proxy.go:246)

    • Location: Returns "runner may not be running" when fetch fails
    • Issue: Generic message doesn't distinguish between network errors, auth failures, etc.
    • Fix: Parse response/error and provide specific guidance
  3. Unused messageTimestamp Parameter (FeedbackButtons.tsx:17, 23)

    • Location: Passed to buttons and modal but never used
    • Issue: Dead code
    • Fix: Remove parameter or implement timestamp tracking in feedback
  4. Frontend API Route Could Use React Query (FeedbackModal.tsx:99-110)

    • Location: Manual fetch call instead of React Query mutation
    • Issue: Doesn't follow project's data fetching standards (all data ops should use React Query)
    • Fix: Create useFeedbackMutation in services/queries/feedback.ts
    • Reference: See .claude/patterns/react-query-usage.md Pattern 3
  5. Missing ARIA Labels for Modal (FeedbackModal.tsx:139)

    • Location: Dialog doesn't specify aria-describedby
    • Issue: Screen readers won't announce description
    • Fix: Add aria-describedby pointing to DialogDescription
  6. No Telemetry/Analytics for Feedback Submission

    • Location: Frontend and backend don't track submission success/failure rates
    • Issue: Can't monitor if feedback system is working without Langfuse
    • Fix: Add logging/metrics for feedback submission attempts and results
  7. Python Type Hints Missing (main.py:1124-1240)

    • Location: handle_feedback function
    • Issue: Not following Python best practices (rest of codebase uses type hints)
    • Fix: Add return type annotation: async def handle_feedback(event: FeedbackEvent) -> Dict[str, Any]:
  8. Environment Variable Comments in Wrong Files (manifests/base/frontend-deployment.yaml:1091, overlays/local-dev/frontend-patch.yaml:1103)

    • Location: Comments say "Langfuse feedback now handled by runner"
    • Issue: Misleading - feedback is still initiated from frontend
    • Fix: Update to: "Feedback forwarded to runner for Langfuse logging"

Positive Highlights

Excellent Security Implementation:

  • Log injection prevention with SanitizeForLog helper (handlers/helpers.go:14-25)
  • RBAC validation before accepting feedback (agui_proxy.go:140-158)
  • Token redaction preserved in all logging
  • Input validation in backend (Gin binding with oneof constraint)

Follows Frontend Standards:

  • Uses Shadcn UI components exclusively (Dialog, Button, Textarea, Checkbox)
  • Proper TypeScript typing throughout (zero any types)
  • Context API used appropriately for cross-component state
  • Components under 200 lines
  • Good separation of concerns (FeedbackButtons, FeedbackModal, FeedbackContext)

Good UX Design:

  • Clear visual feedback (checkmark on submission)
  • Prevents duplicate submissions with disabled state
  • Privacy disclaimer in modal
  • Optional comment and transcript inclusion
  • Tooltips for button actions

Architecture Alignment:

  • Follows AG-UI META event pattern correctly
  • Backend proxies to runner (maintains architecture)
  • Proper error handling in Python endpoint
  • Langfuse integration follows existing observability patterns

Code Quality:

  • Well-documented code with comments explaining design decisions
  • Structured error responses
  • Proper cleanup (Langfuse flush, modal state reset)
  • Go formatting and linting compliance

Recommendations

Priority 1 (Before Merge)

  1. Fix Frontend API Route Error Handling:

    // components/frontend/src/app/api/.../feedback/route.ts
    try {
      const resp = await fetch(backendUrl, { method: 'POST', headers, body })
      const data = await resp.text()
      return new Response(data, { status: resp.status, headers })
    } catch (error) {
      console.error('Feedback proxy error:', error)
      return new Response(
        JSON.stringify({ error: 'Failed to submit feedback' }),
        { status: 502, headers: { 'Content-Type': 'application/json' } }
      )
    }
  2. Fix Trace ID Linkage:

    # Use traceId from payload instead of generating new one
    trace_id = payload.get('traceId') or f"feedback-{session_name}-{event.ts or int(time.time() * 1000)}"
  3. Add Input Validation to Frontend API Route:

    const body = await request.json()
    // Validate required fields
    if (\!body.feedbackType || \!['thumbs_up', 'thumbs_down'].includes(body.feedbackType)) {
      return new Response(
        JSON.stringify({ error: 'Invalid feedback type' }),
        { status: 400, headers: { 'Content-Type': 'application/json' } }
      )
    }

Priority 2 (Follow-up PR)

  1. Migrate to React Query Pattern:

    • Create services/queries/use-feedback.ts with useFeedbackMutation
    • Update FeedbackModal to use mutation hook
    • Follows project standards: .claude/patterns/react-query-usage.md
  2. Persist Feedback State:

    • Store submitted feedback in session storage
    • Key by message content hash or timestamp
    • Prevents duplicate submissions across remounts
  3. Add Observability:

    • Log feedback submission metrics (success/failure rates)
    • Track feedback types (thumbs up vs down ratio)
    • Monitor Langfuse integration health

Priority 3 (Nice to Have)

  1. Add E2E test for feedback flow
  2. Add loading state to feedback buttons
  3. Implement "Include previous messages" (vs all messages)
  4. Add feedback submission confirmation toast

Overall Assessment: Strong implementation with excellent security practices and UX design. The critical issues are fixable with small changes. The code demonstrates good understanding of the project's architecture and coding standards. Recommend fixing Priority 1 items before merge, then addressing Priority 2 in follow-up PRs.

Recommendation: ✅ Approve with changes - Address Priority 1 items (error handling, trace ID linking, input validation) then merge.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

@github-actions
Copy link
Contributor

github-actions bot commented Jan 19, 2026

Claude Code Review

Summary

This PR implements a user feedback mechanism allowing thumbs up/down ratings on AI agent messages, with optional comments and full transcript inclusion. The feedback flows from Frontend → Backend → Runner → Langfuse for observability tracking. The implementation follows AG-UI META event patterns and includes good security practices for input sanitization and RBAC enforcement.

Issues by Severity

🚫 Blocker Issues

None - No blocking issues found.

🔴 Critical Issues

1. Missing User Token Authentication in Frontend API Route

  • Location: components/frontend/src/app/api/projects/[name]/agentic-sessions/[sessionName]/agui/feedback/route.ts
  • Issue: The frontend API route acts as a proxy but doesn't verify user authentication before forwarding to backend. While the backend does auth, the frontend should validate first.
  • Current: Direct proxy without auth check
  • Expected: Should use auth helper to verify token exists before proxying
  • Security Impact: Medium - backend validates, but defense-in-depth requires frontend validation too
  • Reference: .claude/context/security-standards.md - validate at all boundaries

2. Potential Type Safety Issue in Frontend Context

  • Location: components/frontend/src/contexts/FeedbackContext.tsx:69
  • Issue: useMemo dependency array includes messages which is an array reference that changes frequently, causing unnecessary re-renders
  • Current: [projectName, sessionName, username, initialPrompt, activeWorkflow, messages, traceId]
  • Expected: Consider memoizing messages separately or using a stable reference
  • Performance Impact: Could cause excessive re-renders on every message update
  • Reference: .claude/patterns/react-query-usage.md - optimize dependencies

🟡 Major Issues

3. Missing HTTPS Validation in Runner Langfuse Host

  • Location: components/runners/claude-code-runner/main.py:1198
  • Issue: Accepts any host URL from environment variable without validation
  • Current: host = os.getenv("LANGFUSE_HOST", "").strip()
  • Expected: Should validate HTTPS scheme or at least warn on HTTP
  • Security Impact: Credentials could be sent over unencrypted connection
  • Recommendation: Add validation:
    host = os.getenv("LANGFUSE_HOST", "").strip()
    if host and not host.startswith("https://"):
        logger.warning("Langfuse host should use HTTPS for security")

4. Error Exposure in Frontend API Route

  • Location: components/frontend/src/app/api/projects/[name]/agentic-sessions/[sessionName]/agui/feedback/route.ts:385-389
  • Issue: Returns error details to client that may expose internal information
  • Current: details: error instanceof Error ? error.message : String(error)
  • Expected: Generic error message to user, detailed log on server
  • Reference: .claude/patterns/error-handling.md:199-220 - don't expose internal errors
  • Recommendation: Log full error, return generic message

5. Missing Input Validation in Runner

  • Location: components/runners/claude-code-runner/main.py:1132
  • Issue: No validation on payload field lengths (comment, context, transcript)
  • Current: Accepts unlimited length strings
  • Expected: Should enforce reasonable limits (e.g., 10KB for comment, 1MB for transcript)
  • Risk: Potential DoS via extremely large feedback payloads
  • Recommendation: Add length checks before processing

6. No Rate Limiting on Feedback Endpoint

  • Location: Backend websocket/agui_proxy.go:126 and Runner main.py:1132
  • Issue: No rate limiting on feedback submission
  • Risk: User could spam feedback submissions
  • Expected: Rate limiting per user/session (e.g., max 10 feedback/minute)
  • Impact: Could flood Langfuse with duplicate scores

🔵 Minor Issues

7. Inconsistent Type Usage (Frontend Pattern Violation)

  • Location: Multiple frontend files use type correctly ✅
  • Note: Good adherence to type over interface pattern
  • Reference: .claude/context/frontend-development.md:72-78

8. Missing Test Coverage

  • Issue: No tests added for new feedback functionality
  • Expected: Unit tests for:
    • Backend handler RBAC enforcement
    • Frontend modal form validation
    • Runner Langfuse integration
  • Reference: CLAUDE.md:853-866 - tests required for new functionality

9. Langfuse Import Location

  • Location: components/runners/claude-code-runner/main.py:1189
  • Issue: Import inside try/except is good for optional dependency, but could be at module level with conditional usage
  • Current: from langfuse import Langfuse inside function
  • Suggestion: Import at top with try/except, set flag for availability

10. Missing Documentation

  • Issue: No update to component READMEs or docs
  • Expected: Document new feedback feature in:
    • components/frontend/README.md
    • docs/ (user guide)
  • Reference: CLAUDE.md:1069-1075 - update existing docs

11. Unused Environment Variables in Deployment

  • Location: components/manifests/base/frontend-deployment.yaml:1099, overlays/local-dev/frontend-patch.yaml:1112
  • Issue: Comments say "Langfuse feedback now handled by runner" but no cleanup
  • Suggestion: If truly unused, remove old Langfuse env vars from frontend deployment

12. TypeScript any Usage

  • Location: components/backend/types/agui.go:66 (Go - not applicable)
  • Location: components/runners/claude-code-runner/main.py:1127 (Python Dict[str, Any])
  • Note: Python typing is acceptable here; no TypeScript any violations found in frontend ✅
  • Reference: .claude/context/frontend-development.md:15-34

Positive Highlights

Excellent Security Implementation

  • Proper input sanitization using SanitizeForLog helper (helpers.go:23)
  • RBAC enforcement before allowing feedback submission (agui_proxy.go:140-158)
  • User token authentication verified (agui_proxy.go:132-137)
  • Defense-in-depth approach with sanitization at multiple layers

Good Error Handling in Backend

  • Follows established patterns from .claude/patterns/error-handling.md
  • Logs errors with context (project, session, user)
  • Returns appropriate HTTP status codes
  • Graceful degradation when runner unavailable (agui_proxy.go:244-250)

Well-Structured Frontend Components

  • Clean separation: FeedbackButtons → FeedbackModal → FeedbackContext
  • Follows Shadcn UI patterns correctly
  • Good use of loading states and disabled buttons
  • Proper tooltip UX with TooltipProvider

Privacy-Conscious Design

  • Optional transcript inclusion (user must opt-in)
  • Clear privacy disclaimer in modal (FeedbackModal.tsx:843-853)
  • Metadata separation (structured metadata vs. free-form comment)

Type Safety

  • Strong typing throughout (TypeScript types, Pydantic models, Go structs)
  • No any types in TypeScript ✅
  • Proper type validation with binding:"required,oneof=..." in Go

Follows Established Patterns

  • Backend uses GetK8sClientsForRequest correctly ✅
  • Frontend uses React Context for state management ✅
  • AG-UI META event pattern followed correctly ✅

Recommendations

Priority 1 (Before Merge)

  1. Add Frontend Auth Check

    // In route.ts POST handler
    const headers = await buildForwardHeadersAsync(request)
    if (!headers['Authorization']) {
      return Response.json({ error: 'Unauthorized' }, { status: 401 })
    }
  2. Fix Error Exposure

    // In route.ts catch block
    console.error('Error submitting feedback:', error)
    return Response.json(
      { error: 'Failed to submit feedback' }, // Generic message only
      { status: 500 }
    )
  3. Add Input Validation in Runner

    MAX_COMMENT_LENGTH = 10000  # 10KB
    MAX_TRANSCRIPT_SIZE = 1000000  # 1MB
    
    if comment and len(comment) > MAX_COMMENT_LENGTH:
        raise HTTPException(status_code=400, detail="Comment too long")
  4. Optimize FeedbackContext useMemo

    // Consider using messages.length or last message timestamp as dependency
    const value = useMemo(() => ({ /* ... */ }), 
      [projectName, sessionName, username, initialPrompt, activeWorkflow, messages.length, traceId]
    )

Priority 2 (Follow-up PR)

  1. Add Rate Limiting

    • Backend: Use existing rate limiting middleware or implement per-session throttling
    • Suggestion: Max 10 feedback submissions per minute per user
  2. Add Tests

    • Backend: Test RBAC enforcement, input sanitization
    • Frontend: Test modal form validation, context provider
    • Runner: Test Langfuse integration with mock
  3. Documentation Updates

    • Add to components/frontend/README.md
    • Add to user guide in docs/
    • Document Langfuse configuration in deployment guide
  4. HTTPS Validation

    • Validate Langfuse host uses HTTPS in production
    • Warn on startup if using HTTP

Priority 3 (Nice to Have)

  1. Move Langfuse Import to Module Level

    • Import at top, set LANGFUSE_AVAILABLE flag
    • Cleaner code structure
  2. Cleanup Unused Env Vars

    • Remove Langfuse env var comments from frontend deployment if truly unused

Conclusion

This is a well-implemented feature with strong security practices and good adherence to project standards. The code follows established patterns for authentication, error handling, and type safety.

Main strengths:

  • Excellent security implementation (input sanitization, RBAC)
  • Clean component architecture
  • Privacy-conscious design

Main concerns:

  • Missing frontend auth validation (critical for defense-in-depth)
  • Error exposure to clients
  • Missing input validation and rate limiting
  • Performance optimization needed in React context

Recommendation: ✅ Approve with changes - Address Priority 1 items before merge, create follow-up issues for Priority 2 items.

Overall Code Quality: 8.5/10
Security Posture: 8/10 (would be 9/10 with frontend auth + rate limiting)
Adherence to Standards: 9/10


Review performed by Claude Code using project memory system (.claude/context/, .claude/patterns/, CLAUDE.md)


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

@github-actions
Copy link
Contributor

github-actions bot commented Jan 19, 2026

Claude Code Review

Summary

This PR implements a user feedback mechanism using thumbs up/down buttons on agent messages, integrated with Langfuse's Scores API for observability tracking. The implementation follows the AG-UI META events pattern and includes a modal for collecting detailed feedback context.

Overall Assessment: Good implementation with strong security patterns, but several critical issues need addressing before merge.


Issues by Severity

🚫 Blocker Issues

1. Missing Input Sanitization in Frontend Route Handler

  • File: components/frontend/src/app/api/projects/[name]/agentic-sessions/[sessionName]/agui/feedback/route.ts
  • Issue: Route parameters (name, sessionName) are not sanitized before being used in URLs and logs
  • Risk: Potential log injection, URL injection vulnerabilities
  • Fix: Apply input validation/sanitization to route parameters before use
  • Pattern Violation: Security standards require sanitizing all user input (security-standards.md:95-117)

2. Backend SanitizeForLog Not Applied Consistently

  • File: components/backend/websocket/agui_proxy.go:661-662
  • Issue: input.FeedbackType is validated by struct tag but sanitized redundantly on line 662, 747. This is defense-in-depth (good) but the comment suggests it's validated - should clarify this is extra safety.
  • Location: agui_proxy.go:662, 747
  • Pattern: While not wrong, the comments are slightly misleading about why sanitization is applied to validated fields

🔴 Critical Issues

3. Type Safety Violation in FeedbackModal

  • File: components/frontend/src/components/feedback/FeedbackModal.tsx:36-37
  • Issue: Type guard m.type !== undefined is insufficient. Should check for specific message types.
  • Risk: Runtime errors if message structure changes
  • Fix: Use proper discriminated union type guards
// Current (weak):
.filter((m): m is MessageObject => "type" in m && m.type !== undefined)

// Better:
.filter((m): m is MessageObject => 
  "type" in m && 
  (m.type === "user_message" || m.type === "agent_message")
)
  • Pattern Violation: Frontend standards require proper type guards (frontend-development.md:19-34)

4. Missing Error Boundary for Feedback Components

  • File: components/frontend/src/components/feedback/FeedbackButtons.tsx
  • Issue: No error boundary wrapping feedback UI - errors could crash entire session page
  • Risk: Poor user experience if feedback submission fails
  • Recommendation: Wrap in error boundary or add try-catch with fallback UI

5. No Loading State on Route Handler

  • File: components/frontend/src/app/api/projects/[name]/agentic-sessions/[sessionName]/agui/feedback/route.ts
  • Issue: No timeout or loading indicators for fetch operation
  • Risk: Hanging requests with no user feedback
  • Pattern Violation: All buttons should have loading states (DESIGN_GUIDELINES.md)

🟡 Major Issues

6. Context Provider Always Required

  • File: components/frontend/src/contexts/FeedbackContext.tsx:60-65
  • Issue: useFeedbackContext throws error if context missing, but useFeedbackContextOptional exists. Pattern is inconsistent.
  • Fix: Document when to use each, or consolidate to optional-only pattern
  • Impact: Could cause confusion for future developers

7. Missing RBAC Permission Documentation

  • File: components/backend/websocket/agui_proxy.go:627-644
  • Issue: Feedback endpoint requires update permission on session. This is correct but should be documented.
  • Fix: Add comment explaining why update (not get) is required for feedback submission
// SECURITY: Verify user has permission to update this session
// Feedback submission requires 'update' permission because it modifies
// session observability state (Langfuse scores are mutable session data)

8. Langfuse Trace ID Pattern Unclear

  • File: components/runners/claude-code-runner/main.py:368
  • Issue: Trace ID generation uses feedback-{session}-{timestamp} but doesn't link to actual session trace
  • Risk: Feedback scores won't correlate with session traces in Langfuse UI
  • Recommendation: Document trace ID strategy or link to session's actual trace ID
# Current: Creates isolated feedback trace (not linked to session)
trace_id = f"feedback-{session_name}-{event.ts or int(__import__('time').time() * 1000)}"

# Consider: Link to actual session trace for better correlation
# trace_id = get_session_trace_id(session_name)  # or similar

9. No Rate Limiting on Feedback Endpoint

  • File: components/backend/websocket/agui_proxy.go:612, main.py:296
  • Issue: No rate limiting prevents spam/abuse
  • Risk: Users could spam feedback submissions
  • Recommendation: Add rate limiting middleware (e.g., 5 feedback/minute per user)

10. Missing Feedback Button Accessibility

  • File: components/frontend/src/components/feedback/FeedbackButtons.tsx:71, 101
  • Issue: aria-label changes after submission (good), but no aria-pressed state
  • Fix: Add aria-pressed={isPositiveSubmitted} for screen readers
<button
  aria-label={isPositiveSubmitted ? "Positive feedback submitted" : "This was helpful"}
  aria-pressed={isPositiveSubmitted}  // Add this
  ...
>

🔵 Minor Issues

11. Inconsistent Comment Style

  • File: components/backend/types/agui.go:43-45
  • Issue: Comment uses // but should use doc comment // with proper capitalization
  • Fix: Follow Go doc comment conventions

12. Magic Numbers in Frontend

  • File: components/frontend/src/components/feedback/FeedbackModal.tsx:172
  • Issue: rows={3} is hardcoded
  • Recommendation: Extract to const: const FEEDBACK_TEXTAREA_ROWS = 3

13. Unused Import

  • File: components/frontend/src/components/feedback/FeedbackModal.tsx:18
  • Issue: Info icon imported but only used once - not a real issue but worth noting

14. Missing JSDoc for Exported Functions

  • Files: FeedbackButtons.tsx, FeedbackModal.tsx
  • Issue: Exported components lack JSDoc comments
  • Recommendation: Add brief JSDoc for better IDE hints

15. Python Type Hints Incomplete

  • File: main.py:296
  • Issue: handle_feedback return type not annotated
  • Fix: Add -> dict: return type annotation

Positive Highlights

Excellent Security Practices

  • Consistent use of GetK8sClientsForRequest for user authentication (agui_proxy.go:618)
  • RBAC checks before feedback submission (agui_proxy.go:627-644)
  • Input sanitization with SanitizeForLog helper (agui_proxy.go:614, 615, 648, 662, 747)
  • Proper token redaction patterns followed

Good Error Handling

  • Backend gracefully handles runner unavailability (agui_proxy.go:730-736)
  • Frontend shows user-friendly error messages (FeedbackModal.tsx:211-215)
  • Proper error propagation from backend → frontend

Clean Architecture

  • Clear separation: Frontend → API Route → Backend → Runner → Langfuse
  • Follows AG-UI META events pattern correctly
  • Context provider pattern is clean and extensible

Good UX Patterns

  • Feedback buttons disabled after submission (prevents double-submit)
  • Tooltip feedback confirms submission
  • Modal provides privacy disclaimer
  • Optional transcript inclusion gives users control

Type Safety (Mostly)

  • Strong typing in backend (Go structs with validation tags)
  • TypeScript types for AG-UI events
  • Pydantic models for Python validation

Proper Use of React Patterns

  • Uses Shadcn UI components (no custom buttons) ✅
  • State management with useState is appropriate
  • useMemo in context provider prevents unnecessary re-renders

Documentation

  • Comments reference AG-UI docs and Langfuse API
  • Security comments explain RBAC decisions
  • Code is generally self-documenting

Recommendations

High Priority (Before Merge)

  1. Fix input sanitization in frontend route handler (Blocker Outcome: Reduce Refinement Time with agent System #1)
  2. Add error boundary for feedback components (Critical Epic: AI Agent Development #4)
  3. Improve type guards in FeedbackModal (Critical Epic: Data Source Integration #3)
  4. Document Langfuse trace ID strategy (Major Test: Updated Workflow Validation #8)
  5. Add accessibility attributes (Major Bump actions/checkout from 4 to 5 #10)

Medium Priority (Consider for Follow-Up)

  1. Add rate limiting on feedback endpoint (Major Bump actions/add-to-project from 0.5.0 to 1.0.2 #9)
  2. Add loading timeout to route handler (Critical Epic: Jira Integration & Workflow #5)
  3. Consolidate context provider hook patterns (Major Epic: Testing & Validation #6)
  4. Add JSDoc comments to exported components (Minor Add OpenShift AI Virtual Team agents as source of truth #14)

Low Priority (Nice to Have)

  1. Extract magic numbers to constants (Minor Add vTeam shared Claude Code configuration with hooks-based enforcement #12)
  2. Add Python return type annotations (Minor Add RFE Council workflow diagram #15)
  3. Consider error boundary at page level for entire feedback flow

Testing Recommendations

Missing Test Coverage:

  • No frontend tests for FeedbackModal form submission
  • No backend tests for feedback endpoint RBAC
  • No integration tests for end-to-end feedback flow
  • No tests for Langfuse integration (mock recommended)

Suggested Tests:

// Frontend (Jest + React Testing Library)
describe('FeedbackModal', () => {
  it('submits positive feedback with comment', async () => { ... })
  it('handles submission errors gracefully', async () => { ... })
  it('includes transcript when checkbox selected', async () => { ... })
})
// Backend (Go testing)
func TestHandleAGUIFeedback_RBAC(t *testing.T) {
  // Test unauthorized user cannot submit feedback
}
func TestHandleAGUIFeedback_ValidInput(t *testing.T) {
  // Test valid feedback is forwarded to runner
}

Architectural Review

Design Patterns: ✅ Well-structured

  • Follows repository's established patterns (backend proxy → runner)
  • Proper separation of concerns (UI → API → Backend → Observability)
  • Context provider for cross-component state is appropriate

Security: ⚠️ Mostly good, needs minor fixes

  • RBAC enforcement is correct
  • Input sanitization mostly applied (needs frontend route fix)
  • No sensitive data logged (follows token security patterns)

Performance: ✅ No concerns

  • Feedback submission is async (non-blocking)
  • Langfuse flush is immediate but happens in background
  • No N+1 queries or obvious bottlenecks

Scalability: ⚠️ Minor concerns

  • No rate limiting (could be abused)
  • Langfuse trace ID strategy unclear (may impact observability at scale)

Compliance Checklist

Reviewing against CLAUDE.md standards:

Backend Standards (CLAUDE.md:420-891)

  • ✅ User token authentication used (GetK8sClientsForRequest)
  • ✅ RBAC checks performed before operations
  • ✅ Error handling follows patterns (log + return generic error)
  • ✅ Token security: SanitizeForLog used consistently
  • ✅ No panics in production code
  • ⚠️ Missing tests for new handler

Frontend Standards (CLAUDE.md:1109-1136)

  • ✅ Zero any types (all properly typed)
  • ✅ Shadcn UI components used exclusively
  • ❌ React Query not used (uses direct fetch) - Pattern Violation
    • FeedbackModal.tsx:99 should use a mutation hook
  • ✅ Uses type over interface
  • ✅ Single-use components colocated (feedback/)
  • ⚠️ Missing loading states on some buttons
  • ❌ Missing tests

Security Standards (security-standards.md)

  • ✅ User token auth enforced
  • ✅ RBAC checks before mutations
  • ⚠️ Input validation incomplete (frontend route)
  • ✅ Token redaction in logs
  • ✅ Container security (N/A for this PR)

Final Verdict

Overall Grade: B+ (Good, but needs fixes before merge)

Strengths:

  • Clean implementation following AG-UI patterns
  • Strong security awareness (RBAC, sanitization)
  • Good UX with feedback and privacy controls
  • Well-structured architecture

Must Fix Before Merge:

  1. Input sanitization in frontend route handler
  2. Type guard improvements in FeedbackModal
  3. Error boundary for feedback components
  4. Document Langfuse trace ID strategy

Should Fix Soon (Follow-up OK):
5. Add React Query mutation hook (pattern compliance)
6. Add rate limiting
7. Add test coverage
8. Improve accessibility

Recommendation: Request changes for blockers/critical issues, then approve after fixes. The core implementation is solid but needs polish on security and type safety details.


🤖 Generated by Claude Code Review - Checked against project standards in CLAUDE.md, security-standards.md, frontend-development.md, backend-development.md, and established patterns.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

Gkrumbach07 and others added 4 commits January 20, 2026 17:53
- Introduced a new command for logging Jira issues with pre-filled fields for the Ambient team and Agentic component.
- Updated the AG-UI feedback handling to include trace ID for better association of feedback with specific interactions.
- Enhanced the feedback submission process to utilize AG-UI META events, improving observability and user experience.
- Streamlined the frontend feedback modal to construct and send structured META events, including optional fields like trace ID and context.

These changes improve the overall feedback mechanism and facilitate better tracking of user interactions.
- Updated the feedback value mapping from numeric to boolean, improving clarity in the representation of user feedback (thumbs up/down).
- Changed the data type for feedback submissions from "NUMERIC" to "BOOLEAN" to align with the new mapping.
- Removed obsolete code related to fallback handling for feedback submissions.

These changes enhance the feedback processing logic and ensure consistency in data representation.
- Eliminated the session_id parameter from the create_score() API call, simplifying the feedback submission process.
- This change aligns with the existing logic to prioritize trace_id for user feedback tracking, enhancing clarity and consistency in data handling.

These modifications improve the feedback processing workflow and ensure adherence to the updated data requirements.
@github-actions
Copy link
Contributor

github-actions bot commented Jan 21, 2026

Claude Code Review

Summary

This PR implements per-message user feedback using Langfuse Scores API. Overall architecture is solid but several critical issues must be addressed before merge.

Critical Blockers

1. Frontend - React Query Violation

  • FeedbackModal.tsx:131-135 uses manual fetch() instead of React Query
  • Violates DESIGN_GUIDELINES.md requirement
  • No retry/caching/loading state management

2. Backend - Missing Input Validation

  • agui_proxy.go:629-634 accepts raw JSON without validation
  • No size limits - DoS risk
  • Must add payload size limits and field validation

3. Backend - Silent Data Loss

  • Returns 202 when runner unavailable but data is lost
  • Should queue for retry OR return 503 error

4. Python Runner - Session Management

  • Creates new Langfuse client instead of using existing observability context
  • Feedback scores orphaned from session traces
  • Must integrate with existing tracker

5. Python Runner - Error Handling

  • Swallows exceptions - frontend shows success even on failure
  • Missing payload validation

Critical Issues

6. Type Safety

  • Frontend: error typed as unknown but used as Error
  • Backend: Uses map[string]interface{} instead of typed structs

7. Error Message Leakage

  • Backend exposes internal details in error responses

8. Missing Observability

  • No metrics for submission rate/errors/latency

Positive Highlights

  1. Excellent security with proper RBAC and user-scoped K8s clients
  2. Good architecture with clear separation of concerns
  3. Follows AG-UI protocol correctly
  4. Privacy-conscious with opt-in transcript
  5. Uses Shadcn UI components
  6. Token sanitization prevents log injection

Recommendations

Must Fix Before Merge:

  1. Add input validation with size limits to backend
  2. Migrate frontend to React Query
  3. Fix runner to use existing session context
  4. Add error recovery UI
  5. Validate trace_id linkage

Should Fix:
6. Add comprehensive error handling
7. Add telemetry/metrics
8. Sanitize error messages
9. Add unit tests

Overall: Strong implementation but critical issues block approval. Security is good but input validation and React Query compliance are mandatory.

Recommendation: Request changes


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

Gkrumbach07 and others added 2 commits January 21, 2026 13:29
- Implemented persistence for META events to ensure feedback survives reconnects and session restarts.
- Updated the backend to extract and utilize runId from feedback events for better association with specific runs.
- Modified the frontend to preserve message IDs for feedback association, improving the tracking of user feedback.
- Enhanced the FeedbackModal and FeedbackButtons components to support message ID handling and existing feedback retrieval.

These changes improve the robustness of the feedback system and enhance the user experience by ensuring accurate feedback tracking.
Enhance AG-UI feedback handling and message association
@Gkrumbach07 Gkrumbach07 merged commit 9b696f7 into ambient-code:main Jan 21, 2026
27 of 32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants