// @bun
import {
  REPL
} from "./chunk-ta9fp00v.js";
import"./chunk-7t1gvk94.js";
import"./chunk-m1ynb215.js";
import"./chunk-gf4s7x9e.js";
import {
  computeStandaloneAgentContext,
  restoreAgentFromSession,
  restoreWorktreeForResume
} from "./chunk-bw4t6xdw.js";
import"./chunk-290yf5d7.js";
import"./chunk-yamvt0nc.js";
import"./chunk-qdvpweej.js";
import"./chunk-nt837qt9.js";
import"./chunk-3k5aw9my.js";
import {
  renameRecordingForSession
} from "./chunk-gax0fcbx.js";
import"./chunk-wgjsgesk.js";
import"./chunk-1xb29bj2.js";
import"./chunk-6n2qgm9v.js";
import"./chunk-rb60k93s.js";
import"./chunk-1c85kqam.js";
import"./chunk-rvya67xq.js";
import"./chunk-sxbvkahe.js";
import"./chunk-12gc4czk.js";
import"./chunk-z6h0zkry.js";
import"./chunk-2saax0a0.js";
import"./chunk-np4cwdq0.js";
import"./chunk-0paqc2yw.js";
import"./chunk-8gs5fbep.js";
import"./chunk-8t8g8weh.js";
import {
  LogSelector,
  agenticSessionSearch,
  checkCrossProjectResume,
  init_LogSelector,
  init_agenticSessionSearch,
  init_crossProjectResume
} from "./chunk-9xzeb5x5.js";
import"./chunk-hmq8gdbm.js";
import"./chunk-6ka4v634.js";
import"./chunk-28wmj447.js";
import"./chunk-z4jcxmjx.js";
import"./chunk-jdgeec04.js";
import"./chunk-p2qtwree.js";
import"./chunk-rwxpnjsp.js";
import"./chunk-1bxtw3y9.js";
import"./chunk-tvqcgtt2.js";
import"./chunk-66grbekh.js";
import"./chunk-51qa3ab2.js";
import"./chunk-gw5kc2z4.js";
import"./chunk-w0hap6vh.js";
import"./chunk-9d6x9q10.js";
import"./chunk-qvzm7cw3.js";
import"./chunk-c19jtczt.js";
import"./chunk-5p4vedse.js";
import"./chunk-c8h915h4.js";
import"./chunk-pdthz94y.js";
import"./chunk-37kh1q69.js";
import"./chunk-qpkbabgh.js";
import"./chunk-r2t7g2bs.js";
import"./chunk-p0zewybt.js";
import"./chunk-bbd7p8xa.js";
import"./chunk-kpbexwea.js";
import"./chunk-w7wgpqcp.js";
import"./chunk-gsrjky8f.js";
import"./chunk-pzta8ec9.js";
import"./chunk-b69wcsqs.js";
import"./chunk-d71np54x.js";
import"./chunk-zf0dzt34.js";
import"./chunk-ht263vdy.js";
import"./chunk-5m4rsqh3.js";
import"./chunk-rn0v1hk8.js";
import"./chunk-gyj242zr.js";
import {
  Spinner,
  adoptResumedSessionFile,
  asSessionId,
  enrichLogs,
  init_AppState,
  init_Spinner,
  init_concurrentSessions,
  init_conversationRecovery,
  init_cost_tracker,
  init_ids,
  init_messages1 as init_messages,
  init_sessionStorage,
  isCustomTitleEnabled,
  loadAllProjectsMessageLogsProgressive,
  loadConversationForResume,
  loadSameRepoMessageLogsProgressive,
  recordContentReplacement,
  resetSessionFilePointer,
  restoreCostStateForSession,
  restoreSessionMetadata,
  updateSessionName,
  useAppState,
  useSetAppState
} from "./chunk-hvqy1k5w.js";
import"./chunk-we4qy8ww.js";
import"./chunk-t0rgmccj.js";
import"./chunk-de3pfca9.js";
import"./chunk-aqfmmd15.js";
import"./chunk-tcejyzdv.js";
import"./chunk-sjjt8hmh.js";
import"./chunk-nreqc7d7.js";
import"./chunk-ehtwnxpg.js";
import"./chunk-3be7ka25.js";
import"./chunk-q122shkg.js";
import"./chunk-2gzv8nrw.js";
import"./chunk-45kxdsp8.js";
import"./chunk-cgfdkzhb.js";
import"./chunk-bs8c7dnf.js";
import"./chunk-0trrfws6.js";
import"./chunk-9gbamk79.js";
import"./chunk-zvkx2maf.js";
import"./chunk-hfzj1m07.js";
import {
  init_useKeybinding,
  init_useTerminalSize,
  useKeybinding,
  useTerminalSize
} from "./chunk-363qkd03.js";
import {
  ThemedBox_default,
  ThemedText,
  init_ink,
  init_osc,
  require_compiler_runtime,
  setClipboard
} from "./chunk-6dnv27tk.js";
import"./chunk-7m2nd8da.js";
import"./chunk-ps49ymvj.js";
import {
  require_jsx_dev_runtime,
  require_react
} from "./chunk-g338npwr.js";
import"./chunk-wvafkvfd.js";
import"./chunk-zk2wsm7d.js";
import"./chunk-7h9kdcw6.js";
import"./chunk-m06q12hg.js";
import"./chunk-rrvve2kk.js";
import"./chunk-rcmestmq.js";
import"./chunk-e3g8q4cn.js";
import"./chunk-ctw5jwcd.js";
import"./chunk-vratq94g.js";
import"./chunk-rvqtbt9h.js";
import"./chunk-0e1xsncc.js";
import"./chunk-g0j0t6qk.js";
import"./chunk-3c25bcsw.js";
import"./chunk-tjaqa99q.js";
import"./chunk-55wgxwa9.js";
import"./chunk-spqaamnc.js";
import"./chunk-4jm600zv.js";
import"./chunk-w2z5pqd3.js";
import"./chunk-7ymfj7m3.js";
import"./chunk-f5ma3nh5.js";
import"./chunk-qz2x630m.js";
import"./chunk-cvge4pvp.js";
import"./chunk-p2816w9z.js";
import"./chunk-v9smspw2.js";
import"./chunk-v1kzp02e.js";
import"./chunk-0vkfrmqm.js";
import"./chunk-0xjaqda8.js";
import"./chunk-x14dq3v1.js";
import"./chunk-cdz5yb0r.js";
import {
  init_analytics,
  logEvent
} from "./chunk-h0rbjg6x.js";
import"./chunk-7z8j9qfn.js";
import"./chunk-hrzerbfw.js";
import"./chunk-d18z9pna.js";
import"./chunk-qnfx3qtx.js";
import"./chunk-hjhc4cpt.js";
import"./chunk-vyc0rjyx.js";
import"./chunk-hx2tr4ep.js";
import {
  init_log,
  logError
} from "./chunk-p7g7pf3f.js";
import"./chunk-8tnsngw2.js";
import"./chunk-8bedvdm1.js";
import"./chunk-7wm5s02e.js";
import"./chunk-nxsh6de2.js";
import"./chunk-fbv4apne.js";
import"./chunk-3r24h7t6.js";
import {
  init_state,
  switchSession
} from "./chunk-qqfa0dqg.js";
import"./chunk-hqmz36b3.js";
import"./chunk-4g3v8y12.js";
import"./chunk-7739pg2c.js";
import"./chunk-xszk7n10.js";
import"./chunk-sdj9b9wh.js";
import {
  __toESM
} from "./chunk-qp2qdcda.js";

// src/screens/ResumeConversation.tsx
init_useTerminalSize();
init_state();
init_LogSelector();
init_Spinner();
init_cost_tracker();
init_osc();
init_ink();
init_useKeybinding();
init_analytics();
init_AppState();
init_ids();
init_agenticSessionSearch();
var import_compiler_runtime = __toESM(require_compiler_runtime(), 1);
var import_react = __toESM(require_react(), 1);
import { dirname } from "path";
init_concurrentSessions();
init_conversationRecovery();
init_crossProjectResume();
init_log();
init_messages();
init_sessionStorage();
var jsx_dev_runtime = __toESM(require_jsx_dev_runtime(), 1);
function parsePrIdentifier(value) {
  const directNumber = parseInt(value, 10);
  if (!isNaN(directNumber) && directNumber > 0) {
    return directNumber;
  }
  const urlMatch = value.match(/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/);
  if (urlMatch?.[1]) {
    return parseInt(urlMatch[1], 10);
  }
  return null;
}
function ResumeConversation({
  commands,
  worktreePaths,
  initialTools,
  mcpClients,
  dynamicMcpConfig,
  debug,
  mainThreadAgentDefinition,
  autoConnectIdeFlag,
  strictMcpConfig = false,
  systemPrompt,
  appendSystemPrompt,
  initialSearchQuery,
  disableSlashCommands = false,
  forkSession,
  taskListId,
  filterByPr,
  thinkingConfig,
  onTurnComplete
}) {
  const {
    rows
  } = useTerminalSize();
  const agentDefinitions = useAppState((s) => s.agentDefinitions);
  const setAppState = useSetAppState();
  const [logs, setLogs] = import_react.default.useState([]);
  const [loading, setLoading] = import_react.default.useState(true);
  const [resuming, setResuming] = import_react.default.useState(false);
  const [showAllProjects, setShowAllProjects] = import_react.default.useState(false);
  const [resumeData, setResumeData] = import_react.default.useState(null);
  const [crossProjectCommand, setCrossProjectCommand] = import_react.default.useState(null);
  const sessionLogResultRef = import_react.default.useRef(null);
  const logCountRef = import_react.default.useRef(0);
  const filteredLogs = import_react.default.useMemo(() => {
    let result = logs.filter((l) => !l.isSidechain);
    if (filterByPr !== undefined) {
      if (filterByPr === true) {
        result = result.filter((l_0) => l_0.prNumber !== undefined);
      } else if (typeof filterByPr === "number") {
        result = result.filter((l_1) => l_1.prNumber === filterByPr);
      } else if (typeof filterByPr === "string") {
        const prNumber = parsePrIdentifier(filterByPr);
        if (prNumber !== null) {
          result = result.filter((l_2) => l_2.prNumber === prNumber);
        }
      }
    }
    return result;
  }, [logs, filterByPr]);
  const isResumeWithRenameEnabled = isCustomTitleEnabled();
  import_react.default.useEffect(() => {
    loadSameRepoMessageLogsProgressive(worktreePaths).then((result_0) => {
      sessionLogResultRef.current = result_0;
      logCountRef.current = result_0.logs.length;
      setLogs(result_0.logs);
      setLoading(false);
    }).catch((error) => {
      logError(error);
      setLoading(false);
    });
  }, [worktreePaths]);
  const loadMoreLogs = import_react.default.useCallback((count) => {
    const ref = sessionLogResultRef.current;
    if (!ref || ref.nextIndex >= ref.allStatLogs.length)
      return;
    enrichLogs(ref.allStatLogs, ref.nextIndex, count).then((result_1) => {
      ref.nextIndex = result_1.nextIndex;
      if (result_1.logs.length > 0) {
        const offset = logCountRef.current;
        result_1.logs.forEach((log, i) => {
          log.value = offset + i;
        });
        setLogs((prev) => prev.concat(result_1.logs));
        logCountRef.current += result_1.logs.length;
      } else if (ref.nextIndex < ref.allStatLogs.length) {
        loadMoreLogs(count);
      }
    });
  }, []);
  const loadLogs = import_react.default.useCallback((allProjects) => {
    setLoading(true);
    const promise = allProjects ? loadAllProjectsMessageLogsProgressive() : loadSameRepoMessageLogsProgressive(worktreePaths);
    promise.then((result_2) => {
      sessionLogResultRef.current = result_2;
      logCountRef.current = result_2.logs.length;
      setLogs(result_2.logs);
    }).catch((error_0) => {
      logError(error_0);
    }).finally(() => {
      setLoading(false);
    });
  }, [worktreePaths]);
  const handleToggleAllProjects = import_react.default.useCallback(() => {
    const newValue = !showAllProjects;
    setShowAllProjects(newValue);
    loadLogs(newValue);
  }, [showAllProjects, loadLogs]);
  function onCancel() {
    process.exit(1);
  }
  async function onSelect(log_0) {
    setResuming(true);
    const resumeStart = performance.now();
    const crossProjectCheck = checkCrossProjectResume(log_0, showAllProjects, worktreePaths);
    if (crossProjectCheck.isCrossProject) {
      if (!crossProjectCheck.isSameRepoWorktree) {
        const raw = await setClipboard(crossProjectCheck.command);
        if (raw)
          process.stdout.write(raw);
        setCrossProjectCommand(crossProjectCheck.command);
        return;
      }
    }
    try {
      const result_3 = await loadConversationForResume(log_0, undefined);
      if (!result_3) {
        throw new Error("Failed to load conversation");
      }
      if (false) {}
      if (result_3.sessionId && !forkSession) {
        switchSession(asSessionId(result_3.sessionId), log_0.fullPath ? dirname(log_0.fullPath) : null);
        await renameRecordingForSession();
        await resetSessionFilePointer();
        restoreCostStateForSession(result_3.sessionId);
      } else if (forkSession && result_3.contentReplacements?.length) {
        await recordContentReplacement(result_3.contentReplacements);
      }
      const {
        agentDefinition: resolvedAgentDef
      } = restoreAgentFromSession(result_3.agentSetting, mainThreadAgentDefinition, agentDefinitions);
      setAppState((prev_1) => ({
        ...prev_1,
        agent: resolvedAgentDef?.agentType
      }));
      if (false) {}
      const standaloneAgentContext = computeStandaloneAgentContext(result_3.agentName, result_3.agentColor);
      if (standaloneAgentContext) {
        setAppState((prev_2) => ({
          ...prev_2,
          standaloneAgentContext
        }));
      }
      updateSessionName(result_3.agentName);
      restoreSessionMetadata(forkSession ? {
        ...result_3,
        worktreeSession: undefined
      } : result_3);
      if (!forkSession) {
        restoreWorktreeForResume(result_3.worktreeSession);
        if (result_3.sessionId) {
          adoptResumedSessionFile();
        }
      }
      if (false) {}
      logEvent("tengu_session_resumed", {
        entrypoint: "picker",
        success: true,
        resume_duration_ms: Math.round(performance.now() - resumeStart)
      });
      setLogs([]);
      setResumeData({
        messages: result_3.messages,
        fileHistorySnapshots: result_3.fileHistorySnapshots,
        contentReplacements: result_3.contentReplacements,
        agentName: result_3.agentName,
        agentColor: result_3.agentColor === "default" ? undefined : result_3.agentColor,
        mainThreadAgentDefinition: resolvedAgentDef
      });
    } catch (e) {
      logEvent("tengu_session_resumed", {
        entrypoint: "picker",
        success: false
      });
      logError(e);
      throw e;
    }
  }
  if (crossProjectCommand) {
    return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(CrossProjectMessage, {
      command: crossProjectCommand
    }, undefined, false, undefined, this);
  }
  if (resumeData) {
    return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(REPL, {
      debug,
      commands,
      initialTools,
      initialMessages: resumeData.messages,
      initialFileHistorySnapshots: resumeData.fileHistorySnapshots,
      initialContentReplacements: resumeData.contentReplacements,
      initialAgentName: resumeData.agentName,
      initialAgentColor: resumeData.agentColor,
      mcpClients,
      dynamicMcpConfig,
      strictMcpConfig,
      systemPrompt,
      appendSystemPrompt,
      mainThreadAgentDefinition: resumeData.mainThreadAgentDefinition,
      autoConnectIdeFlag,
      disableSlashCommands,
      taskListId,
      thinkingConfig,
      onTurnComplete
    }, undefined, false, undefined, this);
  }
  if (loading) {
    return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
      children: [
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Spinner, {}, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
          children: " Loading conversations\u2026"
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this);
  }
  if (resuming) {
    return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
      children: [
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Spinner, {}, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
          children: " Resuming conversation\u2026"
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this);
  }
  if (filteredLogs.length === 0) {
    return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(NoConversationsMessage, {}, undefined, false, undefined, this);
  }
  return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(LogSelector, {
    logs: filteredLogs,
    maxHeight: rows,
    onCancel,
    onSelect,
    onLogsChanged: isResumeWithRenameEnabled ? () => loadLogs(showAllProjects) : undefined,
    onLoadMore: loadMoreLogs,
    initialSearchQuery,
    showAllProjects,
    onToggleAllProjects: handleToggleAllProjects,
    onAgenticSearch: agenticSessionSearch
  }, undefined, false, undefined, this);
}
function NoConversationsMessage() {
  const $ = import_compiler_runtime.c(2);
  let t0;
  if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
    t0 = {
      context: "Global"
    };
    $[0] = t0;
  } else {
    t0 = $[0];
  }
  useKeybinding("app:interrupt", _temp, t0);
  let t1;
  if ($[1] === Symbol.for("react.memo_cache_sentinel")) {
    t1 = /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
      flexDirection: "column",
      children: [
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
          children: "No conversations found to resume."
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
          dimColor: true,
          children: "Press Ctrl+C to exit and start a new conversation."
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this);
    $[1] = t1;
  } else {
    t1 = $[1];
  }
  return t1;
}
function _temp() {
  process.exit(1);
}
function CrossProjectMessage(t0) {
  const $ = import_compiler_runtime.c(8);
  const {
    command
  } = t0;
  let t1;
  if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
    t1 = [];
    $[0] = t1;
  } else {
    t1 = $[0];
  }
  import_react.default.useEffect(_temp3, t1);
  let t2;
  if ($[1] === Symbol.for("react.memo_cache_sentinel")) {
    t2 = /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
      children: "This conversation is from a different directory."
    }, undefined, false, undefined, this);
    $[1] = t2;
  } else {
    t2 = $[1];
  }
  let t3;
  if ($[2] === Symbol.for("react.memo_cache_sentinel")) {
    t3 = /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
      children: "To resume, run:"
    }, undefined, false, undefined, this);
    $[2] = t3;
  } else {
    t3 = $[2];
  }
  let t4;
  if ($[3] !== command) {
    t4 = /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
      flexDirection: "column",
      children: [
        t3,
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
          children: [
            " ",
            command
          ]
        }, undefined, true, undefined, this)
      ]
    }, undefined, true, undefined, this);
    $[3] = command;
    $[4] = t4;
  } else {
    t4 = $[4];
  }
  let t5;
  if ($[5] === Symbol.for("react.memo_cache_sentinel")) {
    t5 = /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
      dimColor: true,
      children: "(Command copied to clipboard)"
    }, undefined, false, undefined, this);
    $[5] = t5;
  } else {
    t5 = $[5];
  }
  let t6;
  if ($[6] !== t4) {
    t6 = /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
      flexDirection: "column",
      gap: 1,
      children: [
        t2,
        t4,
        t5
      ]
    }, undefined, true, undefined, this);
    $[6] = t4;
    $[7] = t6;
  } else {
    t6 = $[7];
  }
  return t6;
}
function _temp3() {
  const timeout = setTimeout(_temp2, 100);
  return () => clearTimeout(timeout);
}
function _temp2() {
  process.exit(0);
}
export {
  ResumeConversation
};
