// @bun
import {
  REPL
} from "./chunk-zrrwf7ne.js";
import"./chunk-yd5kpmh3.js";
import"./chunk-3k0shne5.js";
import"./chunk-phmpy100.js";
import"./chunk-3q15pdhk.js";
import {
  computeStandaloneAgentContext,
  restoreAgentFromSession,
  restoreWorktreeForResume
} from "./chunk-gw6qccad.js";
import"./chunk-q6vn86d9.js";
import"./chunk-e7y9w98q.js";
import {
  renameRecordingForSession
} from "./chunk-vg493gvk.js";
import"./chunk-s41pahx4.js";
import"./chunk-ap41sqh0.js";
import"./chunk-nt837qt9.js";
import"./chunk-a15bwzv6.js";
import"./chunk-24t67ypa.js";
import"./chunk-b1dc7nfj.js";
import"./chunk-2jxz86kc.js";
import"./chunk-shvkq58d.js";
import"./chunk-cspjnk17.js";
import"./chunk-4tpwabz4.js";
import"./chunk-q5f4p3w8.js";
import"./chunk-m41e19ms.js";
import"./chunk-z6q9bvc0.js";
import"./chunk-q65hv45k.js";
import"./chunk-2j0y03g0.js";
import"./chunk-t97fc7x0.js";
import"./chunk-v6sczawe.js";
import"./chunk-g2kn5gem.js";
import"./chunk-f3pqfwpq.js";
import"./chunk-xwet3awb.js";
import"./chunk-0pkfexr4.js";
import"./chunk-4qtnxgb5.js";
import"./chunk-8cp70ds4.js";
import"./chunk-tracj0s1.js";
import"./chunk-89z9cedj.js";
import"./chunk-h7vmn4cb.js";
import {
  LogSelector,
  agenticSessionSearch,
  checkCrossProjectResume,
  init_LogSelector,
  init_agenticSessionSearch,
  init_crossProjectResume
} from "./chunk-40an83n3.js";
import"./chunk-ftt3vqj2.js";
import"./chunk-xxahjcr2.js";
import"./chunk-b5qggyvr.js";
import"./chunk-d2an0138.js";
import"./chunk-7p2w8v1q.js";
import"./chunk-3vx6zzh5.js";
import"./chunk-zpkvp3rx.js";
import"./chunk-mj78e7py.js";
import"./chunk-tpe57t9s.js";
import"./chunk-xye9mn8j.js";
import"./chunk-xrw80zgd.js";
import"./chunk-f94n7sdt.js";
import"./chunk-wbz2avfn.js";
import"./chunk-ht6fwttn.js";
import"./chunk-mhvh0xr3.js";
import"./chunk-9sh0y9tz.js";
import"./chunk-r0yavxj0.js";
import"./chunk-1xk07zm3.js";
import"./chunk-7h2syxb4.js";
import"./chunk-446yy2hr.js";
import"./chunk-3fqwjjwv.js";
import"./chunk-r9c88ksn.js";
import"./chunk-wcx9zyz7.js";
import"./chunk-b4czbkjk.js";
import"./chunk-7kqc6zqt.js";
import"./chunk-sa6bpjp5.js";
import"./chunk-kb7jef6c.js";
import"./chunk-xe1z9acc.js";
import"./chunk-n6ary9xs.js";
import"./chunk-yqzah8pp.js";
import"./chunk-yq7btjq7.js";
import"./chunk-586erhd6.js";
import"./chunk-32zmhzc9.js";
import"./chunk-k49xc781.js";
import"./chunk-qvjdz7pf.js";
import"./chunk-djs8r2gw.js";
import"./chunk-wtex814h.js";
import"./chunk-8xjhgqt3.js";
import"./chunk-3abaq08g.js";
import"./chunk-rmn1bnbd.js";
import {
  Spinner,
  adoptResumedSessionFile,
  asSessionId,
  createSystemMessage,
  enrichLogs,
  exports_coordinatorMode,
  exports_loadAgentsDir,
  exports_sessionStorage,
  init_AppState,
  init_Spinner,
  init_concurrentSessions,
  init_conversationRecovery,
  init_coordinatorMode,
  init_cost_tracker,
  init_ids,
  init_loadAgentsDir,
  init_messages1 as init_messages,
  init_sessionStorage,
  init_useTerminalSize,
  isCustomTitleEnabled,
  loadAllProjectsMessageLogsProgressive,
  loadConversationForResume,
  loadSameRepoMessageLogsProgressive,
  recordContentReplacement,
  resetSessionFilePointer,
  restoreCostStateForSession,
  restoreSessionMetadata,
  updateSessionName,
  useAppState,
  useSetAppState
} from "./chunk-4vz571bb.js";
import"./chunk-14p6wvsq.js";
import"./chunk-8hseq8b1.js";
import"./chunk-ddtxq6k5.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-ptxteaeh.js";
import"./chunk-wd53a7m4.js";
import"./chunk-hms8ge0k.js";
import"./chunk-whpphypt.js";
import"./chunk-pht800m5.js";
import"./chunk-pjkqh1kq.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-qd3r2s2n.js";
import"./chunk-djzd7tef.js";
import"./chunk-gyhnpbkx.js";
import"./chunk-71sdcaq6.js";
import"./chunk-60gf7p5s.js";
import"./chunk-sj3d0nqx.js";
import"./chunk-9pk9rk2w.js";
import"./chunk-javpza6a.js";
import"./chunk-6v7bre98.js";
import"./chunk-24kv69g3.js";
import"./chunk-fcqebw9m.js";
import"./chunk-dnfd3c9s.js";
import"./chunk-15ezj4ww.js";
import"./chunk-1h284c6e.js";
import"./chunk-582g9yce.js";
import {
  init_useKeybinding
} from "./chunk-y3ztgztb.js";
import"./chunk-4spgkgr3.js";
import"./chunk-n8kbhswc.js";
import"./chunk-60fkafk2.js";
import"./chunk-fgbkrbk3.js";
import"./chunk-ssw61jfd.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-k8wq4qsj.js";
import"./chunk-g7d3xx1p.js";
import"./chunk-3wrx2943.js";
import"./chunk-7p9kkh0f.js";
import"./chunk-qp8cgz66.js";
import"./chunk-1mg610h2.js";
import"./chunk-93hc149s.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-nnat9jw5.js";
import"./chunk-hqxp6b72.js";
import"./chunk-4jzkqgf1.js";
import"./chunk-33rd41ng.js";
import"./chunk-f257kqw9.js";
import"./chunk-w5hnghah.js";
import"./chunk-36twraxy.js";
import"./chunk-1bkvnj0y.js";
import"./chunk-akdpcc5p.js";
import"./chunk-7rrkrej7.js";
import"./chunk-6r0bxrh6.js";
import"./chunk-d6500tvx.js";
import"./chunk-jg4bw4hp.js";
import"./chunk-epvbnq43.js";
import"./chunk-tn2sx7j6.js";
import"./chunk-6tzyv21c.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-ch4pgvwq.js";
import"./chunk-99jc4tcw.js";
import"./chunk-fghczfqt.js";
import"./chunk-vwenx8ke.js";
import"./chunk-f86mwfyd.js";
import"./chunk-v4ypszbb.js";
import"./chunk-bk6ck5c2.js";
import"./chunk-ym6j0wv1.js";
import"./chunk-hjmatcgt.js";
import"./chunk-6mdh70q0.js";
import"./chunk-ch92ycde.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-nt5dmk8q.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-0gp4q8aq.js";
import"./chunk-hn4w9pkj.js";
import {
  ThemedBox_default,
  ThemedText,
  init_src,
  require_react,
  setClipboard,
  useKeybinding,
  useTerminalSize
} from "./chunk-0r6npc3t.js";
import {
  require_jsx_runtime
} from "./chunk-gxyx8b8w.js";
import {
  init_analytics,
  logEvent
} from "./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-t0450ma3.js";
import"./chunk-0cqw3y8h.js";
import"./chunk-k1sw7km0.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-sc9ycxra.js";
import"./chunk-hhta0nge.js";
import {
  init_log,
  logError
} from "./chunk-8wsj9fff.js";
import"./chunk-m28vg9w4.js";
import"./chunk-f8prtxs3.js";
import"./chunk-41a6f2kv.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import"./chunk-byd20vdq.js";
import"./chunk-kb3758f7.js";
import {
  getOriginalCwd,
  init_state,
  switchSession
} from "./chunk-3j8w0rq8.js";
import"./chunk-tj0dzck2.js";
import"./chunk-aeysytks.js";
import"./chunk-ns1htxgd.js";
import"./chunk-ztqzmfx1.js";
import"./chunk-6k1rsk85.js";
import"./chunk-nxzx0ey9.js";
import"./chunk-yes1my80.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_runtime = __toESM(require_jsx_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 (true) {
        const coordinatorModule = (init_coordinatorMode(), __toCommonJS(exports_coordinatorMode));
        const warning = coordinatorModule.matchSessionMode(result.mode);
        if (warning) {
          const { getAgentDefinitionsWithOverrides, getActiveAgentsFromList } = (init_loadAgentsDir(), __toCommonJS(exports_loadAgentsDir));
          getAgentDefinitionsWithOverrides.cache.clear?.();
          const freshAgentDefs = await getAgentDefinitionsWithOverrides(getOriginalCwd());
          setAppState((prev) => ({
            ...prev,
            agentDefinitions: {
              ...freshAgentDefs,
              allAgents: freshAgentDefs.allAgents,
              activeAgents: getActiveAgentsFromList(freshAgentDefs.allAgents)
            }
          }));
          result.messages.push(createSystemMessage(warning, "warning"));
        }
      }
      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 (true) {
        const { saveMode } = (init_sessionStorage(), __toCommonJS(exports_sessionStorage));
        const { isCoordinatorMode } = (init_coordinatorMode(), __toCommonJS(exports_coordinatorMode));
        saveMode(isCoordinatorMode() ? "coordinator" : "normal");
      }
      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 (false) {}
      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_runtime.jsx(CrossProjectMessage, {
      command: crossProjectCommand
    });
  }
  if (resumeData) {
    return /* @__PURE__ */ jsx_runtime.jsx(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
    });
  }
  if (loading) {
    return /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
      children: [
        /* @__PURE__ */ jsx_runtime.jsx(Spinner, {}),
        /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          children: " Loading conversations\u2026"
        })
      ]
    });
  }
  if (resuming) {
    return /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
      children: [
        /* @__PURE__ */ jsx_runtime.jsx(Spinner, {}),
        /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          children: " Resuming conversation\u2026"
        })
      ]
    });
  }
  if (filteredLogs.length === 0) {
    return /* @__PURE__ */ jsx_runtime.jsx(NoConversationsMessage, {});
  }
  return /* @__PURE__ */ jsx_runtime.jsx(LogSelector, {
    logs: filteredLogs,
    maxHeight: rows,
    onCancel,
    onSelect,
    onLogsChanged: isResumeWithRenameEnabled ? () => loadLogs(showAllProjects) : undefined,
    onLoadMore: loadMoreLogs,
    initialSearchQuery,
    showAllProjects,
    onToggleAllProjects: handleToggleAllProjects,
    onAgenticSearch: agenticSessionSearch
  });
}
function NoConversationsMessage() {
  useKeybinding("app:interrupt", () => {
    process.exit(1);
  }, { context: "Global" });
  return /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
    flexDirection: "column",
    children: [
      /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
        children: "No conversations found to resume."
      }),
      /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
        dimColor: true,
        children: "Press Ctrl+C to exit and start a new conversation."
      })
    ]
  });
}
function CrossProjectMessage({ command }) {
  import_react.default.useEffect(() => {
    const timeout = setTimeout(() => {
      process.exit(0);
    }, 100);
    return () => clearTimeout(timeout);
  }, []);
  return /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
    flexDirection: "column",
    gap: 1,
    children: [
      /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
        children: "This conversation is from a different directory."
      }),
      /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
        flexDirection: "column",
        children: [
          /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
            children: "To resume, run:"
          }),
          /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
            children: [
              " ",
              command
            ]
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
        dimColor: true,
        children: "(Command copied to clipboard)"
      })
    ]
  });
}
export {
  ResumeConversation
};

//# debugId=D6C64CA82CD93D6A64756E2164756E21
//# sourceMappingURL=chunk-70fk5gc6.js.map
