// @bun
import {
  REPL
} from "./chunk-cqmsy2s2.js";
import"./chunk-dd89z0aa.js";
import"./chunk-js3dkj4e.js";
import"./chunk-gp6decq8.js";
import"./chunk-6wthn547.js";
import {
  computeStandaloneAgentContext,
  exports_persist,
  init_persist,
  restoreAgentFromSession,
  restoreWorktreeForResume
} from "./chunk-1wen8dar.js";
import"./chunk-v9h2j8jz.js";
import"./chunk-nxgrp26k.js";
import {
  renameRecordingForSession
} from "./chunk-ffjh6d8h.js";
import"./chunk-wcdja0c6.js";
import"./chunk-nt837qt9.js";
import"./chunk-a15bwzv6.js";
import"./chunk-fnnydvgk.js";
import"./chunk-hbs8cmb4.js";
import"./chunk-jtnmdy5f.js";
import"./chunk-g8est5nk.js";
import"./chunk-zeebdzqf.js";
import"./chunk-8yk09jf7.js";
import"./chunk-2j01njj0.js";
import"./chunk-67006cbc.js";
import"./chunk-setxbyxk.js";
import"./chunk-q2ypsn4z.js";
import"./chunk-m41e19ms.js";
import"./chunk-15fcqyjv.js";
import"./chunk-3pdk50ye.js";
import"./chunk-fyhhtbv5.js";
import"./chunk-wfnrfy93.js";
import"./chunk-39mtg69k.js";
import"./chunk-xwet3awb.js";
import"./chunk-p7e3rc2s.js";
import"./chunk-vex1cb1c.js";
import"./chunk-55z891s7.js";
import"./chunk-kxwava1g.js";
import"./chunk-t19akzt2.js";
import"./chunk-p07wrh8v.js";
import {
  LogSelector,
  agenticSessionSearch,
  checkCrossProjectResume,
  init_LogSelector,
  init_agenticSessionSearch,
  init_crossProjectResume
} from "./chunk-qx7t79zw.js";
import"./chunk-ftt3vqj2.js";
import"./chunk-qs2armyz.js";
import"./chunk-t80rws22.js";
import"./chunk-d2an0138.js";
import"./chunk-mc2ax0ff.js";
import"./chunk-ymqv4hyz.js";
import"./chunk-4e3x31c9.js";
import"./chunk-gmrghcqg.js";
import"./chunk-0z13a78r.js";
import"./chunk-6gt42kvj.js";
import"./chunk-3apkj8j9.js";
import"./chunk-xrw80zgd.js";
import"./chunk-fxjcm9bp.js";
import"./chunk-e2vtstkd.js";
import"./chunk-f7tma8gp.js";
import"./chunk-z4psnrvd.js";
import"./chunk-14sd3grv.js";
import"./chunk-pb9v47qr.js";
import"./chunk-75r9z3mk.js";
import"./chunk-y0f5vezg.js";
import"./chunk-rtcm253f.js";
import"./chunk-4b6edzew.js";
import"./chunk-ned5whgb.js";
import"./chunk-es4npmq2.js";
import"./chunk-awgdfggg.js";
import"./chunk-ned5qknr.js";
import"./chunk-9zyj24r6.js";
import"./chunk-b34jxkk8.js";
import"./chunk-mkttdqb0.js";
import"./chunk-mva6b6vr.js";
import"./chunk-3y69j7y8.js";
import"./chunk-2xh8v79x.js";
import"./chunk-120tmt7h.js";
import"./chunk-k49xc781.js";
import"./chunk-24x0sp1j.js";
import"./chunk-d6txmayg.js";
import"./chunk-5tkam0h1.js";
import"./chunk-3abaq08g.js";
import"./chunk-vw6ybyew.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,
  init_useTerminalSize,
  isCustomTitleEnabled,
  loadAllProjectsMessageLogsProgressive,
  loadConversationForResume,
  loadSameRepoMessageLogsProgressive,
  recordContentReplacement,
  resetSessionFilePointer,
  restoreCostStateForSession,
  restoreSessionMetadata,
  updateSessionName,
  useAppState,
  useSetAppState
} from "./chunk-421yegj3.js";
import"./chunk-aaxz8a5g.js";
import"./chunk-2kcgxnvp.js";
import"./chunk-14p6wvsq.js";
import"./chunk-6s0q1s5r.js";
import"./chunk-0cpg8qh8.js";
import"./chunk-9phn5khx.js";
import"./chunk-vk9xcryd.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-ptxteaeh.js";
import"./chunk-7fcmqvbz.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-q3b4n194.js";
import"./chunk-zaqfb3tz.js";
import"./chunk-6hzx0kqr.js";
import"./chunk-71sdcaq6.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-dxa3y9vh.js";
import"./chunk-gjvhjywj.js";
import"./chunk-1w20m7gw.js";
import"./chunk-3gam18xn.js";
import"./chunk-rpmntgyh.js";
import"./chunk-24kv69g3.js";
import"./chunk-tzcrwnrf.js";
import"./chunk-k7xszak2.js";
import"./chunk-ztmb7geg.js";
import"./chunk-tbdkekz3.js";
import {
  init_useKeybinding
} from "./chunk-65zbgg1n.js";
import"./chunk-4spgkgr3.js";
import"./chunk-60fkafk2.js";
import"./chunk-h5zz0vxy.js";
import"./chunk-6hygvrhn.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-8gv2pjby.js";
import"./chunk-pn23dh3d.js";
import"./chunk-rpdh02rm.js";
import"./chunk-j1wktfe2.js";
import"./chunk-fjtzfz1t.js";
import"./chunk-6hr7742d.js";
import"./chunk-xyg1sk2w.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-hem4f4gz.js";
import"./chunk-hqxp6b72.js";
import"./chunk-ccw8pse0.js";
import"./chunk-wsnxtggw.js";
import"./chunk-k8nwt8yq.js";
import"./chunk-vxbjzggp.js";
import"./chunk-d6h68rz1.js";
import"./chunk-8yvsnrkr.js";
import"./chunk-5mmhfbxb.js";
import"./chunk-s2t5anwv.js";
import"./chunk-ga1jkyqy.js";
import"./chunk-9hbhydvp.js";
import"./chunk-ck9r8hpf.js";
import"./chunk-k7hexw3v.js";
import"./chunk-trqrj23e.js";
import"./chunk-za3k6h2h.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-hjxqmtg5.js";
import"./chunk-bzyzrq0k.js";
import"./chunk-vwenx8ke.js";
import"./chunk-q2h79ncs.js";
import"./chunk-v4ypszbb.js";
import"./chunk-qfsn720k.js";
import"./chunk-7qx3xhv3.js";
import"./chunk-j9475b46.js";
import"./chunk-fdwabr8p.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-dbts5q5p.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-q1vrhh0q.js";
import"./chunk-hn4w9pkj.js";
import {
  ThemedBox_default,
  ThemedText,
  init_src,
  setClipboard,
  useKeybinding,
  useTerminalSize
} from "./chunk-2g0ytd9d.js";
import {
  require_jsx_dev_runtime,
  require_react
} from "./chunk-de0qnnf7.js";
import {
  init_analytics,
  logEvent
} from "./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-92bjkrf2.js";
import"./chunk-10k5jfc5.js";
import"./chunk-n9g24mwe.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-hzmzwte2.js";
import"./chunk-pdvg91cg.js";
import"./chunk-c696122m.js";
import"./chunk-xbj5keyy.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import"./chunk-aeysytks.js";
import {
  init_log,
  logError
} from "./chunk-s3hafnk3.js";
import"./chunk-kb3758f7.js";
import {
  init_state,
  switchSession
} from "./chunk-9h9k5vz3.js";
import"./chunk-xmpgmeb8.js";
import"./chunk-2kz09j2s.js";
import"./chunk-c0k7b0jw.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __toCommonJS,
  __toESM
} from "./chunk-hhsxm2yr.js";

// src/screens/ResumeConversation.tsx
init_useTerminalSize();
init_state();
init_LogSelector();
init_Spinner();
init_cost_tracker();
init_src();
init_src();
init_useKeybinding();
init_analytics();
init_AppState();
init_ids();
init_agenticSessionSearch();
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) => l.prNumber !== undefined);
      } else if (typeof filterByPr === "number") {
        result = result.filter((l) => l.prNumber === filterByPr);
      } else if (typeof filterByPr === "string") {
        const prNumber = parsePrIdentifier(filterByPr);
        if (prNumber !== null) {
          result = result.filter((l) => l.prNumber === prNumber);
        }
      }
    }
    return result;
  }, [logs, filterByPr]);
  const isResumeWithRenameEnabled = isCustomTitleEnabled();
  import_react.default.useEffect(() => {
    loadSameRepoMessageLogsProgressive(worktreePaths).then((result) => {
      sessionLogResultRef.current = result;
      logCountRef.current = result.logs.length;
      setLogs(result.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) => {
      ref.nextIndex = result.nextIndex;
      if (result.logs.length > 0) {
        const offset = logCountRef.current;
        result.logs.forEach((log, i) => {
          log.value = offset + i;
        });
        setLogs((prev) => prev.concat(result.logs));
        logCountRef.current += result.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) => {
      sessionLogResultRef.current = result;
      logCountRef.current = result.logs.length;
      setLogs(result.logs);
    }).catch((error) => {
      logError(error);
    }).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) {
    setResuming(true);
    const resumeStart = performance.now();
    const crossProjectCheck = checkCrossProjectResume(log, showAllProjects, worktreePaths);
    if (crossProjectCheck.isCrossProject) {
      if (!crossProjectCheck.isSameRepoWorktree) {
        const cmd = crossProjectCheck.command;
        const raw = await setClipboard(cmd);
        if (raw)
          process.stdout.write(raw);
        setCrossProjectCommand(cmd);
        return;
      }
    }
    try {
      const result = await loadConversationForResume(log, undefined);
      if (!result) {
        throw new Error("Failed to load conversation");
      }
      if (false) {}
      if (result.sessionId && !forkSession) {
        switchSession(asSessionId(result.sessionId), log.fullPath ? dirname(log.fullPath) : null);
        await renameRecordingForSession();
        await resetSessionFilePointer();
        restoreCostStateForSession(result.sessionId);
      } else if (forkSession && result.contentReplacements?.length) {
        await recordContentReplacement(result.contentReplacements);
      }
      const { agentDefinition: resolvedAgentDef } = restoreAgentFromSession(result.agentSetting, mainThreadAgentDefinition, agentDefinitions);
      setAppState((prev) => ({ ...prev, agent: resolvedAgentDef?.agentType }));
      if (false) {}
      const standaloneAgentContext = computeStandaloneAgentContext(result.agentName, result.agentColor);
      if (standaloneAgentContext) {
        setAppState((prev) => ({ ...prev, standaloneAgentContext }));
      }
      updateSessionName(result.agentName);
      restoreSessionMetadata(forkSession ? { ...result, worktreeSession: undefined } : result);
      if (!forkSession) {
        restoreWorktreeForResume(result.worktreeSession);
        if (result.sessionId) {
          adoptResumedSessionFile();
        }
      }
      if (true) {
        (init_persist(), __toCommonJS(exports_persist)).restoreFromEntries(result.contextCollapseCommits ?? [], result.contextCollapseSnapshot);
      }
      logEvent("tengu_session_resumed", {
        entrypoint: "picker",
        success: true,
        resume_duration_ms: Math.round(performance.now() - resumeStart)
      });
      setLogs([]);
      setResumeData({
        messages: result.messages,
        fileHistorySnapshots: result.fileHistorySnapshots,
        contentReplacements: result.contentReplacements,
        agentName: result.agentName,
        agentColor: result.agentColor === "default" ? undefined : result.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() {
  useKeybinding("app:interrupt", () => {
    process.exit(1);
  }, { context: "Global" });
  return /* @__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);
}
function CrossProjectMessage({ command }) {
  import_react.default.useEffect(() => {
    const timeout = setTimeout(() => {
      process.exit(0);
    }, 100);
    return () => clearTimeout(timeout);
  }, []);
  return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
    flexDirection: "column",
    gap: 1,
    children: [
      /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
        children: "This conversation is from a different directory."
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
        flexDirection: "column",
        children: [
          /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
            children: "To resume, run:"
          }, undefined, false, undefined, this),
          /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
            children: [
              " ",
              command
            ]
          }, undefined, true, undefined, this)
        ]
      }, undefined, true, undefined, this),
      /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
        dimColor: true,
        children: "(Command copied to clipboard)"
      }, undefined, false, undefined, this)
    ]
  }, undefined, true, undefined, this);
}
export {
  ResumeConversation
};
