// @bun
import {
  ConfigurableShortcutHint,
  Select,
  Spinner,
  TeleportError,
  init_ConfigurableShortcutHint,
  init_CustomSelect,
  init_Spinner,
  init_TeleportError,
  init_teleport,
  init_useShortcutDisplay,
  init_useTerminalSize,
  teleportResumeCodeSession,
  useShortcutDisplay
} 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 {
  fetchCodeSessionsFromSessionsAPI,
  init_api
} from "./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 {
  formatRelativeTime,
  init_format
} from "./chunk-0gp4q8aq.js";
import"./chunk-hn4w9pkj.js";
import {
  Byline,
  KeyboardShortcutHint,
  ThemedBox_default,
  ThemedText,
  init_src,
  require_react,
  useKeybinding,
  useTerminalSize,
  use_input_default
} 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 {
  detectCurrentRepository,
  init_detectRepository
} from "./chunk-t0450ma3.js";
import"./chunk-0cqw3y8h.js";
import"./chunk-k1sw7km0.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-sc9ycxra.js";
import"./chunk-hhta0nge.js";
import"./chunk-8wsj9fff.js";
import"./chunk-m28vg9w4.js";
import"./chunk-f8prtxs3.js";
import"./chunk-41a6f2kv.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import {
  TeleportOperationError,
  errorMessage,
  init_debug,
  init_errors,
  logForDebugging
} from "./chunk-byd20vdq.js";
import"./chunk-kb3758f7.js";
import {
  init_state,
  setTeleportedSessionInfo
} 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 {
  __toESM
} from "./chunk-hhsxm2yr.js";

// src/components/TeleportResumeWrapper.tsx
init_analytics();
var import_react3 = __toESM(require_react(), 1);

// src/hooks/useTeleportResume.tsx
init_state();
init_analytics();
init_errors();
init_teleport();
var import_react = __toESM(require_react(), 1);
function useTeleportResume(source) {
  const [isResuming, setIsResuming] = import_react.useState(false);
  const [error, setError] = import_react.useState(null);
  const [selectedSession, setSelectedSession] = import_react.useState(null);
  const resumeSession = import_react.useCallback(async (session) => {
    setIsResuming(true);
    setError(null);
    setSelectedSession(session);
    logEvent("tengu_teleport_resume_session", {
      source,
      session_id: session.id
    });
    try {
      const result = await teleportResumeCodeSession(session.id);
      setTeleportedSessionInfo({ sessionId: session.id });
      setIsResuming(false);
      return result;
    } catch (err) {
      const teleportError = {
        message: err instanceof TeleportOperationError ? err.message : errorMessage(err),
        formattedMessage: err instanceof TeleportOperationError ? err.formattedMessage : undefined,
        isOperationError: err instanceof TeleportOperationError
      };
      setError(teleportError);
      setIsResuming(false);
      return null;
    }
  }, [source]);
  const clearError = import_react.useCallback(() => {
    setError(null);
  }, []);
  return {
    resumeSession,
    isResuming,
    error,
    selectedSession,
    clearError
  };
}

// src/components/TeleportResumeWrapper.tsx
init_src();
init_useKeybinding();

// src/components/ResumeTask.tsx
init_useTerminalSize();
init_api();
init_src();
init_useKeybinding();
init_useShortcutDisplay();
init_debug();
init_detectRepository();
init_format();
init_ConfigurableShortcutHint();
init_CustomSelect();
init_src();
init_Spinner();
init_TeleportError();
var import_react2 = __toESM(require_react(), 1);
var jsx_runtime = __toESM(require_jsx_runtime(), 1);
var UPDATED_STRING = "Updated";
var SPACE_BETWEEN_TABLE_COLUMNS = "  ";
function ResumeTask({ onSelect, onCancel, isEmbedded = false }) {
  const { rows } = useTerminalSize();
  const [sessions, setSessions] = import_react2.useState([]);
  const [currentRepo, setCurrentRepo] = import_react2.useState(null);
  const [loading, setLoading] = import_react2.useState(true);
  const [loadErrorType, setLoadErrorType] = import_react2.useState(null);
  const [retrying, setRetrying] = import_react2.useState(false);
  const [hasCompletedTeleportErrorFlow, setHasCompletedTeleportErrorFlow] = import_react2.useState(false);
  const [focusedIndex, setFocusedIndex] = import_react2.useState(1);
  const escKey = useShortcutDisplay("confirm:no", "Confirmation", "Esc");
  const loadSessions = import_react2.useCallback(async () => {
    try {
      setLoading(true);
      setLoadErrorType(null);
      const detectedRepo = await detectCurrentRepository();
      setCurrentRepo(detectedRepo);
      logForDebugging(`Current repository: ${detectedRepo || "not detected"}`);
      const codeSessions = await fetchCodeSessionsFromSessionsAPI();
      let filteredSessions = codeSessions;
      if (detectedRepo) {
        filteredSessions = codeSessions.filter((session) => {
          if (!session.repo)
            return false;
          const sessionRepo = `${session.repo.owner.login}/${session.repo.name}`;
          return sessionRepo === detectedRepo;
        });
        logForDebugging(`Filtered ${filteredSessions.length} sessions for repo ${detectedRepo} from ${codeSessions.length} total`);
      }
      const sortedSessions = [...filteredSessions].sort((a, b) => {
        const dateA = new Date(a.updated_at);
        const dateB = new Date(b.updated_at);
        return dateB.getTime() - dateA.getTime();
      });
      setSessions(sortedSessions);
    } catch (err) {
      const errorMessage2 = err instanceof Error ? err.message : String(err);
      logForDebugging(`Error loading code sessions: ${errorMessage2}`);
      setLoadErrorType(determineErrorType(errorMessage2));
    } finally {
      setLoading(false);
      setRetrying(false);
    }
  }, []);
  const handleRetry = () => {
    setRetrying(true);
    loadSessions();
  };
  useKeybinding("confirm:no", onCancel, { context: "Confirmation" });
  use_input_default((input, key) => {
    if (key.ctrl && input === "c") {
      onCancel();
      return;
    }
    if (key.ctrl && input === "r" && loadErrorType) {
      handleRetry();
      return;
    }
    if (loadErrorType !== null && key.return) {
      onCancel();
      return;
    }
  });
  const handleErrorComplete = import_react2.useCallback(() => {
    setHasCompletedTeleportErrorFlow(true);
    loadSessions();
  }, [setHasCompletedTeleportErrorFlow, loadSessions]);
  if (!hasCompletedTeleportErrorFlow) {
    return /* @__PURE__ */ jsx_runtime.jsx(TeleportError, {
      onComplete: handleErrorComplete
    });
  }
  if (loading) {
    return /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
      flexDirection: "column",
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
          flexDirection: "row",
          children: [
            /* @__PURE__ */ jsx_runtime.jsx(Spinner, {}),
            /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
              bold: true,
              children: "Loading Chris Code sessions\u2026"
            })
          ]
        }),
        /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          children: retrying ? "Retrying\u2026" : "Fetching your Chris Code sessions\u2026"
        })
      ]
    });
  }
  if (loadErrorType) {
    return /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
      flexDirection: "column",
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          bold: true,
          color: "error",
          children: "Error loading Chris Code sessions"
        }),
        renderErrorSpecificGuidance(loadErrorType),
        /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
          dimColor: true,
          children: [
            "Press ",
            /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
              bold: true,
              children: "Ctrl+R"
            }),
            " to retry \xB7 Press ",
            /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
              bold: true,
              children: escKey
            }),
            " to cancel"
          ]
        })
      ]
    });
  }
  if (sessions.length === 0) {
    return /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
      flexDirection: "column",
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
          bold: true,
          children: [
            "No Chris Code sessions found",
            currentRepo && /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
              children: [
                " for ",
                currentRepo
              ]
            })
          ]
        }),
        /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
          marginTop: 1,
          children: /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
            dimColor: true,
            children: [
              "Press ",
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: escKey
              }),
              " to cancel"
            ]
          })
        })
      ]
    });
  }
  const sessionMetadata = sessions.map((session) => ({
    ...session,
    timeString: formatRelativeTime(new Date(session.updated_at))
  }));
  const maxTimeStringLength = Math.max(UPDATED_STRING.length, ...sessionMetadata.map((meta) => meta.timeString.length));
  const options = sessionMetadata.map(({ timeString, title, id }) => {
    const paddedTime = timeString.padEnd(maxTimeStringLength, " ");
    return {
      label: `${paddedTime}  ${title}`,
      value: id
    };
  });
  const layoutOverhead = 7;
  const maxVisibleOptions = Math.max(1, isEmbedded ? Math.min(sessions.length, 5, rows - 6 - layoutOverhead) : Math.min(sessions.length, rows - 1 - layoutOverhead));
  const maxHeight = maxVisibleOptions + layoutOverhead;
  const showScrollPosition = sessions.length > maxVisibleOptions;
  return /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
    flexDirection: "column",
    padding: 1,
    height: maxHeight,
    children: [
      /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
        bold: true,
        children: [
          "Select a session to resume",
          showScrollPosition && /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
            dimColor: true,
            children: [
              " ",
              "(",
              focusedIndex,
              " of ",
              sessions.length,
              ")"
            ]
          }),
          currentRepo && /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
            dimColor: true,
            children: [
              " (",
              currentRepo,
              ")"
            ]
          }),
          ":"
        ]
      }),
      /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
        flexDirection: "column",
        marginTop: 1,
        flexGrow: 1,
        children: [
          /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
            marginLeft: 2,
            children: /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
              bold: true,
              children: [
                UPDATED_STRING.padEnd(maxTimeStringLength, " "),
                SPACE_BETWEEN_TABLE_COLUMNS,
                "Session Title"
              ]
            })
          }),
          /* @__PURE__ */ jsx_runtime.jsx(Select, {
            visibleOptionCount: maxVisibleOptions,
            options,
            onChange: (value) => {
              const session = sessions.find((s) => s.id === value);
              if (session) {
                onSelect(session);
              }
            },
            onFocus: (value) => {
              const index = options.findIndex((o) => o.value === value);
              if (index >= 0) {
                setFocusedIndex(index + 1);
              }
            }
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        flexDirection: "row",
        children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          children: /* @__PURE__ */ jsx_runtime.jsxs(Byline, {
            children: [
              /* @__PURE__ */ jsx_runtime.jsx(KeyboardShortcutHint, {
                shortcut: "\u2191/\u2193",
                action: "select"
              }),
              /* @__PURE__ */ jsx_runtime.jsx(KeyboardShortcutHint, {
                shortcut: "Enter",
                action: "confirm"
              }),
              /* @__PURE__ */ jsx_runtime.jsx(ConfigurableShortcutHint, {
                action: "confirm:no",
                context: "Confirmation",
                fallback: "Esc",
                description: "cancel"
              })
            ]
          })
        })
      })
    ]
  });
}
function determineErrorType(errorMessage2) {
  const message = errorMessage2.toLowerCase();
  if (message.includes("fetch") || message.includes("network") || message.includes("timeout")) {
    return "network";
  }
  if (message.includes("auth") || message.includes("token") || message.includes("permission") || message.includes("oauth") || message.includes("not authenticated") || message.includes("/login") || message.includes("console account") || message.includes("403")) {
    return "auth";
  }
  if (message.includes("api") || message.includes("rate limit") || message.includes("500") || message.includes("529")) {
    return "api";
  }
  return "other";
}
function renderErrorSpecificGuidance(errorType) {
  switch (errorType) {
    case "network":
      return /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        marginY: 1,
        flexDirection: "column",
        children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          children: "Check your internet connection"
        })
      });
    case "auth":
      return /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
        marginY: 1,
        flexDirection: "column",
        children: [
          /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
            dimColor: true,
            children: "Teleport requires a Claude account"
          }),
          /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
            dimColor: true,
            children: [
              "Run ",
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: "/login"
              }),
              ' and select "Claude account with subscription"'
            ]
          })
        ]
      });
    case "api":
      return /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        marginY: 1,
        flexDirection: "column",
        children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          children: "Sorry, Claude encountered an error"
        })
      });
    case "other":
      return /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        marginY: 1,
        flexDirection: "row",
        children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          children: "Sorry, Chris Code encountered an error"
        })
      });
  }
}

// src/components/TeleportResumeWrapper.tsx
init_Spinner();
var jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
function TeleportResumeWrapper({
  onComplete,
  onCancel,
  onError,
  isEmbedded = false,
  source
}) {
  const { resumeSession, isResuming, error, selectedSession } = useTeleportResume(source);
  import_react3.useEffect(() => {
    logEvent("tengu_teleport_started", {
      source
    });
  }, [source]);
  const handleSelect = async (session) => {
    const result = await resumeSession(session);
    if (result) {
      onComplete(result);
    } else if (error) {
      if (onError) {
        onError(error.message, error.formattedMessage);
      }
    }
  };
  const handleCancel = () => {
    logEvent("tengu_teleport_cancelled", {});
    onCancel();
  };
  useKeybinding("app:interrupt", handleCancel, {
    context: "Global",
    isActive: !!error && !onError
  });
  if (isResuming && selectedSession) {
    return /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
      flexDirection: "column",
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
          flexDirection: "row",
          children: [
            /* @__PURE__ */ jsx_runtime2.jsx(Spinner, {}),
            /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
              bold: true,
              children: "Resuming session\u2026"
            })
          ]
        }),
        /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
          dimColor: true,
          children: [
            'Loading "',
            selectedSession.title,
            '"\u2026'
          ]
        })
      ]
    });
  }
  if (error && !onError) {
    return /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
      flexDirection: "column",
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          bold: true,
          color: "error",
          children: "Failed to resume session"
        }),
        /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          dimColor: true,
          children: error.message
        }),
        /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
          marginTop: 1,
          children: /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
            dimColor: true,
            children: [
              "Press ",
              /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
                bold: true,
                children: "Esc"
              }),
              " to cancel"
            ]
          })
        })
      ]
    });
  }
  return /* @__PURE__ */ jsx_runtime2.jsx(ResumeTask, {
    onSelect: handleSelect,
    onCancel: handleCancel,
    isEmbedded
  });
}
export {
  TeleportResumeWrapper
};

//# debugId=4088B5EBA21CDB2864756E2164756E21
//# sourceMappingURL=chunk-dxyn4j8e.js.map
