// @bun
import {
  REPL
} from "./chunk-7st6avj9.js";
import"./chunk-wh2ff3ch.js";
import"./chunk-6xq2xrte.js";
import"./chunk-hzman0ad.js";
import"./chunk-4d7g4q9x.js";
import {
  computeStandaloneAgentContext,
  restoreAgentFromSession,
  restoreWorktreeForResume
} from "./chunk-7hh0jx8q.js";
import"./chunk-zsqbsk44.js";
import"./chunk-z4cyrpb0.js";
import {
  renameRecordingForSession
} from "./chunk-gfmpm09h.js";
import"./chunk-pqsaqs5j.js";
import"./chunk-1atca0aw.js";
import"./chunk-nt837qt9.js";
import"./chunk-a15bwzv6.js";
import"./chunk-24t67ypa.js";
import"./chunk-g7dvrb3z.js";
import"./chunk-84gh0jr2.js";
import"./chunk-ncxkwvej.js";
import"./chunk-6wgtpme1.js";
import"./chunk-y3k7wv9x.js";
import"./chunk-ygg5pmz8.js";
import"./chunk-q7s77pay.js";
import"./chunk-m41e19ms.js";
import"./chunk-kn78peer.js";
import"./chunk-hf1c5cg6.js";
import"./chunk-wpyf9p2w.js";
import"./chunk-btx18bwt.js";
import"./chunk-x4jhbays.js";
import"./chunk-j2k6z1fm.js";
import"./chunk-xwet3awb.js";
import"./chunk-mmst5rby.js";
import {
  LogSelector,
  agenticSessionSearch,
  checkCrossProjectResume,
  init_LogSelector,
  init_agenticSessionSearch,
  init_crossProjectResume
} from "./chunk-4gxrjx1x.js";
import"./chunk-ftt3vqj2.js";
import"./chunk-aj6serpk.js";
import"./chunk-695qq0sf.js";
import"./chunk-d2an0138.js";
import"./chunk-af9g8wrq.js";
import"./chunk-w4ascbjv.js";
import"./chunk-4gjhjt2k.js";
import"./chunk-fv8qe3z0.js";
import"./chunk-9t4s34hy.js";
import"./chunk-bzs7vtfy.js";
import"./chunk-e4rzhy5g.js";
import"./chunk-3qjgadpe.js";
import"./chunk-6zjsjrxv.js";
import"./chunk-70v68jh1.js";
import"./chunk-hpwnjsf6.js";
import"./chunk-ms4bedbv.js";
import"./chunk-xrw80zgd.js";
import"./chunk-f9avmtbr.js";
import"./chunk-qzvdnhv6.js";
import"./chunk-7kpypk7z.js";
import"./chunk-tkkg1hj5.js";
import"./chunk-4cqj75bx.js";
import"./chunk-wpht0axr.js";
import"./chunk-fr758gpr.js";
import"./chunk-61x40vam.js";
import"./chunk-v5srj8wn.js";
import"./chunk-8qt2kaxf.js";
import"./chunk-ghvmfztq.js";
import"./chunk-dp03nxnw.js";
import"./chunk-n3zdy9bp.js";
import"./chunk-1hdfac4e.js";
import"./chunk-bxt4xhfb.js";
import"./chunk-3x57b8m9.js";
import"./chunk-mv42xwx0.js";
import"./chunk-6yhxd7fq.js";
import"./chunk-skxv6jwm.js";
import"./chunk-049yewrh.js";
import"./chunk-yev8xbj4.js";
import"./chunk-k49xc781.js";
import"./chunk-twez5yh3.js";
import"./chunk-rytj4vaa.js";
import"./chunk-daxz5mq2.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-kjxnr94g.js";
import"./chunk-k60b56gr.js";
import"./chunk-14p6wvsq.js";
import"./chunk-azxvgxxj.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-ptxteaeh.js";
import"./chunk-fkj2br21.js";
import"./chunk-shphk01c.js";
import"./chunk-p6k95sgc.js";
import"./chunk-4m3923rb.js";
import"./chunk-y0v4hy3w.js";
import"./chunk-kq5sj40w.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-wngdrp47.js";
import"./chunk-k16xn6nh.js";
import"./chunk-71sdcaq6.js";
import"./chunk-a3d92pmr.js";
import"./chunk-tj8te4np.js";
import"./chunk-vsrmbjkt.js";
import"./chunk-dr2x4ze7.js";
import"./chunk-8ad8jmrf.js";
import"./chunk-24kv69g3.js";
import"./chunk-7epwkzgh.js";
import"./chunk-ecexf828.js";
import"./chunk-4gyjc4jm.js";
import"./chunk-4spgkgr3.js";
import"./chunk-e8dhxycp.js";
import"./chunk-hf0jvnz1.js";
import {
  init_useKeybinding
} from "./chunk-9pygs2bc.js";
import"./chunk-60fkafk2.js";
import"./chunk-gaazk5m4.js";
import"./chunk-syy6c7sf.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-071s9he9.js";
import"./chunk-zbbc88qa.js";
import"./chunk-tar6yn24.js";
import"./chunk-ye27avgv.js";
import"./chunk-31evwxsk.js";
import"./chunk-4nctdw69.js";
import"./chunk-vhghhw4q.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-08snmmg4.js";
import"./chunk-hqxp6b72.js";
import"./chunk-z01behwa.js";
import"./chunk-6wnn50vj.js";
import"./chunk-w5hnghah.js";
import"./chunk-j75as8e6.js";
import"./chunk-x59e8cv0.js";
import"./chunk-s76nvx50.js";
import"./chunk-7jyr5758.js";
import"./chunk-33xsdkzq.js";
import"./chunk-nkg1b3qw.js";
import"./chunk-c1kx8bry.js";
import"./chunk-epvbnq43.js";
import"./chunk-swgt1px0.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-swz6krys.js";
import"./chunk-7eywm3ed.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-25w7rxtr.js";
import"./chunk-5xfj4jkd.js";
import"./chunk-c1t99xmt.js";
import"./chunk-vwenx8ke.js";
import"./chunk-8thwr7p8.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-rt34thxn.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-kgkdmr0x.js";
import"./chunk-hn4w9pkj.js";
import {
  ThemedBox_default,
  ThemedText,
  init_src,
  require_react,
  setClipboard,
  useKeybinding,
  useTerminalSize
} from "./chunk-cswpvb8x.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-ddaxg4xh.js";
import"./chunk-vvh31np8.js";
import"./chunk-tywrrc1m.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-4p0hxk2c.js";
import"./chunk-c4dyxsat.js";
import {
  init_log,
  logError
} from "./chunk-34rn09za.js";
import"./chunk-m28vg9w4.js";
import"./chunk-rk9fgqmg.js";
import"./chunk-nw4zt0y4.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import"./chunk-k9jzhhww.js";
import"./chunk-kb3758f7.js";
import {
  getOriginalCwd,
  init_state,
  switchSession
} from "./chunk-xqs9r7pg.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=C452C877A5B9F4D064756E2164756E21
//# sourceMappingURL=chunk-86s6gms7.js.map
