| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685 |
- import { computed, inject, Injectable, signal } from '@angular/core';
- import { FmodeApi } from './api/fmode-api';
- import { ProvisionStartResult, ProvisionStatus, ProvisionStepStatus } from './api/models';
- /**
- * 开通的六个阶段,**顺序固定**(2026-11-28)
- *
- * 与 `cloud/skills/container-provision-job/SKILL.md` 的执行步骤一一对应。
- * 等待页按这个顺序渲染,未到达的显示为「等待」。
- */
- const STAGE_ORDER = ['prepare', 'copy', 'configure', 'create', 'start', 'verify'] as const;
- type StageKey = (typeof STAGE_ORDER)[number];
- /** 阶段的用户可见文案(不暴露内部术语) */
- const STAGE_LABEL: Record<StageKey, string> = {
- prepare: '准备开通',
- copy: '准备基础内容',
- configure: '设置专属信息',
- create: '创建容器',
- start: '启动容器',
- verify: '确认可以使用',
- };
- /**
- * 阶段说明(用户可见,**不给内部术语**)
- *
- * 🔴 2026-11-27:原来直接渲染 Agent 写的 `step` 原文,
- * 用户看到的是「targetDir 已清空重建」「.env/SOUL/sessions 已配置」,
- * 全是技术黑话,看不懂进度到底到哪了。
- *
- * 现在用固定文案,只表达"这一阶段在做什么"。
- * Agent 原文仍保留在 `detail` 字段里供排查,但**不再渲染到界面**。
- */
- const STAGE_DESC: Record<StageKey, string> = {
- prepare: '正在准备开通所需内容',
- copy: '正在准备基础内容',
- configure: '正在保存你的专属设置',
- create: '正在创建容器',
- start: '正在启动,请稍候',
- verify: '正在连接平台',
- };
- /** 等待页渲染用的阶段视图 */
- export interface ProvisionStageView {
- stage: StageKey;
- label: string;
- /** `pending` = 还没到这步 */
- status: ProvisionStepStatus | 'pending';
- detail: string;
- /** Only shown when the executor reported a measured phase duration. */
- durationText: string;
- }
- /**
- * 进行中任务的 localStorage 键(2026-11-27)
- *
- * 入口页 `entry.ts` 也读这个键,用来把刷新后的用户送回等待页。
- * 抽成常量避免两处写死不同的字符串。
- */
- const ACTIVE_JOB_KEY = 'fmode_active_provision_job';
- const PENDING_START_PREFIX = 'fmode_pending_provision_start:';
- interface PendingProvisionStart {
- planCode: string;
- containerName: string;
- idempotencyKey: string;
- }
- /**
- * 容器开通服务(2026-11-25)
- *
- * ## 职责
- *
- * 把「App 里点开通」接到后端 `fmode-provisioning`,并轮询真实进度。
- *
- * ## 🔴 状态真实性(最重要的一条)
- *
- * 后端返回 `provisioning` 只代表**受理了**,不代表容器建好了。
- * 容器是否真的可用,**只认后端 `status` 接口的服务端核验结果**
- * (容器记录 + Matrix joined + 心跳新鲜三项)。
- *
- * 本服务**不自己计时、不自己猜**,后端说什么就是什么。
- * 主容器的自然语言回报(「建好了」)不参与判断。
- *
- * ## 轮询纪律
- *
- * 沿用 `LiveService` 的思路:只在有在途任务时轮询,任务终结立即停。
- * 视图层禁止自建 `setInterval`(AC-14.2)。
- */
- @Injectable({ providedIn: 'root' })
- export class ProvisionService {
- private readonly api = inject(FmodeApi);
- /** 当前正在跟踪的任务 */
- private readonly _current = signal<ProvisionStatus | null>(null);
- /**
- * 正在提交的档位(`null` = 没有)。
- *
- * 🔴 2026-11-27 修:原来是布尔 `_starting`,导致**所有卡片的按钮一起转**。
- * 用户点「试用」,三张卡片全变「提交中…」,看起来像全都点了。
- * 现在记录具体是哪个 planCode,只有那个按钮转。
- */
- private readonly _startingPlan = signal<string | null>(null);
- private readonly _error = signal<string | null>(null);
- /** 试用/入门档返回的接入提示词 */
- private readonly _instruction = signal<string | null>(null);
- readonly current = this._current.asReadonly();
- readonly startingPlan = this._startingPlan.asReadonly();
- readonly error = this._error.asReadonly();
- readonly instruction = this._instruction.asReadonly();
- private readonly _restoring = signal(false);
- private readonly _recoveryFailed = signal(false);
- readonly restoring = this._restoring.asReadonly();
- readonly recoveryFailed = this._recoveryFailed.asReadonly();
- readonly startBlocked = computed(() => this.starting() || this.isRunning() || this.restoring() || this.recoveryFailed());
- /** A lost start response must be resolved by a same-key retry, never a new request. */
- pendingStartRetryAvailable(): boolean {
- return this.recoveryFailed() && this.readPendingStart() !== null;
- }
- /** 是否有任何提交在进行(全局锁用) */
- readonly starting = computed(() => this._startingPlan() !== null);
- /** 指定档位是否正在提交(按钮用) */
- isStarting(planCode: string): boolean {
- return this._startingPlan() === planCode;
- }
- readonly hasJob = computed(() => this._current() !== null);
- readonly isRunning = computed(() => {
- const s = this._current()?.status;
- return s === 'queued' || s === 'provisioning' || s === 'verifying';
- });
- readonly isReady = computed(() => this._current()?.status === 'ready');
- readonly isFailed = computed(() => this._current()?.status === 'failed');
- /**
- * 失败是否值得重试。
- *
- * 🔴 后端给出 `retryable` 时以它为准:
- * · 通道抖动 / 阶段失败 → true(重试通常就好)
- * · 配额满 → false(重试也没用,应引导升级或删容器)
- * 后端没给(老任务)时保守地允许重试。
- */
- readonly canRetry = computed(() => {
- const job = this._current();
- if (!job || job.status !== 'failed') return false;
- return job.retryable !== false;
- });
- /** 面向用户的失败说明(后端已脱敏,不含内部术语) */
- readonly failureMessage = computed(() => {
- const job = this._current();
- if (!job || job.status !== 'failed') return '';
- return job.error ?? '开通未完成,请稍后重试。';
- });
- /**
- * 主容器的**真实执行进度**(来自 Agent 写进 FmodeProvisionStep 的记录)。
- *
- * 🔴 这是「用户能看到的真实进展」,不是估算、不是计时器。
- * 主容器每进入/完成一个阶段就写一条,我们直接读。
- * 它不写库时这里是空字符串(降级为按 status 的笼统文案)。
- */
- readonly progressText = computed(() => {
- const job = this._current();
- if (!job) return '';
- const step = job.currentStep;
- const stage = step?.stage;
- if (!stage || !STAGE_ORDER.includes(stage as StageKey)) return '';
- const key = stage as StageKey;
- switch (step?.status) {
- case 'ok': return `${STAGE_LABEL[key]}已完成`;
- case 'failed':
- /*
- * 🔴 区分「任务失败」与「阶段瞬时失败」(2026-12-02 用户实测反馈)。
- *
- * 任务整体已失败 → 优先用云函数的 userMessage(job.error,
- * FAIL 文案表 fmode-provisioning.js),不再拼「X遇到问题」;
- * 任务仍在推进(verify 阶段有重试/复跑)→ 如实说明在自动重试,
- * 不要把一次瞬时失败渲染成「确认可以使用遇到问题」这种终态观感。
- */
- if (job.status === 'failed') return job.error || `${STAGE_LABEL[key]}遇到问题`;
- return `${STAGE_LABEL[key]}:未一次通过,正在自动重试`;
- case 'warn': return `${STAGE_LABEL[key]}正在继续处理`;
- default: return STAGE_DESC[key];
- }
- });
- /** 已完成的阶段数(用于进度条) */
- readonly completedStages = computed(() => {
- return this.stageList().filter((stage) => stage.status === 'ok').length;
- });
- /** 面向用户的友好状态文案 —— 有真实进度时优先显示真实进度 */
- readonly statusText = computed(() => {
- const job = this._current();
- if (!job) return '';
- const progress = this.progressText();
- switch (job.status) {
- case 'queued':
- return '等待开通';
- case 'provisioning':
- return progress || '正在开通';
- case 'verifying':
- return progress || '即将就绪';
- case 'ready':
- return '已就绪';
- case 'failed':
- return '开通失败';
- default:
- return '未知状态';
- }
- });
- private timer: ReturnType<typeof setTimeout> | null = null;
- private progressVersion = 0;
- private pendingStartStorageKey(): string | null {
- try {
- const userId = (JSON.parse(localStorage.getItem('fmode_me') || 'null') as { id?: string } | null)?.id;
- return userId ? PENDING_START_PREFIX + userId : null;
- } catch { return null; }
- }
- private readPendingStart(): PendingProvisionStart | null {
- const key = this.pendingStartStorageKey();
- if (!key) return null;
- try {
- const value = localStorage.getItem(key);
- if (!value) return null;
- const parsed = JSON.parse(value) as PendingProvisionStart;
- return parsed.planCode && parsed.containerName && parsed.idempotencyKey ? parsed : null;
- } catch { return null; }
- }
- private writePendingStart(value: PendingProvisionStart): boolean {
- const key = this.pendingStartStorageKey();
- if (!key) return false;
- try { localStorage.setItem(key, JSON.stringify(value)); return true; }
- catch { return false; }
- }
- private clearPendingStart(): void {
- const key = this.pendingStartStorageKey();
- if (!key) return;
- try { localStorage.removeItem(key); } catch { /* Storage failure leaves duplicate protection unavailable. */ }
- }
- /** 套餐页重新打开时找回服务端任务;核对失败不能当作没有在途任务。 */
- async restorePending(): Promise<void> {
- if (this.restoring() || this.starting()) return;
- const version = ++this.progressVersion;
- this.stopPolling();
- this._restoring.set(true);
- this._recoveryFailed.set(false);
- this._error.set(null);
- try {
- const jobs = await this.api.listProvisions();
- if (version !== this.progressVersion) return;
- const pending = jobs.filter(job => ['queued', 'provisioning', 'verifying'].includes(job.status));
- const persisted = ProvisionService.readPersistedJobId();
- const intent = this.readPendingStart();
- const job = intent
- ? jobs.find(candidate => candidate.idempotencyKey === intent.idempotencyKey)
- : pending.find(candidate => candidate.jobId === persisted) ?? pending[0];
- if (job) {
- const current = await this.api.fetchProvisionStatus(job.jobId);
- if (version !== this.progressVersion) return;
- if (current.jobId !== job.jobId) throw new Error('返回的开通任务不一致,请重新检查');
- this._current.set(current);
- this.clearPendingStart();
- this._recoveryFailed.set(false);
- this._error.set(null);
- if (['queued', 'provisioning', 'verifying'].includes(current.status)) {
- this.persistJobId(current.jobId);
- this.schedulePoll();
- } else {
- this.stopPolling();
- this.persistJobId(null);
- }
- } else {
- this.stopPolling();
- if (intent) {
- this._recoveryFailed.set(true);
- this._error.set('暂时无法确认原开通请求,请继续查看原申请。');
- return;
- }
- this._recoveryFailed.set(false);
- // 列表已证实没有在途任务,不能继续显示内存里的旧进行中状态。
- const previous = this._current();
- this._current.set(jobs.find(job => job.jobId === (persisted || previous?.jobId)) ?? null);
- this.persistJobId(null);
- }
- } catch (e) {
- if (version !== this.progressVersion) return;
- this._recoveryFailed.set(true);
- this._error.set(e instanceof Error ? e.message : '暂时无法核实已有开通任务,请重新检查');
- } finally {
- this._restoring.set(false);
- }
- }
- /**
- * 发起开通。
- *
- * @returns `onboarding` 时把提示词写进 `instruction()`;`provision` 时开始轮询
- */
- /**
- * 重新获取本地容器的接入提示词(2026-12-03)。
- *
- * 云函数 `start` 的 onboarding 分支按 `user + name` **幂等复用**记录,
- * 不发工单、不碰 R730。所以这里可以绕过「开通队列」那套防重入逻辑:
- * 与 `start()` 的区别是不写 pending、不置 starting(不会和真正的开通互相干扰),
- * 只把结果写进 `instruction()` 供容器设置页展示。已过期的试用由云函数拒绝。
- */
- async reissueInstruction(agent: { name: string; planCode?: string }): Promise<string | null> {
- const planCode = agent.planCode === 'starter' ? 'starter' : 'trial';
- try {
- const result = await this.api.startProvision({
- planCode,
- containerName: agent.name,
- idempotencyKey: `reissue-${Date.now()}`,
- });
- if (result?.mode === 'onboarding' && result.instruction) {
- this._instruction.set(result.instruction);
- this._error.set(null);
- return result.instruction;
- }
- this._error.set(result?.message ?? '暂时无法生成接入提示词');
- return null;
- } catch (e) {
- this._error.set(e instanceof Error ? e.message : '暂时无法生成接入提示词');
- return null;
- }
- }
- async start(planCode: string, containerName: string): Promise<ProvisionStartResult | null> {
- /*
- * 🔴 防重入(2026-11-27):已在开通中时直接忽略。
- *
- * 等待页会全屏锁定,但套餐页的「开通」按钮在跳转前的几十毫秒内
- * 仍可能被连点。忽略而不是报错 —— 用户本意就是「开一次」。
- */
- if (this.startBlocked()) return null;
- const pending = this.readPendingStart();
- if (pending) {
- this._recoveryFailed.set(true);
- this._error.set(pending.planCode === planCode && pending.containerName === containerName
- ? '原开通请求的结果尚未确认,请先核对或安全重试原申请。'
- : '已有开通请求的结果尚未确认,请先恢复原任务。');
- return null;
- }
- const request = {
- planCode,
- containerName,
- idempotencyKey: `${planCode}-${Date.now()}`,
- };
- if (!this.writePendingStart(request)) {
- this._recoveryFailed.set(true);
- this._error.set('无法安全保存开通请求,请检查设备存储后重试。');
- return null;
- }
- return this.submitStart(request);
- }
- /** Resume the exact original request after a lost response, reusing its server idempotency key. */
- async retryPendingStart(): Promise<ProvisionStartResult | null> {
- const request = this.readPendingStart();
- if (!request || this.starting() || this.restoring()) return null;
- return this.submitStart(request);
- }
- private async submitStart(request: PendingProvisionStart): Promise<ProvisionStartResult | null> {
- const { planCode, containerName, idempotencyKey } = request;
- if (this.starting()) return null;
- this._startingPlan.set(planCode);
- this._error.set(null);
- /*
- * 🔴 不清 `_instruction`(2026-11-27 修)
- *
- * 原来这里 `set(null)` 会在点「进阶开通」的瞬间**清掉试用档的提示词**,
- * 用户手上正在复制的参数直接消失。
- *
- * 提示词和开通任务是两件独立的事:用户可以先拿提示词,
- * 再决定要不要开通进阶。两者可以同时存在。
- */
- try {
- const result = await this.api.startProvision({
- planCode,
- containerName,
- idempotencyKey,
- });
- if (result.mode === 'onboarding') {
- this._instruction.set(result.instruction ?? result.message ?? '');
- this._current.set(null);
- this.clearPendingStart();
- this._recoveryFailed.set(false);
- return result;
- }
- if (result.jobId) {
- this._current.set({
- jobId: result.jobId,
- agentId: result.agentId,
- planCode,
- status: result.status ?? 'provisioning',
- });
- // 🔴 持久化:刷新后入口页据此把用户送回等待页,而不是丢到套餐页
- this.persistJobId(result.jobId);
- this.clearPendingStart();
- this._recoveryFailed.set(false);
- this.schedulePoll();
- } else {
- this._recoveryFailed.set(true);
- this._error.set('暂时无法确认开通请求,请继续查看原申请。');
- }
- return result;
- } catch (e) {
- this._error.set(e instanceof Error ? e.message : '开通请求失败');
- // The server may already have accepted the request; keep both its key and any prior job marker.
- this._recoveryFailed.set(true);
- return null;
- } finally {
- this._startingPlan.set(null);
- }
- }
- /** 立即查一次状态并推进(用户点「检查进度」时调) */
- async refresh(): Promise<void> {
- if (this.restoring()) return;
- const job = this._current();
- if (!job) return;
- const version = ++this.progressVersion;
- try {
- const next = await this.api.fetchProvisionStatus(job.jobId);
- if (version !== this.progressVersion) return;
- this._current.set(next);
- // 查询成功即清掉上次的错误,否则失败态会一直粘着
- this._error.set(null);
- if (next.status === 'ready' || next.status === 'failed') {
- this.stopPolling();
- // 终态 → 清掉持久化的 jobId,入口页不再把用户送回来
- this.persistJobId(null);
- } else this.schedulePoll();
- } catch (e) {
- if (version !== this.progressVersion) return;
- this._error.set(e instanceof Error ? e.message : '查询失败');
- }
- }
- /** 重试同一任务 */
- async retry(): Promise<void> {
- const job = this._current();
- if (!job) return;
- try {
- await this.api.retryProvision(job.jobId);
- this._error.set(null);
- await this.refresh();
- } catch (e) {
- this._error.set(e instanceof Error ? e.message : '重试失败');
- }
- }
- /** 恢复一个已有任务(刷新页面后回等待页用) */
- async resume(jobId: string): Promise<void> {
- const version = ++this.progressVersion;
- try {
- const job = await this.api.fetchProvisionStatus(jobId);
- if (version !== this.progressVersion) return;
- this._current.set(job);
- // 恢复成功即清错,否则上一次失败的错误会一直显示
- this._error.set(null);
- if (job.status === 'ready' || job.status === 'failed') {
- this.persistJobId(null);
- } else {
- this.persistJobId(jobId);
- this.schedulePoll();
- }
- } catch (e) {
- if (version !== this.progressVersion) return;
- this._error.set(e instanceof Error ? e.message : '任务恢复失败');
- }
- }
- /**
- * 等待页专用:从 URL 的 jobId 恢复并开始轮询。
- *
- * 与 `resume()` 的区别:本方法是**幂等**的 —— 已经跟踪同一个 job 时不再重复请求,
- * 避免等待页 `ngOnInit` 和路由复用各触发一次。
- *
- * @param force `true` 时强制重拉(用户点「重新加载」用)。
- * 🔴 不加这个参数的话,失败后 `_current` 仍是旧值,
- * 幂等判断会直接 return,用户点重试没有任何反应。
- */
- async resumeFromUrl(jobId: string, opts?: { force?: boolean }): Promise<void> {
- if (!jobId) return;
- if (!opts?.force && this._current()?.jobId === jobId) {
- if (this.isRunning()) this.schedulePoll();
- return;
- }
- await this.resume(jobId);
- }
- // ---------- jobId 持久化 ----------
- /**
- * 🔴 把进行中的 jobId 写进 localStorage(2026-11-27)
- *
- * 为什么:`_current` 是内存 signal,**刷新就没了**。
- * 用户在等待页按 F5,入口页会跳 `/mobile/messages` → 被门禁拦回 `/plans`,
- * 用户以为「开通任务丢了」。
- *
- * 存了之后,入口页能在跳转前把用户送回 `/provision?jobId=xxx`。
- * 任务终结(ready/failed)时清掉,避免下次登录被莫名送回等待页。
- */
- private persistJobId(jobId: string | null): void {
- try {
- if (jobId) localStorage.setItem(ACTIVE_JOB_KEY, jobId);
- else localStorage.removeItem(ACTIVE_JOB_KEY);
- } catch {
- // 隐私模式 / 存储满:持久化失败不影响主流程
- }
- }
- /** 读持久化的 jobId(入口页用) */
- static readPersistedJobId(): string | null {
- try {
- return localStorage.getItem(ACTIVE_JOB_KEY);
- } catch {
- return null;
- }
- }
- /** 清持久化的 jobId(任务已终结时用) */
- static clearPersistedJobId(): void {
- try {
- localStorage.removeItem(ACTIVE_JOB_KEY);
- } catch {
- /* 隐私模式:忽略 */
- }
- }
- /**
- * 查询某个 job 是否仍在进行(入口页用)。
- *
- * 🔴 为什么入口页不能只看 localStorage 里"有没有 jobId":
- * 任务早就 ready 了但没清干净时,用户每次打开 App 都被送回等待页,
- * 看到的却是「已完成」—— 表现为「容器开通成功了却还在开通页」。
- *
- * 查询失败按「未运行」处理:宁可让用户进主界面,也不要卡在等待页。
- */
- static async isJobRunning(api: FmodeApi, jobId: string): Promise<boolean> {
- try {
- const s = await api.fetchProvisionStatus(jobId);
- return s.status === 'queued' || s.status === 'provisioning' || s.status === 'verifying';
- } catch {
- return false;
- }
- }
- /**
- * 是否处于「锁定态」:开通进行中。
- *
- * 🔴 语义:为 true 时**不允许用户离开等待页**。
- * 与 `isRunning()` 同义,单独命名是为了让调用处读起来像业务意图。
- */
- readonly isLocked = computed(() => this.isRunning());
- /**
- * 六个阶段的固定展示顺序(等待页渲染用)。
- *
- * 不直接用后端返回的 `steps`,因为:
- * · 后端可能只写了前 3 条,后 2 条要显示为「等待」占位
- * · 顺序必须稳定,不能按到达顺序跳
- */
- /**
- * 是否已拿到真实的阶段数据(等待页骨架态判断用)。
- *
- * 🔴 为什么需要:`stageList()` **永远返回 6 项**(固定顺序,没到的显示 pending),
- * 所以不能靠 `stageList().length` 判断有没有数据。
- * 刚进页面时全是 pending → 显示骨架更诚实,比 5 个空圆圈好看。
- */
- readonly hasStepData = computed(() => {
- const steps = this._current()?.steps ?? [];
- return steps.length > 0;
- });
- readonly stageList = computed<ProvisionStageView[]>(() => {
- const steps = this._current()?.steps ?? [];
- return STAGE_ORDER.map((stage) => {
- const hit = steps.filter((s) => s.stage === stage);
- /*
- * 🔴 取**最后一条**记录,但要注意 Agent 写入顺序不总是可靠的。
- *
- * 实测(2026-11-27):同一阶段可能先写 `verify/ok` 再写 `verify/running`,
- * 按 createdAt 排最后一条会是 running —— 界面看起来"完成的阶段又回去了"。
- *
- * 因此:**只要出现过 ok,就判定该阶段已完成**(完成是不可逆的)。
- */
- const hasOk = hit.some((s) => s.status === 'ok');
- const last = hit.length ? hit[hit.length - 1] : null;
- const status = hasOk ? 'ok' : ((last?.status ?? 'pending') as ProvisionStageView['status']);
- const measured = [...hit].reverse().find((s) => typeof s.elapsedSec === 'number' && s.elapsedSec > 0);
- const runningAt = status === 'running' && last?.at ? Date.parse(last.at) : NaN;
- const runningSec = Number.isFinite(runningAt)
- ? Math.max(0, Math.floor((Date.now() - runningAt) / 1000))
- : 0;
- return {
- stage,
- label: STAGE_LABEL[stage],
- status,
- // 用户可见文案用固定描述;Agent 原文不展示
- detail: status === 'pending' ? '' : STAGE_DESC[stage],
- durationText: measured
- ? `本阶段用时 ${formatDuration(measured.elapsedSec!)}`
- : runningSec > 0
- ? `本阶段已进行 ${formatDuration(runningSec)}`
- : '',
- };
- });
- });
- /** 按服务端任务创建时间显示真实等待时长,不推测剩余时间。 */
- readonly elapsedText = computed(() => {
- const created = this._current()?.createdAt;
- if (!created) return '';
- const createdAt = new Date(created).getTime();
- if (!Number.isFinite(createdAt)) return '';
- const elapsedSec = Math.max(0, Math.floor((Date.now() - createdAt) / 1000));
- return elapsedSec < 60
- ? `已等待 ${elapsedSec} 秒`
- : `已等待 ${Math.floor(elapsedSec / 60)} 分钟`;
- });
- /** 已耗时分钟数(长任务提示用) */
- readonly elapsedMin = computed(() => {
- const created = this._current()?.createdAt;
- if (!created) return 0;
- const ms = Date.now() - new Date(created).getTime();
- return Number.isFinite(ms) ? Math.floor(ms / 60000) : 0;
- });
- /** 清空当前任务(如从失败态开始新一次开通) */
- clear(): void {
- this.progressVersion++;
- this.stopPolling();
- this._current.set(null);
- this._error.set(null);
- this._instruction.set(null);
- this._recoveryFailed.set(false);
- }
- // ---------- 轮询 ----------
- private schedulePoll(): void {
- this.stopPolling();
- // 12 秒一次:容器创建通常几分钟,这个频率够用且不至于打爆入口层
- this.timer = setTimeout(() => {
- this.timer = null;
- void this.refresh();
- }, 12_000);
- }
- private stopPolling(): void {
- if (this.timer) {
- clearTimeout(this.timer);
- this.timer = null;
- }
- }
- }
- function formatDuration(seconds: number): string {
- if (seconds < 60) return `${seconds} 秒`;
- const minutes = Math.floor(seconds / 60);
- const remainder = seconds % 60;
- return remainder ? `${minutes} 分 ${remainder} 秒` : `${minutes} 分钟`;
- }
|