All files / src/views/components WorkItemSubtasksModal.js

100% Statements 629/629
100% Branches 191/191
100% Functions 21/21
100% Lines 629/629

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 63043x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 16x 16x 16x 16x 1x 1x 15x 15x 11x 11x 11x 11x 15x 15x 11x 11x 11x 11x 16x 43x 43x 43x 43x 43x 43x 43x 6x 6x 6x 1x 1x 6x 6x 1x 1x 6x 6x 2x 1x 6x 6x 1x 1x 6x 6x 1x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 43x 43x 7x 7x 7x 7x 7x 7x 6x 7x 1x 1x 6x 7x 2x 2x 4x 4x 7x 7x 2x 7x 2x 2x 2x 7x 1x 1x 1x 1x 7x 43x 43x 7x 7x 1x 7x 1x 7x 2x 7x 1x 7x 2x 7x 7x 43x 43x 10x 3x 3x 7x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 4x 4x 4x 4x 4x 4x 4x 7x 10x 10x 10x 10x 10x 10x 43x 43x 5x 1x 1x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 4x 4x 5x 43x 43x 3x 3x 3x 3x 3x 1x 1x 3x 1x 1x 3x 1x 3x 3x 43x 43x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 1x 1x 2x 2x 2x 2x 2x 4x 43x 43x 1x 1x 1x 1x 1x 1x 43x 43x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 43x 43x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 43x 43x 4x 4x 4x 4x 4x 3x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 4x 43x 43x 9x 9x 2x 2x 7x 7x 7x 7x 7x 7x 8x 2x 2x 2x 1x 1x 2x 7x 7x 7x 8x 1x 8x 5x 5x 7x 8x 1x 1x 7x 7x 7x 7x 7x 7x 7x 13x 13x 1x 1x 12x 12x 7x 9x 43x 43x 8x 8x 1x 1x 7x 7x 8x 43x 43x 1x 1x 1x 1x 1x 43x 43x 7x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 43x 43x 12x 12x 12x 12x 2x 2x 10x 10x 10x 9x 70x 9x 9x 12x 12x 12x 2x 2x 8x 10x 1x 1x 7x 7x 7x 7x 7x 1x 1x 6x 6x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 8x 8x 8x 4x 4x 4x 4x 4x 4x 4x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 12x 3x 3x 3x 3x 1x 1x 1x 3x 2x 2x 2x 2x 2x 12x 43x 43x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 4x 43x 43x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 4x 1x 1x 3x 4x 1x 1x 2x 2x 1x 1x 1x 1x 8x 43x 43x 1x 1x 1x 1x 43x 43x 43x  
/**
 * Componente backend para manejar el modal de subtareas base
 */
 
const vscode = require("vscode");
const path = require("path");
const fs = require("fs").promises;
const { jsonrepair } = require("jsonrepair");
const WorkItemService = require("../../api/workItemService");
const { AzureDevOpsService } = require("../../api/azureDevOps");
 
class WorkItemSubtasksModal {
  /**
   * @param {vscode.Webview} webview
   * @param {Object} config
   * @param {Object} logger
   */
  constructor(webview, config, logger) {
    this.webview = webview;
    this.config = config;
    this.logger = logger;
 
    this.workItemService = null;
    this.azureService = null;
    const docsConfig = vscode.workspace.getConfiguration("gbotDocs");
    const maxSubtasks = Number(docsConfig.get("subtasks.maxSubtasks", 50));
    this._maxSubtasks =
      Number.isFinite(maxSubtasks) && maxSubtasks > 0 ? maxSubtasks : 50;
    this._maxErrorLength = 500;
 
    this.logger.info("WorkItemSubtasksModal inicializado");
  }
 
  _initServices() {
    const organization = this.config.azure?.organization;
    const pat = this.config.azure?.pat;
 
    if (!organization || !pat) {
      throw new Error("Configuracion de Azure Boards incompleta");
    }
 
    if (!this.workItemService) {
      this.workItemService = new WorkItemService(organization, pat, (msg) =>
        this.logger.info(msg),
      );
    }
 
    if (!this.azureService) {
      this.azureService = new AzureDevOpsService(organization, pat, (msg) =>
        this.logger.info(msg),
      );
    }
  }
 
  /**
   * Manejar mensajes desde el webview
   * @param {Object} message
   * @returns {Promise<boolean>}
   */
  async handleMessage(message) {
    try {
      switch (message.command) {
        case "loadSubtaskTemplate":
          await this.loadTemplate();
          return true;
 
        case "suggestSubtasks":
          await this.suggestSubtasks(message.workItemId);
          return true;
 
        case "createSubtasks":
          await this.createSubtasks(message.workItemId, message.tasks);
          return true;
 
        case "logSubtasksMessage":
          this._handleWebviewLog(message.level, message.message, message.data);
          return true;
 
        default:
          return false;
      }
    } catch (error) {
      const detailedError = this._formatAzureError(error);
      const errorType = this._classifyError(error);
      const userMessage = this._getFriendlyMessage(
        detailedError || error,
        errorType,
      );
      const sanitizedMessage = this._sanitizeErrorMessage(userMessage);
 
      this.logger.error(
        `Error en WorkItemSubtasksModal.handleMessage [${errorType}]: ${detailedError || error.message}`,
      );
 
      this.webview.postMessage({
        command: "subtasksError",
        error: sanitizedMessage,
        errorType,
      });
      return true;
    }
  }
 
  _classifyError(error) {
    const message = error.message || "";
    const code = error.code || "";
 
    if (
      code === "ECONNREFUSED" ||
      code === "ETIMEDOUT" ||
      code === "ENOTFOUND"
    ) {
      return "network";
    }
 
    if (error.response?.status === 401 || error.response?.status === 403) {
      return "auth";
    }
 
    if (
      message.toLowerCase().includes("invalido") ||
      message.toLowerCase().includes("no encontrado") ||
      message.toLowerCase().includes("configuracion")
    ) {
      return "validation";
    }
 
    if (code === "EACCES" || code === "EPERM") {
      return "permission";
    }
 
    return "unknown";
  }
 
  _getFriendlyMessage(error, errorType) {
    switch (errorType) {
      case "network":
        return "Error de conexion. Verifica tu red o Azure DevOps.";
      case "auth":
        return "Error de autenticacion. Verifica el PAT de Azure Boards.";
      case "validation":
        return error.message;
      case "permission":
        return "Error de permisos. Verifica acceso a archivos.";
      default:
        return `Error inesperado: ${error.message || error}`;
    }
  }
 
  _formatAzureError(error) {
    if (!error || !error.response) {
      return "";
    }
 
    const status = error.response?.status;
    const statusText = error.response?.statusText;
    const data = error.response?.data;
    const message =
      data?.message ||
      data?.error?.message ||
      error.message ||
      "Error desconocido";
 
    let details = "";
    if (data?.errors && typeof data.errors === "object") {
      const entries = Object.entries(data.errors)
        .map(([field, fieldError]) => `${field}: ${fieldError}`)
        .join("; ");
      if (entries) {
        details = ` (${entries})`;
      }
    }
 
    const statusLabel = status ? `HTTP ${status}` : "";
    const statusSuffix = statusText ? ` ${statusText}` : "";
    const prefix = statusLabel ? `${statusLabel}${statusSuffix}: ` : "";
 
    return `${prefix}${message}${details}`;
  }
 
  _sanitizeErrorMessage(errorMessage) {
    if (!errorMessage || typeof errorMessage !== "string") {
      return "Error desconocido";
    }
 
    let sanitized = errorMessage;
    const maxErrorLength =
      Number.isFinite(this._maxErrorLength) && this._maxErrorLength > 0
        ? this._maxErrorLength
        : 500;
 
    sanitized = sanitized.replace(/[a-z0-9]{20,}/gi, "[TOKEN]");
    sanitized = sanitized.replace(/[A-Z]{2,}\\[\w\-\.]+/g, "[DOMAIN\\USER]");
    sanitized = sanitized.replace(
      /[\w\-\.]+@[\w\-\.]+\.[a-z]{2,}/gi,
      "[EMAIL]",
    );
    sanitized = sanitized.replace(
      /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
      "[IP]",
    );
    sanitized = sanitized.replace(
      /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
      "[GUID]",
    );
    sanitized = sanitized.replace(/\{[^}]{20,}\}/g, "[JSON]");
    sanitized = sanitized.replace(/[?&][\w-]+=[^&\s]+/g, "?[PARAM]");
    sanitized = sanitized.replace(/[A-Z]:\\[\\\w\s\-\.()]+/gi, "[PATH]");
    sanitized = sanitized.replace(
      /\\\\[\w\-\.]+\\[\\\w\s\-\.()]+/gi,
      "[UNC_PATH]",
    );
    sanitized = sanitized.replace(/\/[\w\-\.\/~]+/g, "[PATH]");
 
    if (sanitized.length > maxErrorLength) {
      sanitized = `${sanitized.substring(0, maxErrorLength)}...[TRUNCADO]`;
    }
 
    return sanitized;
  }
 
  _handleWebviewLog(level, message, data) {
    const payload = data ? ` ${JSON.stringify(data)}` : "";
    const logMessage = `[Subtasks Modal] ${message}${payload}`;
 
    switch (level) {
      case "warn":
        this.logger.warn(logMessage);
        break;
      case "error":
        this.logger.error(logMessage);
        break;
      default:
        this.logger.info(logMessage);
    }
  }
 
  async suggestSubtasks(workItemId) {
    this._initServices();
 
    const normalizedId = Number(workItemId);
    if (!Number.isFinite(normalizedId)) {
      throw new Error("Work item ID invalido");
    }
 
    const summary = await this.workItemService.getWorkItemSummary(normalizedId);
    const docsConfig = vscode.workspace.getConfiguration("gbotDocs");
    const config = vscode.workspace.getConfiguration("gbot");
 
    const suggestedCountRaw = Number(
      docsConfig.get("subtasks.suggestedCount", 6),
    );
    const suggestedCount = Number.isFinite(suggestedCountRaw)
      ? Math.max(1, Math.min(12, Math.floor(suggestedCountRaw)))
      : 6;
 
    const description = this._normalizeHtmlToText(summary.description);
    const acceptance = this._normalizeHtmlToText(summary.acceptanceCriteria);
 
    const prompt = this._buildSubtasksPrompt({
      title: summary.title,
      workItemType: summary.workItemType,
      description,
      acceptance,
      suggestedCount,
    });
 
    const preferredModel = config.get("prReview.aiModel");
    const suggestions = await this._requestCopilotSuggestions(
      prompt,
      preferredModel,
    );
 
    if (!suggestions.length) {
      throw new Error("Copilot no devolvio sugerencias");
    }
 
    this.webview.postMessage({
      command: "subtasksSuggested",
      tasks: suggestions,
    });
  }
 
  async loadTemplate() {
    const template = await this._loadTemplate();
    this.webview.postMessage({
      command: "subtaskTemplateLoaded",
      tasks: template,
    });
  }
 
  _buildSubtasksPrompt({
    title,
    workItemType,
    description,
    acceptance,
    suggestedCount,
  }) {
    const safeTitle = title || "(sin titulo)";
    const safeType = workItemType || "Work Item";
    const safeDescription = description || "(sin descripcion)";
    const safeAcceptance = acceptance || "(sin criterios)";
 
    return `Eres un asistente de desarrollo. Con base en la informacion del work item, sugiere ${suggestedCount} subtareas tecnicas accionables.
 
REGLAS:
- Usa verbos en infinitivo (ej: Analizar, Implementar).
- Cada subtarea debe ser concreta y breve (max 80 caracteres).
- Evita repetir el titulo del work item.
- Devuelve SOLO JSON con este formato: {"tasks":[{"title":"..."}]}
 
WORK ITEM:
Tipo: ${safeType}
Titulo: ${safeTitle}
Descripcion: ${safeDescription}
Criterios de aceptacion: ${safeAcceptance}`;
  }
 
  async _requestCopilotSuggestions(prompt, preferredModel) {
    const models = await this._selectCopilotModels(preferredModel);
    if (!models.length) {
      throw new Error("GitHub Copilot no esta disponible");
    }
 
    const model = models[0];
    const messages = [vscode.LanguageModelChatMessage.User(prompt)];
    const response = await model.sendRequest(
      messages,
      {},
      new vscode.CancellationTokenSource().token,
    );
 
    let fullResponse = "";
    for await (const fragment of response.text) {
      fullResponse += fragment;
    }
 
    return this._parseSuggestedTasks(fullResponse);
  }
 
  async _selectCopilotModels(preferredModel) {
    try {
      if (preferredModel) {
        const byFamily = await vscode.lm.selectChatModels({
          family: preferredModel,
        });
        if (byFamily.length > 0) {
          return byFamily;
        }
      }
 
      return await vscode.lm.selectChatModels({ vendor: "copilot" });
    } catch (error) {
      this.logger.warn(
        `No se pudo seleccionar modelo Copilot: ${error.message}`,
      );
      return [];
    }
  }
 
  _parseSuggestedTasks(responseText) {
    const text = String(responseText || "").trim();
    if (!text) {
      return [];
    }
 
    const jsonBlock = this._extractJsonBlock(text);
    let parsed = null;
 
    try {
      parsed = JSON.parse(jsonBlock);
    } catch {
      try {
        parsed = JSON.parse(jsonrepair(jsonBlock));
      } catch {
        parsed = null;
      }
    }
 
    let tasks = [];
 
    if (Array.isArray(parsed)) {
      tasks = parsed;
    } else if (Array.isArray(parsed?.tasks)) {
      tasks = parsed.tasks;
    }
 
    if (tasks.length === 0) {
      tasks = this._parseLinesAsTasks(text);
    }
 
    const seen = new Set();
    return tasks
      .map((task) => (typeof task === "string" ? task : task?.title))
      .map((title) => String(title || "").trim())
      .filter((title) => title.length > 0)
      .filter((title) => {
        const normalized = title.toLowerCase();
        if (seen.has(normalized)) {
          return false;
        }
        seen.add(normalized);
        return true;
      });
  }
 
  _extractJsonBlock(text) {
    const fence = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
    if (fence && fence[1]) {
      return fence[1].trim();
    }
 
    return text.trim();
  }
 
  _parseLinesAsTasks(text) {
    return text
      .split("\n")
      .map((line) => line.replace(/^[\s\-*\d.()]+/, "").trim())
      .filter((line) => line.length > 0);
  }
 
  _normalizeHtmlToText(html) {
    if (!html || typeof html !== "string") {
      return "";
    }
 
    let text = html;
    text = text.replace(/<br\s*\/?>/gi, "\n");
    text = text.replace(/<\/?p>/gi, "\n");
    text = text.replace(/<\/?div>/gi, "\n");
    text = text.replace(/<li>/gi, "- ");
    text = text.replace(/<\/li>/gi, "\n");
    text = text.replace(/<[^>]+>/g, "");
    text = text.replace(/&nbsp;/gi, " ");
    text = text.replace(/&amp;/gi, "&");
    text = text.replace(/&lt;/gi, "<");
    text = text.replace(/&gt;/gi, ">");
    text = text.replace(/&quot;/gi, '"');
    text = text.replace(/&#39;/gi, "'");
    text = text.replace(/\n{3,}/g, "\n\n");
    return text.trim();
  }
 
  async createSubtasks(workItemId, tasks) {
    this._initServices();
 
    const normalizedId = Number(workItemId);
    if (!Number.isFinite(normalizedId)) {
      throw new Error("Work item ID invalido");
    }
 
    const normalizedTasks = Array.isArray(tasks)
      ? tasks
          .map((task) => ({
            title: String(task?.title || "").trim(),
          }))
          .filter((task) => task.title.length > 0)
      : [];
 
    if (normalizedTasks.length === 0) {
      throw new Error("No hay subtareas para crear");
    }
 
    if (normalizedTasks.length > this._maxSubtasks) {
      throw new Error(`Maximo ${this._maxSubtasks} subtareas por ejecucion`);
    }
 
    const parentSummary =
      await this.workItemService.getWorkItemSummary(normalizedId);
 
    if (!parentSummary.project) {
      throw new Error("No se pudo determinar el proyecto del work item");
    }
 
    const docsConfig = vscode.workspace.getConfiguration("gbotDocs");
    const taskType = docsConfig.get("subtasks.taskType") || "Sub task";
 
    const relation = {
      rel: "System.LinkTypes.Hierarchy-Reverse",
      url: `https://dev.azure.com/${this.config.azure?.organization}/_apis/wit/workItems/${normalizedId}`,
      attributes: {
        comment: "Generado por G-Bot",
      },
    };
 
    const results = [];
 
    for (const task of normalizedTasks) {
      try {
        const fields = {
          "System.Title": task.title,
        };
 
        if (parentSummary.areaPath) {
          fields["System.AreaPath"] = parentSummary.areaPath;
        }
 
        if (parentSummary.iterationPath) {
          fields["System.IterationPath"] = parentSummary.iterationPath;
        }
 
        const created = await this.azureService.createWorkItem({
          organization: this.config.azure?.organization,
          project: parentSummary.project,
          pat: this.config.azure?.pat,
          workItemType: taskType,
          fields,
          relations: [relation],
        });
 
        results.push({
          title: task.title,
          success: true,
          id: created?.id,
        });
      } catch (error) {
        const detailedError = this._formatAzureError(error) || error.message;
        results.push({
          title: task.title,
          success: false,
          error: detailedError,
        });
      }
    }
 
    const successCount = results.filter((r) => r.success).length;
    const failCount = results.filter((r) => !r.success).length;
    const errorItems = results.filter((r) => !r.success);
    const errorSummary = errorItems
      .slice(0, 3)
      .map((item) => `${item.title}: ${item.error}`)
      .join("\n");
 
    if (errorItems.length > 0) {
      const logDetails = errorItems
        .map((item) => `${item.title}: ${item.error}`)
        .join(" | ");
      this.logger.warn(`Subtareas con errores: ${logDetails}`);
    }
 
    this.webview.postMessage({
      command: "subtasksCreationComplete",
      results,
      errorSummary,
      errorCount: errorItems.length,
    });
 
    if (successCount > 0 && failCount === 0) {
      vscode.window.showInformationMessage(
        `Subtareas creadas: ${successCount}`,
      );
    } else if (successCount > 0) {
      vscode.window.showWarningMessage(
        `Subtareas creadas: ${successCount}. Fallos: ${failCount}.`,
      );
    } else {
      const errorMessage = errorSummary
        ? `No se pudieron crear subtareas. ${errorSummary}`
        : "No se pudieron crear subtareas.";
      vscode.window.showErrorMessage(errorMessage);
    }
  }
 
  async _loadTemplate() {
    const docsConfig = vscode.workspace.getConfiguration("gbotDocs");
    const templatePath = docsConfig.get("subtasks.templatePath");
 
    const resolvedPath = await this._resolveTemplatePath(
      templatePath,
      "subtasks-template.json",
    );
 
    try {
      const raw = await fs.readFile(resolvedPath, "utf-8");
      const parsed = JSON.parse(raw);
      const tasks = Array.isArray(parsed?.tasks) ? parsed.tasks : [];
 
      return tasks
        .map((task) => ({ title: String(task?.title || "").trim() }))
        .filter((task) => task.title.length > 0);
    } catch (error) {
      this.logger.warn(
        `No se pudo leer plantilla de subtareas en ${resolvedPath}: ${error.message}`,
      );
      return [];
    }
  }
 
  async _resolveTemplatePath(overridePath, defaultFileName) {
    const workspaceFolder = vscode.workspace.workspaceFolders?.[0]?.uri?.fsPath;
    const defaultPath = path.join(
      __dirname,
      "..",
      "..",
      "..",
      "resources",
      "templates",
      defaultFileName,
    );
 
    if (!overridePath || typeof overridePath !== "string") {
      return defaultPath;
    }
 
    const trimmed = overridePath.trim();
    if (!trimmed) {
      return defaultPath;
    }
 
    if (path.isAbsolute(trimmed)) {
      return trimmed;
    }
 
    if (workspaceFolder) {
      return path.join(workspaceFolder, trimmed);
    }
 
    return defaultPath;
  }
 
  dispose() {
    this.logger.info("WorkItemSubtasksModal recursos liberados");
    this.workItemService = null;
    this.azureService = null;
  }
}
 
module.exports = WorkItemSubtasksModal;