All session endpoints (get, update, complete, scratchpad, variables, export,
ticket-link) now return 404 instead of 403 when a user tries to access
another user's session. This prevents confirming existence of resources
across tenant boundaries.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Cross-tenant isolation audit found:
- retry-psa-push had NO ownership check (CRITICAL) — any user could retry any session's PSA push
- save_task_lane used db.get() without ownership filter, returned 403 revealing existence
- get_session returned 403 instead of 404 for unauthorized access
- stream_documentation returned 403 instead of 404
All now use query-level user_id filtering and return 404 to avoid revealing existence.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Search endpoint used OR(user_id, account_id), exposing other users'
problem_summary and problem_domain within the same account. Sessions
are user-scoped only — cross-user access requires explicit escalation
or sharing. List and search endpoints now behave consistently.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
tree_count on GET /categories/{id} was including trees from all
accounts, leaking cross-tenant row counts.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Any authenticated user could read flow analytics (session counts,
completion rates, CSAT) for any tree UUID. Now returns 404 if the
tree doesn't belong to the requesting account.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
tenant_filter(model, account_id) is the canonical app-layer tenant
scoping expression. Every query on a tenant table must use it.
build_tree_access_filter and build_step_visibility_filter updated
to call tenant_filter() internally for the account_id match.
get_tenant_context is a FastAPI dependency that returns account_id
or raises 403 if the user has no account — prevents raw access to
current_user.account_id and centralises the null check.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- script_builder endpoint: pg_advisory_xact_lock on user_id before
session count check, preventing concurrent creates from both passing
the MAX_SESSIONS_PER_USER guard
- script_builder_service send_message: pg_advisory_xact_lock on session_id
before message count check, preventing concurrent sends from both
passing the MAX_MESSAGES_PER_SESSION guard
- script_builder_service save_to_library: replace check-then-insert slug
logic with IntegrityError retry loop (3 attempts with fresh UUID suffix);
add unique constraint on script_templates.slug (migration 070)
- ScriptBuilderPage: add creatingSessionRef to serialize concurrent
handleSend calls that would otherwise both call createSession() while
session is still null
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Previously save_to_library() hardcoded parameters_schema to empty and
always used session.latest_script. Now accepts optional overrides from
the frontend for parameterized script bodies.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
_build_session_detail was omitting pending_task_lane, is_branching, and
active_branch_id from the GET /ai-sessions/{id} response. The fields
existed on the schema and model but were never passed in the manual
constructor, so task lane state could never be restored on navigation.
Also adds console logging to AssistantChatPage selectChat flow to
diagnose message restoration, and fixes ScriptTemplateEditor stepper
dismiss firing during programmatic script_body updates.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add PUT /ai-sessions/{id}/task-lane endpoint that saves the full task
lane state (AI questions/actions + user's in-progress responses) to
the pending_task_lane JSONB column. TaskLane debounce-saves to the
backend every 2s after changes. On session load, user responses are
restored from the backend into sessionStorage so TaskLane picks them
up on mount. Users can now close the browser, come back later, and
find their task lane exactly where they left it.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add DOCX MIME type to ALLOWED_DOCUMENT_TYPES in storage_service.py
- Add python-docx text extraction in _generate_ai_description
- Extract shared _store_document_content helper for PDF/DOCX
- Add python-docx>=1.1.0 to requirements.txt
- Add tests for docx upload acceptance and document fetch
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
PDF uploads were stored in S3 and had text extracted during upload, but
fetch_upload_images() filtered exclusively for image MIME types, so
document content never reached the AI.
- Add fetch_upload_documents() in storage_service.py to retrieve
extracted_content for PDFs and text files
- Update ai_sessions.py chat endpoint to call both fetch_upload_images
and fetch_upload_documents, injecting document text as context
- Add PDF text extraction in _generate_ai_description (pypdf)
- Add pypdf>=4.0.0 to requirements.txt
- Fix test_db teardown to avoid connection pool issues
- Add 5 tests for fetch_upload_documents
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
When user.team_id is None, `WHERE team_id == None` matches all
personal templates. Return empty set instead when user has no team.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- script_template.py: add server_default for requires_elevation,
is_gallery_featured, gallery_sort_order so Base.metadata.create_all
emits proper SQL DEFAULTs (test fixtures use raw SQL INSERT)
- session_branches.py: refresh fork_point after commit so JSONB options
field is loaded before Pydantic serialization
- test_session_branches_api.py: add status assertion on fork response
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Fix system prompt to ensure [QUESTIONS]/[ACTIONS] markers in AI responses
- Add format reminder injection to user messages for marker compliance
- Wire TaskLane activation in prefill and resume paths
- Add ActionCardGroup component for structured question/action rendering
- Update FlowPilot session and step card components
- Update ai-session schemas and types for marker data
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Integrates ResolutionOutputGenerator into the resolve endpoint so that
structured outputs (ticket note, KB article, etc.) are auto-generated
after every successful session resolution. Non-blocking — resolve still
succeeds if output generation fails.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Adds _generate_ai_description background task that fires after a
successful upload: images get a one-sentence vision description via
Claude, text/log/config files get extracted_content + AI summary when
>2000 chars. Runs as asyncio.create_task so it never blocks the upload
response. Errors are logged and swallowed.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Adds GET /outputs, PATCH /outputs/{id}, and POST /outputs/{id}/push
endpoints under /ai-sessions/{session_id}/, plus integration tests.
Router registered before ai_sessions to avoid path conflict.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Four endpoints: create handoff (park/escalate), list handoff history,
claim session, and team queue. Two routers: session-scoped router with
prefix /ai-sessions/{session_id} and queue_router with prefix /ai-sessions.
queue_router registered before ai_sessions.router to avoid /{session_id}
path conflict on GET /ai-sessions/queue.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The old /assistant/chats/* CRUD endpoints and assistant_chat_service
chat functions were unused — the frontend exclusively uses
/ai-sessions/{id}/chat (unified_chat_service) for all chat operations.
Removed:
- Chat CRUD endpoints (create, list, get, send, delete, conclude)
- assistant_chat_service: create_chat, send_message,
generate_conclusion_summary, CONCLUSION_SYSTEM_PROMPT
- Frontend: assistantChatApi chat methods, dead types
(AssistantChat, AssistantChatMessage, ConcludeChatRequest, etc.)
Kept:
- /assistant/retention endpoints (used by ChatRetentionSettingsPage)
- Shared AI infrastructure (_call_ai, _call_anthropic_cached,
ASSISTANT_SYSTEM_PROMPT, _auto_title) — imported by unified_chat_service
Moved:
- fetch_upload_images + resize_image_for_vision → storage_service.py
(shared location, not tied to dead endpoint)
Also added "Image Analysis" section to system prompt so Claude knows
to describe attached screenshots.
-650 lines of dead code removed.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The frontend calls /ai-sessions/{id}/chat (unified_chat_service), not
/assistant/chats/{id}/messages (assistant_chat_service). The previous
commit wired images into the wrong backend. This fixes it:
- ai_session.py schema: add upload_ids to ChatMessageRequest
- ai_sessions.py endpoint: fetch images via _fetch_upload_images
- unified_chat_service: accept and forward images to _call_ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Backend: ChatMessageRequest accepts upload_ids, endpoint fetches
images from S3, base64-encodes them, passes to Claude as multimodal
content blocks (vision API)
- Backend: add download_file() to storage_service for fetching from S3
- Frontend: handleSend collects completed upload IDs from pendingUploads
and includes them in the sendChatMessage API call
- Frontend: prefill handler passes upload IDs from dashboard nav state
- Enables paste-screenshot → AI-sees-it flow end-to-end
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add session_type ('guided'|'chat') and title columns to ai_sessions,
enabling both FlowPilot guided sessions and assistant chat sessions to
live in a single table. This is the foundation for a unified session
history and consistent UX across both interaction modes.
Backend:
- Migration 066: session_type + title columns
- unified_chat_service: chat sessions on ai_sessions with same AI/RAG
- POST /ai-sessions supports session_type='chat' creation
- POST /ai-sessions/{id}/chat for chat messages
- DELETE /ai-sessions/{id} for session deletion
- session_type filter on GET /ai-sessions
Frontend:
- AssistantChatPage rewired to aiSessionsApi (no more assistantChatApi)
- /assistant/:sessionId route for deep-linking
- Session history: type filter pills (All/Guided/Chat), type icons
- Dashboard: both types shown with correct routing and icons
- Fixed glass-border → border-default in dashboard components
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Full-stack beta feedback system:
Backend:
- BetaFeedback model with reaction, category, text, page context
- POST /feedback/beta (any auth user), GET /feedback/beta (admin, filtered)
- Alembic migration 065 with indexes on user_id, reaction, created_at
Frontend:
- Persistent "Feedback" tab on right edge of all authenticated pages
- Slide-out panel: quick reaction (👍😐👎), category pills, optional text
- Auto-captures page URL and FlowPilot session ID
- Hidden on mobile (<640px), closes on Escape/outside click
- Shows "Thanks!" confirmation then auto-closes
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Engineers can now generate AI-powered status updates during active FlowPilot
sessions and after resolve/escalate. Three audiences (Ticket Notes, Client
Update, Email Draft) with Quick/Detailed length options. Copy to clipboard
with one click. Client names auto-inserted from intake/PSA context.
Backend: new endpoint POST /ai-sessions/{id}/status-update with audience-aware
system prompts. Frontend: StatusUpdateModal with 2-step selection flow,
Share Update button in action bar, Share Resolution/Escalation on completed
sessions. Also updates Solutions Library spec with Community tier design.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Extract JSONB messages array from script_builder_sessions into a proper
script_builder_messages table with individual columns for role, content,
script, tokens, etc. Migration handles data migration from JSONB to rows.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Message bar now fixed-positioned above action bar with full-width
layout (respects both app sidebar and session sidebar)
- Added abandon_session endpoint (POST /ai-sessions/{id}/abandon)
- Added "Close" button to FlowPilot action bar with confirmation dialog
- Session can now be closed without resolving or escalating
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add language column (powershell/bash/python) to script_templates model and schemas
- Seed 'AI Generated' script category via migration 063
- Add mine and shared query params to list_templates endpoint
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Script Builder service with language-specific system prompts (PowerShell, Bash, Python)
- AI-powered script generation with code block extraction and filename detection
- Context window management (last 20 messages) and session message limits
- REST API: CRUD sessions, send messages, save to Script Library
- Rate limiting on message endpoint (10/min), max 5 concurrent sessions per user
- Registered script_build action in AI model tier routing (standard tier)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Users without team_id (solo accounts, pro plans) couldn't see
escalations because the query filtered by team_id which was NULL.
Now falls back to account_id scoping for both the escalation queue
endpoint and the sidebar badge count.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add escalation_count to sidebar stats (team-wide requesting_escalation)
- Show badge on Escalations nav item in sidebar
- Remove user_id filter from escalation queue — show all team escalations
including your own (needed for solo users and visibility)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The same model_validate bug existed in link_ticket endpoint (line 467).
Extracted the manual AISessionDetail construction into a shared helper
_build_session_detail() used by both get_session and link_ticket.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Root cause: AISessionDetail.model_validate(session) tried to validate the
ORM relationship 'steps' which has field 'id', but AISessionStepResponse
expects 'step_id'. This caused a Pydantic ValidationError on every session
detail load.
Fix: Construct AISessionDetail manually from ORM fields, passing the
already-built step_responses list directly instead of relying on
model_validate to serialize the ORM steps relationship.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Temporary debug commit — surfaces the actual exception when GET /ai-sessions/{id}
fails with 500, instead of generic "Internal server error" from middleware.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Root cause: embedding generation could break the DB transaction via a failed
SQL statement. The except block caught the Python error but left the transaction
in a failed state. Subsequent queries (_record_usage → subscription lookup)
then failed with InFailedSQLTransactionError.
Fixes:
- session_embedding_service: use begin_nested() savepoint so failures don't
poison the parent transaction
- ai_sessions.py: add db.rollback() before _record_usage in all 3 error
handlers (create, respond, pickup) to recover from broken transactions
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Fix AISession.ticket_id → psa_ticket_id in list_sessions filter query
- Add Gallery nav item (LayoutGrid icon) to AdminSidebar navItems array
- Remove ForeignKey from FileUpload.session_id (Python model) + migration b8d2f4a6c091 to drop DB constraint, allowing column to reference either session type
- Add 400ms debounce on AI session search input in SessionHistoryPage (aiSearchInput state + useRef timeout pattern)
- Show friendly 503 error message in RichTextInput upload error handler (both initial upload and retry paths)
- Add overflow-x-auto to FlowPilotAnalyticsPage tab bar container
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Adds vector-based similar session discovery using the existing Voyage AI
embedding infrastructure and pgvector cosine similarity search.
- New AISessionEmbedding model with vector(1024) column
- session_embedding_service: generate + upsert embeddings, find similar sessions
- Embeddings generated on session create (from problem_summary/domain) and
updated on resolve (adds resolution_summary)
- GET /ai-sessions/{id}/similar endpoint returns top-N similar sessions
- Migration a7c9e3b1f402 creates ai_session_embeddings table
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- POST /uploads: multipart upload with content-type/size validation, per-session limits, S3 storage
- GET /uploads/{id}/url: presigned download URL with account ownership check
- GET /uploads: list uploads for a session
- DELETE /uploads/{id}: delete with ownership enforcement (403 for non-owners)
- Returns 503 gracefully when STORAGE_ENDPOINT is not configured
- 15 integration tests covering auth, validation, 503 behavior, and ownership
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Issue 1: Normalize domain lookup to lowercase on both sides (flow category names and session problem_domain) to fix case-sensitive mismatch in coverage endpoint
- Issue 2: Count distinct ai_session_id (not PsaPostLog.id) in doc_pushed funnel step to avoid inflating counts on retried sessions
- Issue 3: Clamp recency_score to [0.0, 1.0] with min/max to handle negative days_since from future timestamps (clock skew/test data)
- Issue 4: Wrap func.sum(case(...)) results with int() in dashboard endpoint to handle Decimal returns from asyncpg
- Issue 5: Remove dead domain_flow_counts_result query (result fetched but never consumed) to eliminate unnecessary DB round-trip
- Issue 6: Replace select(Tree) with select(Tree.id, Tree.name, Tree.tree_type) in flow-quality endpoint to avoid loading large tree_structure JSONB column
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Log `note_posted` and `time_entry_posted` activities to `psa_activity_logs`
after each successful PSA push in `psa_documentation_service.py`; errors
are caught and logged without blocking the main push flow
- Add `PsaFunnel`, `PsaDailyTrend`, and `EnhancedPsaMetrics` Pydantic schemas
- Add `GET /analytics/flowpilot/psa-metrics?period=30d` endpoint (team_admin,
rate-limited 15/min) returning time entry totals, push funnel
(sessions → linked → doc pushed → time entry logged), and daily trend
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add branding_logo_url, branding_primary_color, branding_company_name columns to Account model
- Add Alembic migration (58e3f27f3e8f) for branding and SSO columns
- Add GET/PATCH /accounts/me/branding endpoints (owner-only for PATCH)
- Add BrandingSettingsPage with logo URL input, color picker, preview section
- Add /account/branding route (ProtectedRoute owner) in router.tsx
- Add Branding link card in AccountSettingsPage
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add super-admin-only backend endpoints for toggling is_gallery_featured and
gallery_sort_order on flows and scripts, plus a frontend GalleryManagementPage
with toggle switches, editable sort order fields, and name/featured filters.
13 integration tests; all pass.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>