import { _ as __nuxt_component_0 } from './Card-BkfpdQZ7.mjs';
import { a as __nuxt_component_1 } from './Button-Dgqz5RR8.mjs';
import { _ as __nuxt_component_2, u as useApi } from './useApi-CFWxoIea.mjs';
import { defineComponent, computed, ref, mergeProps, withCtx, unref, createTextVNode, toDisplayString, openBlock, createBlock, createCommentVNode, createVNode, Fragment, renderList, nextTick, useSSRContext } from 'vue';
import { ssrRenderAttrs, ssrRenderComponent, ssrRenderList, ssrInterpolate, ssrRenderClass } from 'vue/server-renderer';
import { k as useRuntimeConfig } from './server.mjs';
import { _ as _export_sfc } from './_plugin-vue_export-helper-1tPrXgE0.mjs';
import 'tailwind-merge';
import './selectMenu-B2FUotwL.mjs';
import './nuxt-link-B3UD8izG.mjs';
import '../nitro/nitro.mjs';
import 'node:path';
import 'node:module';
import 'node:fs';
import 'node:os';
import 'dotenv';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'node:crypto';
import 'node:async_hooks';
import 'node:url';
import 'node:net';
import '@iconify/utils';
import 'consola';
import './index-Dy4Tu7MB.mjs';
import '@iconify/vue';
import '@iconify/utils/lib/css/icon';
import 'perfect-debounce';
import 'vue-router';
import '@vueuse/core';
import '../routes/renderer.mjs';
import 'vue-bundle-renderer/runtime';
import 'unhead/server';
import 'devalue';
import 'unhead/utils';
import 'unhead/plugins';

const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "run",
  __ssrInlineRender: true,
  setup(__props) {
    const api = useApi();
    const runtime = useRuntimeConfig();
    const cwd = computed(() => runtime.public.aidevCwd);
    const statuses = [
      { value: "open", label: "Open", color: "primary" },
      { value: "pending", label: "Pending", color: "sky" },
      { value: "review", label: "Review", color: "amber" },
      { value: "all", label: "All", color: "gray" }
    ];
    const lines = ref([]);
    const running = ref(false);
    const cancelling = ref(false);
    const activeStatus = ref(null);
    const lastExit = ref(null);
    const error = ref("");
    const viewer = ref(null);
    const text = computed(() => lines.value.join("\n"));
    const stateKey = computed(() => {
      if (running.value) return "running";
      if (error.value) return "error";
      if (lastExit.value) {
        return lastExit.value.code === 0 ? "done" : "failed";
      }
      return "idle";
    });
    const statusText = computed(() => {
      if (running.value && activeStatus.value) {
        return `Running aidev run ${activeStatus.value}\u2026`;
      }
      if (lastExit.value) {
        const { code, signal, durationMs } = lastExit.value;
        const dur = formatDuration(durationMs);
        if (signal) return `Terminated by signal ${signal} after ${dur}`;
        return `Exited with code ${code != null ? code : "null"} after ${dur}`;
      }
      return "Idle";
    });
    function formatDuration(ms) {
      if (ms < 1e3) return `${ms}ms`;
      const s = ms / 1e3;
      if (s < 60) return `${s.toFixed(1)}s`;
      const m = Math.floor(s / 60);
      const rem = Math.round(s - m * 60);
      return `${m}m ${rem}s`;
    }
    function appendLine(prefix, line) {
      lines.value.push(line);
      nextTick(() => {
        const el = viewer.value;
        if (el) el.scrollTop = el.scrollHeight;
      });
    }
    async function startRun(status) {
      if (running.value) return;
      {
        error.value = "Not authenticated \u2014 refresh and log in again.";
        return;
      }
    }
    async function cancelRun() {
      if (!running.value || cancelling.value) return;
      cancelling.value = true;
      try {
        await api("/api/run/cancel", { method: "POST" });
        appendLine("", "--- cancel requested (SIGTERM) ---");
      } catch (err) {
        cancelling.value = false;
        error.value = err instanceof Error ? err.message : String(err);
      }
    }
    return (_ctx, _push, _parent, _attrs) => {
      const _component_UCard = __nuxt_component_0;
      const _component_UButton = __nuxt_component_1;
      const _component_UAlert = __nuxt_component_2;
      _push(`<div${ssrRenderAttrs(mergeProps({ class: "run-page" }, _attrs))} data-v-3bd8ab3c>`);
      _push(ssrRenderComponent(_component_UCard, null, {
        header: withCtx((_, _push2, _parent2, _scopeId) => {
          if (_push2) {
            _push2(`<div class="flex items-center justify-between gap-3 flex-wrap" data-v-3bd8ab3c${_scopeId}><div data-v-3bd8ab3c${_scopeId}><h1 class="text-lg font-semibold" data-v-3bd8ab3c${_scopeId}>Run</h1><p class="text-xs text-gray-500 mt-1" data-v-3bd8ab3c${_scopeId}> Spawns <code data-v-3bd8ab3c${_scopeId}>aidev run &lt;status&gt;</code> in <code data-v-3bd8ab3c${_scopeId}>${ssrInterpolate(unref(cwd) || "\u2014")}</code> and streams output live below. </p></div>`);
            if (unref(lines).length > 0 && !unref(running)) {
              _push2(ssrRenderComponent(_component_UButton, {
                size: "xs",
                color: "gray",
                variant: "ghost",
                onClick: ($event) => lines.value = []
              }, {
                default: withCtx((_2, _push3, _parent3, _scopeId2) => {
                  if (_push3) {
                    _push3(` Clear output `);
                  } else {
                    return [
                      createTextVNode(" Clear output ")
                    ];
                  }
                }),
                _: 1
              }, _parent2, _scopeId));
            } else {
              _push2(`<!---->`);
            }
            _push2(`</div>`);
          } else {
            return [
              createVNode("div", { class: "flex items-center justify-between gap-3 flex-wrap" }, [
                createVNode("div", null, [
                  createVNode("h1", { class: "text-lg font-semibold" }, "Run"),
                  createVNode("p", { class: "text-xs text-gray-500 mt-1" }, [
                    createTextVNode(" Spawns "),
                    createVNode("code", null, "aidev run <status>"),
                    createTextVNode(" in "),
                    createVNode("code", null, toDisplayString(unref(cwd) || "\u2014"), 1),
                    createTextVNode(" and streams output live below. ")
                  ])
                ]),
                unref(lines).length > 0 && !unref(running) ? (openBlock(), createBlock(_component_UButton, {
                  key: 0,
                  size: "xs",
                  color: "gray",
                  variant: "ghost",
                  onClick: ($event) => lines.value = []
                }, {
                  default: withCtx(() => [
                    createTextVNode(" Clear output ")
                  ]),
                  _: 1
                }, 8, ["onClick"])) : createCommentVNode("", true)
              ])
            ];
          }
        }),
        default: withCtx((_, _push2, _parent2, _scopeId) => {
          if (_push2) {
            if (unref(error)) {
              _push2(ssrRenderComponent(_component_UAlert, {
                color: "red",
                variant: "soft",
                title: unref(error),
                class: "mb-3"
              }, null, _parent2, _scopeId));
            } else {
              _push2(`<!---->`);
            }
            _push2(`<div class="actions" data-v-3bd8ab3c${_scopeId}><!--[-->`);
            ssrRenderList(statuses, (s) => {
              _push2(ssrRenderComponent(_component_UButton, {
                key: s.value,
                size: "md",
                color: s.color,
                loading: unref(running) && unref(activeStatus) === s.value,
                disabled: unref(running),
                class: "action-btn",
                onClick: ($event) => startRun(s.value)
              }, {
                default: withCtx((_2, _push3, _parent3, _scopeId2) => {
                  if (_push3) {
                    _push3(`${ssrInterpolate(s.label)}`);
                  } else {
                    return [
                      createTextVNode(toDisplayString(s.label), 1)
                    ];
                  }
                }),
                _: 2
              }, _parent2, _scopeId));
            });
            _push2(`<!--]-->`);
            _push2(ssrRenderComponent(_component_UButton, {
              size: "md",
              color: "red",
              variant: "soft",
              disabled: !unref(running) || unref(cancelling),
              loading: unref(cancelling),
              class: "cancel-btn",
              onClick: cancelRun
            }, {
              default: withCtx((_2, _push3, _parent3, _scopeId2) => {
                if (_push3) {
                  _push3(` Cancel `);
                } else {
                  return [
                    createTextVNode(" Cancel ")
                  ];
                }
              }),
              _: 1
            }, _parent2, _scopeId));
            _push2(`</div><div class="status-bar" data-v-3bd8ab3c${_scopeId}><span class="${ssrRenderClass([`status-dot--${unref(stateKey)}`, "status-dot"])}" data-v-3bd8ab3c${_scopeId}></span><span class="status-text" data-v-3bd8ab3c${_scopeId}>${ssrInterpolate(unref(statusText))}</span></div>`);
            if (unref(lines).length > 0) {
              _push2(`<pre class="viewer" data-v-3bd8ab3c${_scopeId}><code data-v-3bd8ab3c${_scopeId}>${ssrInterpolate(unref(text))}</code></pre>`);
            } else {
              _push2(`<p class="empty" data-v-3bd8ab3c${_scopeId}>No output yet. Click a status above to start a run.</p>`);
            }
          } else {
            return [
              unref(error) ? (openBlock(), createBlock(_component_UAlert, {
                key: 0,
                color: "red",
                variant: "soft",
                title: unref(error),
                class: "mb-3"
              }, null, 8, ["title"])) : createCommentVNode("", true),
              createVNode("div", { class: "actions" }, [
                (openBlock(), createBlock(Fragment, null, renderList(statuses, (s) => {
                  return createVNode(_component_UButton, {
                    key: s.value,
                    size: "md",
                    color: s.color,
                    loading: unref(running) && unref(activeStatus) === s.value,
                    disabled: unref(running),
                    class: "action-btn",
                    onClick: ($event) => startRun(s.value)
                  }, {
                    default: withCtx(() => [
                      createTextVNode(toDisplayString(s.label), 1)
                    ]),
                    _: 2
                  }, 1032, ["color", "loading", "disabled", "onClick"]);
                }), 64)),
                createVNode(_component_UButton, {
                  size: "md",
                  color: "red",
                  variant: "soft",
                  disabled: !unref(running) || unref(cancelling),
                  loading: unref(cancelling),
                  class: "cancel-btn",
                  onClick: cancelRun
                }, {
                  default: withCtx(() => [
                    createTextVNode(" Cancel ")
                  ]),
                  _: 1
                }, 8, ["disabled", "loading"])
              ]),
              createVNode("div", { class: "status-bar" }, [
                createVNode("span", {
                  class: ["status-dot", `status-dot--${unref(stateKey)}`]
                }, null, 2),
                createVNode("span", { class: "status-text" }, toDisplayString(unref(statusText)), 1)
              ]),
              unref(lines).length > 0 ? (openBlock(), createBlock("pre", {
                key: 1,
                ref_key: "viewer",
                ref: viewer,
                class: "viewer"
              }, [
                createVNode("code", null, toDisplayString(unref(text)), 1)
              ], 512)) : (openBlock(), createBlock("p", {
                key: 2,
                class: "empty"
              }, "No output yet. Click a status above to start a run."))
            ];
          }
        }),
        _: 1
      }, _parent));
      _push(`</div>`);
    };
  }
});
const _sfc_setup = _sfc_main.setup;
_sfc_main.setup = (props, ctx) => {
  const ssrContext = useSSRContext();
  (ssrContext.modules || (ssrContext.modules = /* @__PURE__ */ new Set())).add("pages/run.vue");
  return _sfc_setup ? _sfc_setup(props, ctx) : void 0;
};
const run = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-3bd8ab3c"]]);

export { run as default };
//# sourceMappingURL=run-CfSa6qTR.mjs.map
