All files / src/session-inputs session-inputs.service.ts

63.95% Statements 126/197
54.09% Branches 33/61
62.06% Functions 18/29
63.54% Lines 122/192

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 63315x             15x 15x 15x                         15x       15x 15x 15x 15x 15x     4x   1x           3x                 15x 32x       32x   32x   32x   32x   32x 32x 32x 32x 32x 32x 32x 32x 32x 32x       9x 6x     3x 3x               3x               3x 6x     3x       3x         4x                                                                                                                     10x     10x                                           10x       10x                 10x 1x     9x 9x             9x     9x           9x                 9x     9x     9x                 9x                                                     37x                   37x 3x       34x                                                                                                                                                                                                                                                                                             9x       9x         9x 2x           7x         7x 15x     7x             7x 7x 6x       6x 6x       7x 1x           6x 6x 2x 1x     1x       6x     6x 6x 6x 6x 6x 6x 6x 6x 6x       6x   6x     2x           6x                       17x       17x     14x 4x   14x 4x   14x     14x 2x   14x 4x       14x     14x 4x     14x   14x                   4x   4x         4x   2x 2x 2x       2x                               6x       6x 1x           5x 9x       5x       5x      
import {
  Injectable,
  NotFoundException,
  Logger,
  forwardRef,
  Inject,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import {
  Session,
  SessionInput,
  ContextTemplate,
  AIAction,
  ExecutionLog,
} from '../core-entities';
import {
  CreateSessionInputDto,
  UpdateSessionInputDto,
  UpdateSessionInputContentDto,
  BatchToggleDiscardedDto,
} from './dto/session-input.dto';
import {
  AIActionsService,
  AIActionStatus,
} from '../ai-actions/ai-actions.service';
import { SystemPromptsService } from '../system-prompts/system-prompts.service';
import { SessionInputContextService } from './session-input-context.service';
import { ApplicationStateService } from '../application-state/application-state.service';
import { ChatService } from '../interactive-chat/chat.service';
import { LlmResponsesService } from '../llm-responses/llm-responses.service';
 
function formatActionStatusForLLM(status: AIActionStatus): string {
  switch (status) {
    case AIActionStatus.CONFIRMED_KEPT:
      return 'The user confirmed and kept the changes.';
    case AIActionStatus.CONFIRMED_REVERTED:
      return 'The user chose to revert the changes.';
    case AIActionStatus.REJECTED_BEFORE_APPLY:
      return 'The action was rejected by the user before being applied.';
    case AIActionStatus.EXECUTION_FAILED:
      return 'The action failed to execute.';
    case AIActionStatus.REVERT_FAILED:
      return 'Reverting the action failed.';
    default:
      return `The action's final status was '${status}'.`;
  }
}
 
@Injectable()
export class SessionInputsService {
  private readonly logger = new Logger(SessionInputsService.name);
 
  constructor(
    @InjectRepository(Session)
    private sessionsRepository: Repository<Session>,
    @InjectRepository(SessionInput)
    private sessionInputsRepository: Repository<SessionInput>,
    @InjectRepository(ContextTemplate)
    private contextTemplatesRepository: Repository<ContextTemplate>,
    @InjectRepository(AIAction)
    private aiActionsRepository: Repository<AIAction>,
    @InjectRepository(ExecutionLog)
    private executionLogsRepository: Repository<ExecutionLog>,
    @Inject(forwardRef(() => AIActionsService))
    private readonly aiActionsService: AIActionsService,
    private readonly systemPromptsService: SystemPromptsService,
    private readonly sessionInputContextService: SessionInputContextService,
    private readonly applicationStateService: ApplicationStateService,
    @Inject(forwardRef(() => ChatService))
    private readonly chatService: ChatService,
    @Inject(forwardRef(() => LlmResponsesService))
    private readonly llmResponsesService: LlmResponsesService,
  ) {}
 
  private generatePreviousActionsSummary(session: Session): string {
    if (!session.sessionInputs || session.sessionInputs.length === 0) {
      return '';
    }
 
    const lastInput = session.sessionInputs[session.sessionInputs.length - 1];
    Iif (
      !lastInput ||
      !lastInput.aiActions ||
      lastInput.aiActions.length === 0
    ) {
      return '';
    }
 
    const finalStatuses: string[] = [
      AIActionStatus.REJECTED_BEFORE_APPLY,
      AIActionStatus.CONFIRMED_KEPT,
      AIActionStatus.CONFIRMED_REVERTED,
      AIActionStatus.EXECUTION_FAILED,
      AIActionStatus.REVERT_FAILED,
    ];
 
    const finalActions = lastInput.aiActions.filter((action: AIAction) =>
      finalStatuses.includes(action.status),
    );
 
    Iif (finalActions.length === 0) {
      return '';
    }
 
    return (
      'Summary of the results from your previous plan:\n' +
      finalActions
        .map(
          (action) =>
            `- For the action \`${action.action_type}\` on \`${
              action.file_path || action.command_string || 'N/A'
            }\`: ${formatActionStatusForLLM(action.status as AIActionStatus)}`,
        )
        .join('\n')
    );
  }
 
  /**
   * Generates the full context string for a given session input DTO WITHOUT
   * creating a SessionInput entity or triggering an LLM call.
   * This is useful for pre-validating context size before creating a follow-up.
   *
   * @param sessionId - The session ID to generate context for
   * @param createSessionInputDto - The input data to generate context from
   * @returns The generated context string
   */
  async generateContextString(
    sessionId: string,
    createSessionInputDto: CreateSessionInputDto,
  ): Promise<string> {
    const session = await this.sessionsRepository.findOne({
      where: { id: sessionId },
      relations: ['systemPrompt', 'sessionInputs', 'sessionInputs.aiActions'],
      order: {
        sessionInputs: {
          created_at: 'ASC',
        },
      },
    });
    Iif (!session) {
      throw new NotFoundException(`Session with ID "${sessionId}" not found`);
    }
 
    let contextTemplate: ContextTemplate | null = null;
    Iif (createSessionInputDto.context_template_id) {
      contextTemplate = await this.contextTemplatesRepository.findOneBy({
        id: createSessionInputDto.context_template_id,
      });
    }
 
    const previous_actions_summary =
      this.generatePreviousActionsSummary(session);
 
    const generated_context_string =
      await this.sessionInputContextService.generateContext(
        createSessionInputDto,
        contextTemplate,
        previous_actions_summary,
      );
 
    return generated_context_string;
  }
 
  async create(
    sessionId: string,
    createSessionInputDto: CreateSessionInputDto,
  ): Promise<SessionInput | null> {
    const isManualFlow =
      await this.applicationStateService.getManualLlmEnabled();
 
    // Check skip_persistence flag for native tool calling follow-ups
    Iif (createSessionInputDto.skip_persistence) {
      this.logger.log(
        `Triggering follow-up for session ${sessionId} without persistence.`,
      );
 
      // For follow-ups, use empty context or minimal prompt
      const generated_context_string = createSessionInputDto.user_prompt || '';
 
      // Trigger LLM call directly without creating SessionInput
      this.chatService
        .sendMessage(sessionId, generated_context_string, isManualFlow)
        .catch((err) => {
          this.logger.error(
            `LLM follow-up call failed for session ${sessionId}: ${err.message}`,
            err.stack,
          );
        });
 
      return null; // No SessionInput created
    }
 
    // Normal flow: Create SessionInput with persistence
    this.logger.log(
      `Creating new session input for session ${sessionId}. Manual flow: ${isManualFlow}`,
    );
 
    const session = await this.sessionsRepository.findOne({
      where: { id: sessionId },
      relations: ['systemPrompt', 'sessionInputs', 'sessionInputs.aiActions'],
      order: {
        sessionInputs: {
          created_at: 'ASC',
        },
      },
    });
    if (!session) {
      throw new NotFoundException(`Session with ID "${sessionId}" not found`);
    }
 
    let contextTemplate: ContextTemplate | null = null;
    Iif (createSessionInputDto.context_template_id) {
      contextTemplate = await this.contextTemplatesRepository.findOneBy({
        id: createSessionInputDto.context_template_id,
      });
    }
 
    const previous_actions_summary =
      this.generatePreviousActionsSummary(session);
 
    const generated_context_string =
      await this.sessionInputContextService.generateContext(
        createSessionInputDto,
        contextTemplate,
        previous_actions_summary,
      );
 
    const newSessionInputEntity = this.sessionInputsRepository.create({
      ...createSessionInputDto,
      session: { id: sessionId },
      contextTemplate: contextTemplate,
      generated_context_string: generated_context_string,
      raw_llm_response: null, // Always start with null
      role: 'user', // Explicitly set role for user-initiated turns
    });
 
    const savedSessionInput = await this.sessionInputsRepository.save(
      newSessionInputEntity,
    );
    await this.applicationStateService.setActiveSessionId(sessionId);
 
    // Trigger the appropriate flow. This is now a fire-and-forget background task.
    this.chatService
      .sendMessage(sessionId, generated_context_string, isManualFlow)
      .catch((err) => {
        this.logger.error(
          `LLM call failed for input ID ${savedSessionInput.id}: ${err.message}`,
          err.stack,
        );
      });
 
    return savedSessionInput;
  }
 
  async createFromRawLlmResponse(): Promise<SessionInput> {
    throw new Error(
      'This method is deprecated and its logic has moved to LlmResponsesService.',
    );
  }
 
  async findAllBySessionId(sessionId: string): Promise<SessionInput[]> {
    const session = await this.sessionsRepository.findOneBy({ id: sessionId });
    Iif (!session) {
      throw new NotFoundException(`Session with ID "${sessionId}" not found`);
    }
    return this.sessionInputsRepository.find({
      where: { session: { id: sessionId } },
      relations: ['contextTemplate', 'aiActions', 'aiActions.executionLogs'],
      order: {
        created_at: 'ASC',
        aiActions: {
          order_of_execution: 'ASC',
        },
      },
    });
  }
 
  async findOne(sessionId: string, inputId: string): Promise<SessionInput> {
    const sessionInput = await this.sessionInputsRepository.findOne({
      where: { id: inputId, session: { id: sessionId } },
      relations: ['contextTemplate', 'aiActions', 'aiActions.executionLogs'],
      order: {
        aiActions: {
          order_of_execution: 'ASC',
        },
      },
    });
 
    if (!sessionInput) {
      throw new NotFoundException(
        `SessionInput with ID "${inputId}" not found in Session "${sessionId}"`,
      );
    }
    return sessionInput;
  }
 
  async removeUntilHere(sessionId: string, inputId: string): Promise<void> {
    const session = await this.sessionsRepository.findOne({
      where: { id: sessionId },
      relations: ['sessionInputs', 'sessionInputs.aiActions'],
      order: {
        sessionInputs: {
          created_at: 'ASC',
        },
      },
    });
 
    Iif (!session) {
      throw new NotFoundException(`Session with ID "${sessionId}" not found`);
    }
 
    const targetIndex = session.sessionInputs.findIndex(
      (input) => input.id === inputId,
    );
    Iif (targetIndex === -1) {
      throw new NotFoundException(
        `SessionInput with ID "${inputId}" not found in Session "${sessionId}"`,
      );
    }
 
    const inputsToDelete = session.sessionInputs.slice(targetIndex + 1);
    Iif (inputsToDelete.length === 0) {
      this.logger.log(
        `No inputs after ${inputId} to delete in Session ${sessionId}.`,
      );
      return;
    }
 
    const idsToDelete = inputsToDelete.map((input) => input.id);
 
    // Delete all inputs after the selected one
    // Cascade delete will handle associated AI actions
    const deleteResult = await this.sessionInputsRepository.delete(idsToDelete);
 
    this.logger.log(
      `Deleted ${deleteResult.affected} SessionInputs (from ${idsToDelete[0]} onwards) from Session ${sessionId}.`,
    );
  }
 
  async remove(sessionId: string, inputId: string): Promise<void> {
    const sessionInput = await this.findOne(sessionId, inputId);
    await this.sessionInputsRepository.remove(sessionInput);
    this.logger.log(
      `Deleted SessionInput ${inputId} from Session ${sessionId}.`,
    );
  }
 
  async retry(
    sessionId: string,
    inputId: string,
    updateSessionInputDto: UpdateSessionInputDto,
  ): Promise<SessionInput> {
    this.logger.log(
      `Retrying SessionInput ${inputId} for Session ${sessionId}.`,
    );
 
    const sessionInput = await this.sessionInputsRepository.findOne({
      where: { id: inputId, session: { id: sessionId } },
      relations: ['session', 'session.systemPrompt'],
    });
 
    Iif (!sessionInput) {
      throw new NotFoundException(
        `SessionInput with ID "${inputId}" not found in Session "${sessionId}"`,
      );
    }
 
    // Update the prompt and optionally context template
    Iif (updateSessionInputDto.user_prompt) {
      sessionInput.user_prompt = updateSessionInputDto.user_prompt;
    }
 
    let contextTemplate: ContextTemplate | null = null;
    Iif (updateSessionInputDto.context_template_id) {
      contextTemplate = await this.contextTemplatesRepository.findOneBy({
        id: updateSessionInputDto.context_template_id,
      });
      sessionInput.contextTemplate = contextTemplate;
    }
 
    // Regenerate context string if prompt changed
    const generated_context_string =
      await this.sessionInputContextService.generateContext(
        {
          user_prompt: sessionInput.user_prompt,
          context_template_id:
            contextTemplate?.id || sessionInput.context_template_id,
          ad_hoc_context_definition:
            updateSessionInputDto.ad_hoc_context_definition ||
            sessionInput.ad_hoc_context_definition,
          execution_strategy:
            updateSessionInputDto.execution_strategy ||
            sessionInput.execution_strategy,
        },
        contextTemplate,
        '', // No previous actions summary on retry
      );
 
    // Reset LLM response fields
    sessionInput.generated_context_string = generated_context_string;
    sessionInput.raw_llm_response = null;
    sessionInput.llm_response_explanation = null;
    sessionInput.tool_calls = null;
    sessionInput.thoughts = null;
    sessionInput.error_message = null;
 
    // Update timestamps
    sessionInput.updated_at = new Date();
 
    // Save the updated input
    const updatedSessionInput =
      await this.sessionInputsRepository.save(sessionInput);
 
    // Clear any existing AI actions for this input
    await this.aiActionsService.deleteAllByInputId(inputId);
 
    // Trigger the LLM call again
    const isManualFlow =
      await this.applicationStateService.getManualLlmEnabled();
 
    this.chatService
      .sendMessage(sessionId, generated_context_string, isManualFlow)
      .catch((err) => {
        this.logger.error(
          `LLM retry failed for input ID ${updatedSessionInput.id}: ${err.message}`,
          err.stack,
        );
      });
 
    return this.findOne(sessionId, updatedSessionInput.id);
  }
 
  async regenerateAiResponse(
    sessionId: string,
    inputId: string,
  ): Promise<SessionInput> {
    this.logger.log(
      `Regenerating AI response for SessionInput ${inputId} in Session ${sessionId}.`,
    );
 
    const sessionInput = await this.sessionInputsRepository.findOne({
      where: { id: inputId, session: { id: sessionId } },
      relations: ['session'],
    });
 
    if (!sessionInput) {
      throw new NotFoundException(
        `SessionInput with ID "${inputId}" not found in Session "${sessionId}"`,
      );
    }
 
    // Find all inputs ordered by sequence_number
    const allInputs = await this.sessionInputsRepository.find({
      where: { session: { id: sessionId } },
      order: { sequence_number: 'ASC' },
    });
 
    const currentIndex = allInputs.findIndex(
      (input) => input.id === sessionInput.id,
    );
 
    Iif (currentIndex === -1) {
      throw new NotFoundException(
        `SessionInput ${inputId} not found in session inputs list.`,
      );
    }
 
    // Find the preceding user input that has generated_context_string
    let contextString: string | null = null;
    for (let i = currentIndex - 1; i >= 0; i--) {
      if (
        allInputs[i].role === 'user' &&
        allInputs[i].generated_context_string
      ) {
        contextString = allInputs[i].generated_context_string;
        break;
      }
    }
 
    if (!contextString) {
      throw new Error(
        `No preceding user input with generated_context_string found for SessionInput ${inputId}. Cannot regenerate.`,
      );
    }
 
    // Delete subsequent inputs if any exist
    const subsequentInputs = allInputs.slice(currentIndex + 1);
    if (subsequentInputs.length > 0) {
      const idsToDelete = subsequentInputs.map((input) => input.id);
      this.logger.log(
        `Deleting ${idsToDelete.length} subsequent inputs for regeneration.`,
      );
      await this.sessionInputsRepository.delete(idsToDelete);
    }
 
    // Delete all existing AI actions for this input
    await this.aiActionsService.deleteAllByInputId(inputId);
 
    // Clear AI response fields
    sessionInput.raw_llm_response = null;
    sessionInput.thoughts = null;
    sessionInput.tool_calls = null;
    sessionInput.llm_response_explanation = null;
    sessionInput.error_message = null;
    sessionInput.input_token_count = null;
    sessionInput.output_token_count = null;
    sessionInput.cached_token_count = null;
    await this.sessionInputsRepository.save(sessionInput);
 
    // Trigger the LLM call with the existing input ID
    const isManualFlow =
      await this.applicationStateService.getManualLlmEnabled();
 
    this.chatService
      .sendMessage(sessionId, contextString, isManualFlow, inputId)
      .catch((err) => {
        this.logger.error(
          `LLM regeneration failed for input ID ${inputId}: ${err.message}`,
          err.stack,
        );
      });
 
    return this.findOne(sessionId, inputId);
  }
 
  /**
   * Silent update of input content without triggering LLM regeneration.
   * Use for redacting sensitive data or compressing session history.
   */
  async updateContent(
    sessionId: string,
    inputId: string,
    updateDto: UpdateSessionInputContentDto,
  ): Promise<SessionInput> {
    this.logger.log(
      `Silent update of SessionInput ${inputId} in Session ${sessionId}.`,
    );
 
    const input = await this.findOne(sessionId, inputId);
 
    // Apply content updates
    if (updateDto.user_prompt !== undefined) {
      input.user_prompt = updateDto.user_prompt;
    }
    if (updateDto.raw_llm_response !== undefined) {
      input.raw_llm_response = updateDto.raw_llm_response;
    }
    Iif (updateDto.llm_response_explanation !== undefined) {
      input.llm_response_explanation = updateDto.llm_response_explanation;
    }
    if (updateDto.generated_context_string !== undefined) {
      input.generated_context_string = updateDto.generated_context_string;
    }
    if (updateDto.thoughts !== undefined) {
      input.thoughts = updateDto.thoughts;
    }
 
    // Save the updated input
    await this.sessionInputsRepository.save(input);
 
    // Update tool execution logs if provided
    if (updateDto.tool_results && updateDto.tool_results.length > 0) {
      await this.updateToolResults(inputId, updateDto.tool_results);
    }
 
    this.logger.log(`Silent update complete for SessionInput ${inputId}.`);
 
    return this.findOne(sessionId, inputId);
  }
 
  /**
   * Update tool execution log outputs for redaction purposes.
   */
  private async updateToolResults(
    inputId: string,
    toolResults: { tool_call_id: string; output: string }[],
  ): Promise<void> {
    for (const tr of toolResults) {
      // Find AIAction by tool_call_id
      const action = await this.aiActionsRepository.findOne({
        where: { input_id: inputId, tool_call_id: tr.tool_call_id },
        relations: ['executionLogs'],
      });
 
      if (action && action.executionLogs && action.executionLogs.length > 0) {
        // Update the first execution log's output
        action.executionLogs[0].output = tr.output;
        await this.executionLogsRepository.save(action.executionLogs[0]);
        this.logger.log(
          `Updated execution log for tool_call_id ${tr.tool_call_id}`,
        );
      } else {
        this.logger.warn(
          `No execution log found for tool_call_id ${tr.tool_call_id} in input ${inputId}`,
        );
      }
    }
  }
 
  /**
   * Batch toggle is_discarded flag for multiple inputs.
   * Used to exclude/include inputs from LLM context.
   */
  async toggleDiscardedBatch(
    sessionId: string,
    dto: BatchToggleDiscardedDto,
  ): Promise<{ affected: number }> {
    // Verify all inputs belong to the session
    const inputs = await this.sessionInputsRepository.find({
      where: { id: In(dto.input_ids), session: { id: sessionId } },
    });
 
    if (inputs.length === 0) {
      throw new NotFoundException(
        `No inputs found with provided IDs in session ${sessionId}`,
      );
    }
 
    // Update is_discarded flag
    const updateResult = await this.sessionInputsRepository.update(
      { id: In(inputs.map((i) => i.id)) },
      { is_discarded: dto.is_discarded },
    );
 
    this.logger.log(
      `Toggled is_discarded=${dto.is_discarded} for ${updateResult.affected} inputs in session ${sessionId}`,
    );
 
    return { affected: updateResult.affected || 0 };
  }
}