Skip to content

Refactor: Simplify useAISession hook by extracting mode transition logic #4259

@elias-ba

Description

@elias-ba

Summary

The useAISession hook in assets/js/collaborative-editor/hooks/useAISession.ts is 287 lines and handles multiple concerns:

  • Mode change detection (job_code vs workflow_template)
  • Job change detection within job_code mode
  • Channel subscription lifecycle
  • Context initialization
  • URL synchronization

The contextMismatch check (lines 190-197) is a band-aid compensating for ref timing issues rather than addressing the root cause.

Proposed Solution

Extract mode transition logic to a new useAIModeTransition hook:

// New hook handles mode/job change detection and cleanup
export const useAIModeTransition = ({
  aiMode,
  aiStore,
  onModeChange,
}: {
  aiMode: AIMode | null;
  aiStore: AIAssistantStoreInstance;
  onModeChange: () => void;
}) => {
  // Handles mode change detection, session/list clearing, connection state reset
  // Returns { mode, jobId }
};

This would allow useAISession to focus solely on channel subscription lifecycle (~150 lines).

Benefits

  • Each hook has single responsibility
  • Removes the contextMismatch band-aid by handling mode transitions explicitly
  • Easier to test, debug, and modify
  • Future developers understand the flow without reverse-engineering ref timing

Files to Modify

  • Create: assets/js/collaborative-editor/hooks/useAIModeTransition.ts
  • Modify: assets/js/collaborative-editor/hooks/useAISession.ts
  • Modify: assets/js/collaborative-editor/components/AIAssistantPanelWrapper.tsx

Related

This was identified during the review of PR #4249 (collaborative AI chat sessions).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Tech Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions