Files
webup-cloud/frontend/src/views/Develop.vue
T

627 lines
19 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref, watch } from "vue";
import { api, body } from "../api";
const projects = ref<any[]>([]),
models = ref<any[]>([]),
tasks = ref<any[]>([]),
events = ref<any[]>([]),
selected = ref<any>(null),
error = ref(""),
success = ref(""),
busy = ref(false),
filePath = ref("."),
files = ref<any[]>([]),
content = ref(""),
editingPath = ref(""),
versions = ref<any[]>([]);
const fileBusy = ref(false),
fileLoaded = ref(false),
fileError = ref("");
let fileGeneration = 0;
let fileTaskSignature = "";
const execution = ref<any>({
ready: false,
state: "CHECKING",
reason: "正在检查开发执行环境…",
filesConfigured: false,
});
const queue = ref<any>({
config: { priority_enabled: false, priority_price: "0", max_concurrent: 0 },
positions: [],
running: 0,
reviewSlots: 0,
queued: 0,
});
const priorityKeys = new Map<string, string>();
function position(id: string) {
return queue.value.positions.find((p: any) => p.id === id)?.position;
}
const sandboxApi = (path: string, options: RequestInit = {}) =>
api(path, { signal: AbortSignal.timeout(150000), ...options });
const form = reactive({
projectId: "",
modelId: "",
prompt: "",
budget: "20",
idempotencyKey: crypto.randomUUID(),
});
let timer: ReturnType<typeof setInterval> | undefined;
const labels: Record<string, string> = {
QUEUED: "排队中",
RUNNING: "执行中",
PAUSED: "已暂停",
COMPLETED: "已结束",
CANCELLED: "已取消",
FAILED: "失败",
REVIEW_REQUIRED: "自动核算中",
};
async function load() {
try {
[tasks.value, queue.value] = await Promise.all([
api("/tasks"),
api("/queue"),
]);
execution.value = queue.value.execution;
const projectTasks = tasks.value.filter(
(t) => t.project_id === form.projectId,
);
const signature = projectTasks
.map((t) => `${t.id}:${t.status}:${t.step_count}`)
.join("|");
if (
signature !== fileTaskSignature ||
projectTasks.some((t) => t.status === "RUNNING")
) {
fileTaskSignature = signature;
if (execution.value.filesConfigured && !fileBusy.value) void list();
}
const id = selected.value?.id;
if (id) {
const [task, log] = await Promise.all([
api("/tasks/" + id),
api("/tasks/" + id + "/events"),
]);
if (selected.value?.id === id) {
const changed =
selected.value.status !== task.status ||
events.value.at(-1)?.id !== log.at(-1)?.id;
selected.value = task;
events.value = log;
if (changed && execution.value.filesConfigured && !fileBusy.value)
void list();
}
}
} catch (e) {
execution.value = {
ready: false,
state: "UNKNOWN",
reason: "暂时无法确认执行服务状态,请刷新后重试。",
filesConfigured: false,
};
error.value = (e as Error).message;
}
}
async function select(t: any) {
selected.value = t;
events.value = [];
form.projectId = t.project_id;
await load();
}
async function start() {
if (!execution.value.ready) {
error.value = execution.value.reason;
return;
}
busy.value = true;
error.value = "";
try {
selected.value = await api("/tasks", { method: "POST", body: body(form) });
form.idempotencyKey = crypto.randomUUID();
success.value = "执行服务已连接,任务已提交并预留预算。";
await load();
} catch (e) {
error.value = (e as Error).message;
} finally {
busy.value = false;
}
}
async function action(a: string) {
if (a === "cancel" && !confirm("确认取消任务?当前调用会先结算实际费用。"))
return;
busy.value = true;
try {
await api("/tasks/" + selected.value.id + "/" + a, { method: "POST" });
await load();
} catch (e) {
error.value = (e as Error).message;
} finally {
busy.value = false;
}
}
async function buyPriority() {
const task = selected.value;
if (!task || !execution.value.ready) return;
const price = queue.value.config.priority_price;
if (
!confirm(
`为当前任务支付 ¥${price} 购买排队优先权?优先费独立于 AI 开发预算,管理员人工调度优先于付费优先,不抢占正在执行的任务。首次执行前取消会自动退费,开始执行后不自动退费;不保证具体开始时间。`,
)
)
return;
busy.value = true;
error.value = "";
try {
if (!priorityKeys.has(task.id))
priorityKeys.set(task.id, crypto.randomUUID());
const order = await api(`/tasks/${task.id}/priority`, {
method: "POST",
body: body({
expectedPrice: price,
idempotencyKey: priorityKeys.get(task.id),
}),
});
success.value =
order.status === "REFUNDED"
? "该优先权订单已退款"
: "已获得本任务排队优先权,费用 ¥" + order.amount;
await load();
} catch (e) {
error.value = (e as Error).message;
} finally {
busy.value = false;
}
}
async function list() {
if (!form.projectId || fileBusy.value || !execution.value.filesConfigured)
return;
const project = form.projectId,
directory = filePath.value,
generation = fileGeneration;
fileBusy.value = true;
fileError.value = "";
try {
const result = await sandboxApi(
"/projects/" + project + "/files?path=" + encodeURIComponent(directory),
);
if (result.error) throw new Error(result.error);
if (
generation === fileGeneration &&
project === form.projectId &&
directory === filePath.value
) {
files.value = result.files || [];
fileLoaded.value = true;
if (!editingPath.value && !content.value) {
const first =
files.value.find(
(f) => !f.directory && !f.symlink && f.name === "index.html",
) ||
files.value.find(
(f) =>
!f.directory &&
!f.symlink &&
/\.(html|css|vue|svelte|tsx?|jsx?|py|java|go|rs|php)$/i.test(
f.name,
),
);
if (first) void openFile(first);
}
}
} catch (e) {
if (generation === fileGeneration) fileError.value = (e as Error).message;
} finally {
fileBusy.value = false;
if (
generation !== fileGeneration ||
project !== form.projectId ||
directory !== filePath.value
)
void list();
}
}
async function openFile(f: any) {
const project = form.projectId,
generation = fileGeneration;
const path = (filePath.value === "." ? "" : filePath.value + "/") + f.name;
if (f.directory) {
filePath.value = path;
await list();
return;
}
try {
const result = await sandboxApi(
"/projects/" + project + "/file?path=" + encodeURIComponent(path),
);
if (result.error) throw new Error(result.error);
if (generation === fileGeneration && project === form.projectId) {
content.value = result.content;
editingPath.value = path;
}
} catch (e) {
error.value = (e as Error).message;
}
}
async function saveFile() {
try {
const r = await sandboxApi("/projects/" + form.projectId + "/file", {
method: "PUT",
body: body({ path: editingPath.value, content: content.value }),
});
if (r.error) throw new Error(r.error);
success.value = "文件已写入隔离工作区";
await list();
} catch (e) {
error.value = (e as Error).message;
}
}
async function version(save = false) {
try {
let result;
if (save) {
const message = prompt("版本说明");
if (!message) return;
result = await sandboxApi("/projects/" + form.projectId + "/versions", {
method: "POST",
body: body({ message }),
});
} else
result = await sandboxApi("/projects/" + form.projectId + "/versions");
if (result.error) throw new Error(result.error);
versions.value = result.versions || [];
} catch (e) {
error.value = (e as Error).message;
}
}
async function download() {
if (!form.projectId) return;
busy.value = true;
try {
const res = await fetch("/api/projects/" + form.projectId + "/source", {
headers: { Authorization: "Bearer " + sessionStorage.getItem("session") },
signal: AbortSignal.timeout(150000),
});
if (!res.ok) {
const data = await res.json();
throw new Error(data.message || "下载失败");
}
const url = URL.createObjectURL(await res.blob()),
a = document.createElement("a");
a.href = url;
a.download = "project-" + form.projectId + ".zip";
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
} catch (e) {
error.value = (e as Error).message;
} finally {
busy.value = false;
}
}
watch(
() => form.projectId,
() => {
fileGeneration++;
files.value = [];
content.value = "";
editingPath.value = "";
versions.value = [];
filePath.value = ".";
fileLoaded.value = false;
fileError.value = "";
void list();
},
);
watch(
() => execution.value.filesConfigured,
(configured) => {
if (configured) void list();
},
);
onMounted(async () => {
try {
[projects.value, models.value] = await Promise.all([
api("/projects"),
api("/models"),
]);
form.projectId = projects.value.find((p) => p.status === "DRAFT")?.id || "";
form.modelId = models.value.find((m) => m.tools_enabled)?.id || "";
await load();
timer = setInterval(() => {
if (!document.hidden) load();
}, 3000);
} catch (e) {
error.value = (e as Error).message;
}
});
onUnmounted(() => clearInterval(timer));
</script>
<template>
<div class="page-heading">
<div>
<span class="eyebrow">AI DEVELOPMENT WORKSPACE</span>
<h1>AI 开发</h1>
<p>模型、工具、文件与预算,在同一个持久化任务中协作。</p>
</div>
<button class="secondary" @click="load">刷新状态</button>
</div>
<div v-if="error" class="alert error" role="alert">
{{ error }} <button class="link" @click="error = ''">关闭</button>
</div>
<div v-if="success" class="alert success">{{ success }}</div>
<div
class="alert"
:class="execution.ready ? 'success' : 'info'"
role="status"
>
<strong
>开发执行环境 ·
{{
execution.ready
? "已就绪"
: execution.state === "CHECKING"
? "检查中"
: "未就绪"
}}</strong
>
<p>{{ execution.reason }}</p>
<p v-if="queue.config.max_concurrent">
正在执行 {{ queue.running }} / 平台并发
{{ queue.config.max_concurrent }} · 排队 {{ queue.queued }} 项<span
v-if="queue.reviewSlots"
>
· 待核对占用 {{ queue.reviewSlots }} 个执行位</span
>
</p>
</div>
<div class="two-columns">
<section class="panel form-panel">
<h3>发起开发任务</h3>
<p class="muted">预算先预留,每轮按任务价格快照结算实际 usage。</p>
<form @submit.prevent="start">
<label
>项目<select v-model="form.projectId" required>
<option value="" disabled>先在项目管理创建项目</option>
<option
v-for="p in projects.filter((p) => p.status === 'DRAFT')"
:key="p.id"
:value="p.id"
>
{{ p.name }} · {{ p.stack }}
</option>
</select></label
><label
>开发模型<select v-model="form.modelId" required>
<option value="" disabled>等待管理员开放支持工具的模型</option>
<option
v-for="m in models.filter((m) => m.tools_enabled)"
:key="m.id"
:value="m.id"
>
{{ m.name }} · {{ m.provider_name }}
</option></select
><small v-if="form.modelId"
>输入 {{ models.find((m) => m.id === form.modelId)?.input_price }} /
输出
{{ models.find((m) => m.id === form.modelId)?.output_price }} CNY /
百万 Token</small
></label
><label
>本轮需求<textarea
v-model="form.prompt"
rows="4"
maxlength="10000"
required
placeholder="描述要开发或修改的功能。任务会保留该项目最近已完成的对话历史。"
/></label
><label
>预算上限 · CNY<input
v-model="form.budget"
type="number"
min="0.00000001"
step="0.00000001"
required /></label
><button
class="primary"
:disabled="
busy || !form.modelId || !form.projectId || !execution.ready
"
>
预留预算并提交
</button>
</form>
</section>
<section class="panel">
<div class="panel-heading">
<h3>我的任务</h3>
<span class="muted">最近 100 条</span>
</div>
<div class="task-list">
<button
v-for="t in tasks"
:key="t.id"
class="task-item"
:class="{ chosen: selected?.id === t.id }"
@click="select(t)"
>
<b>{{ t.project_name }}</b
><span class="status">{{ labels[t.status] || t.status }}</span>
<small v-if="t.status === 'QUEUED'"
>当前第 {{ position(t.id) || "—" }} 位 ·
{{
t.run_next
? "管理员指定下一位"
: t.paid_priority
? "付费优先"
: "普通队列"
}}</small
>
<p>{{ t.prompt }}</p>
<small
>费用 ¥{{ t.spent }} / 预算 ¥{{ t.budget }} ·
{{ t.step_count }} 轮</small
>
</button>
<div v-if="!tasks.length" class="empty">尚无开发任务</div>
</div>
</section>
</div>
<section v-if="selected" class="panel table-panel">
<div class="panel-heading">
<div>
<h3>任务日志 · {{ labels[selected.status] }}</h3>
<p>当前消费 ¥{{ selected.spent }} / 预算 ¥{{ selected.budget }}</p>
<p v-if="selected.status === 'QUEUED'">
当前排队第 {{ position(selected.id) || "—" }} 位<span
v-if="selected.paid_priority"
>
· 已购买优先权(独立计费)</span
>
</p>
</div>
<div class="table-actions">
<button
v-if="
selected.status === 'QUEUED' &&
!selected.paid_priority &&
queue.config.priority_enabled
"
class="primary"
:disabled="busy || !execution.ready"
@click="buyPriority"
>
¥{{ queue.config.priority_price }} 购买优先权
</button>
<button
v-if="['QUEUED', 'RUNNING'].includes(selected.status)"
class="secondary"
:disabled="busy"
@click="action('pause')"
>
暂停</button
><button
v-if="selected.status === 'PAUSED'"
class="primary"
:disabled="busy || !execution.ready"
@click="action('resume')"
>
继续</button
><button
v-if="['QUEUED', 'RUNNING', 'PAUSED'].includes(selected.status)"
class="secondary"
:disabled="busy"
@click="action('cancel')"
>
取消
</button>
</div>
</div>
<div v-if="selected.error" class="alert info">{{ selected.error }}</div>
<div class="event-log">
<div v-for="e in events" :key="e.id">
<small
>{{ new Date(e.created_at).toLocaleTimeString() }} ·
{{ e.event }}</small
>
<pre>{{ e.detail }}</pre>
</div>
<p v-if="!events.length" class="empty">等待任务事件</p>
</div>
</section>
<section class="panel form-panel">
<div class="panel-heading">
<h3>项目文件与版本</h3>
<button
class="secondary"
:disabled="busy || !form.projectId"
@click="download"
>
下载源码 ZIP
</button>
</div>
<div class="toolbar">
<select v-model="form.projectId">
<option v-for="p in projects" :key="p.id" :value="p.id">
{{ p.name }}
</option></select
><input
v-model="filePath"
placeholder="相对目录,例如 src"
aria-label="目录路径"
/><button
class="secondary"
:disabled="!form.projectId || fileBusy || !execution.filesConfigured"
@click="list"
>
{{ fileBusy ? "读取中…" : "刷新目录" }}</button
><button
class="secondary"
:disabled="!form.projectId"
@click="
filePath = '.';
list();
"
>
根目录
</button>
</div>
<div class="two-columns">
<div class="file-tree">
<button
v-for="f in files"
:key="f.name"
class="file-entry"
@click="openFile(f)"
>
{{ f.directory ? "▸" : "·" }} {{ f.name
}}{{ f.symlink ? "(符号链接)" : "" }}
</button>
<p v-if="fileBusy" class="muted">正在读取工作区文件…</p>
<p v-else-if="fileError" class="alert error">{{ fileError }}</p>
<p v-else-if="!files.length" class="muted">
{{
fileLoaded
? "当前目录没有文件。AI 尚未写入源码时,这里会保持为空;任务有费用记录不代表已经生成代码。"
: "选择项目后自动读取真实工作区文件。"
}}
</p>
</div>
<div>
<label class="muted"
>文件路径<input
v-model="editingPath"
placeholder="新建文件路径,例如 src/main.ts" /></label
><textarea
v-model="content"
class="code-editor"
rows="14"
placeholder="读取或编辑项目文件"
maxlength="64000"
/><button
class="secondary"
:disabled="!editingPath || !form.projectId"
@click="saveFile"
>
保存文件
</button>
</div>
</div>
<div class="toolbar">
<button class="secondary" :disabled="!form.projectId" @click="version()">
查看版本</button
><button
class="primary"
:disabled="!form.projectId"
@click="version(true)"
>
保存 Git 版本
</button>
</div>
<div v-for="v in versions" :key="v.commit" class="version-row">
<code>{{ v.commit.slice(0, 12) }}</code> {{ v.message }}
</div>
<div class="alert info">
文件、终端和版本操作需要连接 Kubernetes Sandbox
Gateway。未配置或集群未就绪会返回真实错误,不会在控制面执行命令。
</div>
</section>
</template>