// @bun
import {
  ConfigurableShortcutHint,
  Select,
  Spinner,
  TeleportError,
  init_ConfigurableShortcutHint,
  init_CustomSelect,
  init_Spinner,
  init_TeleportError,
  init_teleport,
  init_useShortcutDisplay,
  init_useTerminalSize,
  teleportResumeCodeSession,
  useShortcutDisplay
} from "./chunk-e91vvygt.js";
import"./chunk-k60b56gr.js";
import"./chunk-14p6wvsq.js";
import"./chunk-n66h7gtd.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-ptxteaeh.js";
import"./chunk-ftrj0crk.js";
import"./chunk-yrpthe2x.js";
import"./chunk-10fpzkhd.js";
import"./chunk-awz3dq2e.js";
import"./chunk-2tabctw9.js";
import"./chunk-z21x0z3h.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-9rwstxn3.js";
import"./chunk-td4ter5p.js";
import"./chunk-71sdcaq6.js";
import"./chunk-cb6yemrf.js";
import"./chunk-tj8te4np.js";
import"./chunk-jjh8y2m7.js";
import"./chunk-dr2x4ze7.js";
import"./chunk-8ad8jmrf.js";
import"./chunk-24kv69g3.js";
import"./chunk-68n1gfc7.js";
import"./chunk-1w7c5hws.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-vgmsapsy.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-zypcr179.js";
import"./chunk-etcs82b2.js";
import"./chunk-7wy0nfkf.js";
import"./chunk-1emjj9xz.js";
import {
  fetchCodeSessionsFromSessionsAPI,
  init_api
} from "./chunk-m1hz377a.js";
import"./chunk-4nctdw69.js";
import"./chunk-vhghhw4q.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-hdwp8fte.js";
import"./chunk-hqxp6b72.js";
import"./chunk-3cwfww0q.js";
import"./chunk-xqc9bbe3.js";
import"./chunk-w5hnghah.js";
import"./chunk-qm7pdcft.js";
import"./chunk-x59e8cv0.js";
import"./chunk-s76nvx50.js";
import"./chunk-7jyr5758.js";
import"./chunk-zrpa39fh.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 {
  formatRelativeTime,
  init_format
} from "./chunk-kgkdmr0x.js";
import"./chunk-hn4w9pkj.js";
import {
  Byline,
  KeyboardShortcutHint,
  ThemedBox_default,
  ThemedText,
  init_src,
  require_react,
  useKeybinding,
  useTerminalSize,
  use_input_default
} 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 {
  detectCurrentRepository,
  init_detectRepository
} from "./chunk-ddaxg4xh.js";
import"./chunk-vvh31np8.js";
import"./chunk-tywrrc1m.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-4p0hxk2c.js";
import"./chunk-c4dyxsat.js";
import"./chunk-34rn09za.js";
import"./chunk-m28vg9w4.js";
import"./chunk-rk9fgqmg.js";
import"./chunk-nw4zt0y4.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import {
  TeleportOperationError,
  errorMessage,
  init_debug,
  init_errors,
  logForDebugging
} from "./chunk-k9jzhhww.js";
import"./chunk-kb3758f7.js";
import {
  init_state,
  setTeleportedSessionInfo
} 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 {
  __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 Claude Code sessions\u2026"
            })
          ]
        }),
        /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          children: retrying ? "Retrying\u2026" : "Fetching your Claude 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 Claude 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 Claude 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, Claude 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=E303F8AB62FEF0F764756E2164756E21
//# sourceMappingURL=chunk-cmsw79ew.js.map
