provision.service.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. import { computed, inject, Injectable, signal } from '@angular/core';
  2. import { FmodeApi } from './api/fmode-api';
  3. import { ProvisionStartResult, ProvisionStatus, ProvisionStepStatus } from './api/models';
  4. /**
  5. * 开通的六个阶段,**顺序固定**(2026-11-28)
  6. *
  7. * 与 `cloud/skills/container-provision-job/SKILL.md` 的执行步骤一一对应。
  8. * 等待页按这个顺序渲染,未到达的显示为「等待」。
  9. */
  10. const STAGE_ORDER = ['prepare', 'copy', 'configure', 'create', 'start', 'verify'] as const;
  11. type StageKey = (typeof STAGE_ORDER)[number];
  12. /** 阶段的用户可见文案(不暴露内部术语) */
  13. const STAGE_LABEL: Record<StageKey, string> = {
  14. prepare: '准备开通',
  15. copy: '准备基础内容',
  16. configure: '设置专属信息',
  17. create: '创建容器',
  18. start: '启动容器',
  19. verify: '确认可以使用',
  20. };
  21. /**
  22. * 阶段说明(用户可见,**不给内部术语**)
  23. *
  24. * 🔴 2026-11-27:原来直接渲染 Agent 写的 `step` 原文,
  25. * 用户看到的是「targetDir 已清空重建」「.env/SOUL/sessions 已配置」,
  26. * 全是技术黑话,看不懂进度到底到哪了。
  27. *
  28. * 现在用固定文案,只表达"这一阶段在做什么"。
  29. * Agent 原文仍保留在 `detail` 字段里供排查,但**不再渲染到界面**。
  30. */
  31. const STAGE_DESC: Record<StageKey, string> = {
  32. prepare: '正在准备开通所需内容',
  33. copy: '正在准备基础内容',
  34. configure: '正在保存你的专属设置',
  35. create: '正在创建容器',
  36. start: '正在启动,请稍候',
  37. verify: '正在连接平台',
  38. };
  39. /** 等待页渲染用的阶段视图 */
  40. export interface ProvisionStageView {
  41. stage: StageKey;
  42. label: string;
  43. /** `pending` = 还没到这步 */
  44. status: ProvisionStepStatus | 'pending';
  45. detail: string;
  46. /** Only shown when the executor reported a measured phase duration. */
  47. durationText: string;
  48. }
  49. /**
  50. * 进行中任务的 localStorage 键(2026-11-27)
  51. *
  52. * 入口页 `entry.ts` 也读这个键,用来把刷新后的用户送回等待页。
  53. * 抽成常量避免两处写死不同的字符串。
  54. */
  55. const ACTIVE_JOB_KEY = 'fmode_active_provision_job';
  56. const PENDING_START_PREFIX = 'fmode_pending_provision_start:';
  57. interface PendingProvisionStart {
  58. planCode: string;
  59. containerName: string;
  60. idempotencyKey: string;
  61. }
  62. /**
  63. * 容器开通服务(2026-11-25)
  64. *
  65. * ## 职责
  66. *
  67. * 把「App 里点开通」接到后端 `fmode-provisioning`,并轮询真实进度。
  68. *
  69. * ## 🔴 状态真实性(最重要的一条)
  70. *
  71. * 后端返回 `provisioning` 只代表**受理了**,不代表容器建好了。
  72. * 容器是否真的可用,**只认后端 `status` 接口的服务端核验结果**
  73. * (容器记录 + Matrix joined + 心跳新鲜三项)。
  74. *
  75. * 本服务**不自己计时、不自己猜**,后端说什么就是什么。
  76. * 主容器的自然语言回报(「建好了」)不参与判断。
  77. *
  78. * ## 轮询纪律
  79. *
  80. * 沿用 `LiveService` 的思路:只在有在途任务时轮询,任务终结立即停。
  81. * 视图层禁止自建 `setInterval`(AC-14.2)。
  82. */
  83. @Injectable({ providedIn: 'root' })
  84. export class ProvisionService {
  85. private readonly api = inject(FmodeApi);
  86. /** 当前正在跟踪的任务 */
  87. private readonly _current = signal<ProvisionStatus | null>(null);
  88. /**
  89. * 正在提交的档位(`null` = 没有)。
  90. *
  91. * 🔴 2026-11-27 修:原来是布尔 `_starting`,导致**所有卡片的按钮一起转**。
  92. * 用户点「试用」,三张卡片全变「提交中…」,看起来像全都点了。
  93. * 现在记录具体是哪个 planCode,只有那个按钮转。
  94. */
  95. private readonly _startingPlan = signal<string | null>(null);
  96. private readonly _error = signal<string | null>(null);
  97. /** 试用/入门档返回的接入提示词 */
  98. private readonly _instruction = signal<string | null>(null);
  99. readonly current = this._current.asReadonly();
  100. readonly startingPlan = this._startingPlan.asReadonly();
  101. readonly error = this._error.asReadonly();
  102. readonly instruction = this._instruction.asReadonly();
  103. private readonly _restoring = signal(false);
  104. private readonly _recoveryFailed = signal(false);
  105. readonly restoring = this._restoring.asReadonly();
  106. readonly recoveryFailed = this._recoveryFailed.asReadonly();
  107. readonly startBlocked = computed(() => this.starting() || this.isRunning() || this.restoring() || this.recoveryFailed());
  108. /** A lost start response must be resolved by a same-key retry, never a new request. */
  109. pendingStartRetryAvailable(): boolean {
  110. return this.recoveryFailed() && this.readPendingStart() !== null;
  111. }
  112. /** 是否有任何提交在进行(全局锁用) */
  113. readonly starting = computed(() => this._startingPlan() !== null);
  114. /** 指定档位是否正在提交(按钮用) */
  115. isStarting(planCode: string): boolean {
  116. return this._startingPlan() === planCode;
  117. }
  118. readonly hasJob = computed(() => this._current() !== null);
  119. readonly isRunning = computed(() => {
  120. const s = this._current()?.status;
  121. return s === 'queued' || s === 'provisioning' || s === 'verifying';
  122. });
  123. readonly isReady = computed(() => this._current()?.status === 'ready');
  124. readonly isFailed = computed(() => this._current()?.status === 'failed');
  125. /**
  126. * 失败是否值得重试。
  127. *
  128. * 🔴 后端给出 `retryable` 时以它为准:
  129. * · 通道抖动 / 阶段失败 → true(重试通常就好)
  130. * · 配额满 → false(重试也没用,应引导升级或删容器)
  131. * 后端没给(老任务)时保守地允许重试。
  132. */
  133. readonly canRetry = computed(() => {
  134. const job = this._current();
  135. if (!job || job.status !== 'failed') return false;
  136. return job.retryable !== false;
  137. });
  138. /** 面向用户的失败说明(后端已脱敏,不含内部术语) */
  139. readonly failureMessage = computed(() => {
  140. const job = this._current();
  141. if (!job || job.status !== 'failed') return '';
  142. return job.error ?? '开通未完成,请稍后重试。';
  143. });
  144. /**
  145. * 主容器的**真实执行进度**(来自 Agent 写进 FmodeProvisionStep 的记录)。
  146. *
  147. * 🔴 这是「用户能看到的真实进展」,不是估算、不是计时器。
  148. * 主容器每进入/完成一个阶段就写一条,我们直接读。
  149. * 它不写库时这里是空字符串(降级为按 status 的笼统文案)。
  150. */
  151. readonly progressText = computed(() => {
  152. const job = this._current();
  153. if (!job) return '';
  154. const step = job.currentStep;
  155. const stage = step?.stage;
  156. if (!stage || !STAGE_ORDER.includes(stage as StageKey)) return '';
  157. const key = stage as StageKey;
  158. switch (step?.status) {
  159. case 'ok': return `${STAGE_LABEL[key]}已完成`;
  160. case 'failed':
  161. /*
  162. * 🔴 区分「任务失败」与「阶段瞬时失败」(2026-12-02 用户实测反馈)。
  163. *
  164. * 任务整体已失败 → 优先用云函数的 userMessage(job.error,
  165. * FAIL 文案表 fmode-provisioning.js),不再拼「X遇到问题」;
  166. * 任务仍在推进(verify 阶段有重试/复跑)→ 如实说明在自动重试,
  167. * 不要把一次瞬时失败渲染成「确认可以使用遇到问题」这种终态观感。
  168. */
  169. if (job.status === 'failed') return job.error || `${STAGE_LABEL[key]}遇到问题`;
  170. return `${STAGE_LABEL[key]}:未一次通过,正在自动重试`;
  171. case 'warn': return `${STAGE_LABEL[key]}正在继续处理`;
  172. default: return STAGE_DESC[key];
  173. }
  174. });
  175. /** 已完成的阶段数(用于进度条) */
  176. readonly completedStages = computed(() => {
  177. return this.stageList().filter((stage) => stage.status === 'ok').length;
  178. });
  179. /** 面向用户的友好状态文案 —— 有真实进度时优先显示真实进度 */
  180. readonly statusText = computed(() => {
  181. const job = this._current();
  182. if (!job) return '';
  183. const progress = this.progressText();
  184. switch (job.status) {
  185. case 'queued':
  186. return '等待开通';
  187. case 'provisioning':
  188. return progress || '正在开通';
  189. case 'verifying':
  190. return progress || '即将就绪';
  191. case 'ready':
  192. return '已就绪';
  193. case 'failed':
  194. return '开通失败';
  195. default:
  196. return '未知状态';
  197. }
  198. });
  199. private timer: ReturnType<typeof setTimeout> | null = null;
  200. private progressVersion = 0;
  201. private pendingStartStorageKey(): string | null {
  202. try {
  203. const userId = (JSON.parse(localStorage.getItem('fmode_me') || 'null') as { id?: string } | null)?.id;
  204. return userId ? PENDING_START_PREFIX + userId : null;
  205. } catch { return null; }
  206. }
  207. private readPendingStart(): PendingProvisionStart | null {
  208. const key = this.pendingStartStorageKey();
  209. if (!key) return null;
  210. try {
  211. const value = localStorage.getItem(key);
  212. if (!value) return null;
  213. const parsed = JSON.parse(value) as PendingProvisionStart;
  214. return parsed.planCode && parsed.containerName && parsed.idempotencyKey ? parsed : null;
  215. } catch { return null; }
  216. }
  217. private writePendingStart(value: PendingProvisionStart): boolean {
  218. const key = this.pendingStartStorageKey();
  219. if (!key) return false;
  220. try { localStorage.setItem(key, JSON.stringify(value)); return true; }
  221. catch { return false; }
  222. }
  223. private clearPendingStart(): void {
  224. const key = this.pendingStartStorageKey();
  225. if (!key) return;
  226. try { localStorage.removeItem(key); } catch { /* Storage failure leaves duplicate protection unavailable. */ }
  227. }
  228. /** 套餐页重新打开时找回服务端任务;核对失败不能当作没有在途任务。 */
  229. async restorePending(): Promise<void> {
  230. if (this.restoring() || this.starting()) return;
  231. const version = ++this.progressVersion;
  232. this.stopPolling();
  233. this._restoring.set(true);
  234. this._recoveryFailed.set(false);
  235. this._error.set(null);
  236. try {
  237. const jobs = await this.api.listProvisions();
  238. if (version !== this.progressVersion) return;
  239. const pending = jobs.filter(job => ['queued', 'provisioning', 'verifying'].includes(job.status));
  240. const persisted = ProvisionService.readPersistedJobId();
  241. const intent = this.readPendingStart();
  242. const job = intent
  243. ? jobs.find(candidate => candidate.idempotencyKey === intent.idempotencyKey)
  244. : pending.find(candidate => candidate.jobId === persisted) ?? pending[0];
  245. if (job) {
  246. const current = await this.api.fetchProvisionStatus(job.jobId);
  247. if (version !== this.progressVersion) return;
  248. if (current.jobId !== job.jobId) throw new Error('返回的开通任务不一致,请重新检查');
  249. this._current.set(current);
  250. this.clearPendingStart();
  251. this._recoveryFailed.set(false);
  252. this._error.set(null);
  253. if (['queued', 'provisioning', 'verifying'].includes(current.status)) {
  254. this.persistJobId(current.jobId);
  255. this.schedulePoll();
  256. } else {
  257. this.stopPolling();
  258. this.persistJobId(null);
  259. }
  260. } else {
  261. this.stopPolling();
  262. if (intent) {
  263. this._recoveryFailed.set(true);
  264. this._error.set('暂时无法确认原开通请求,请继续查看原申请。');
  265. return;
  266. }
  267. this._recoveryFailed.set(false);
  268. // 列表已证实没有在途任务,不能继续显示内存里的旧进行中状态。
  269. const previous = this._current();
  270. this._current.set(jobs.find(job => job.jobId === (persisted || previous?.jobId)) ?? null);
  271. this.persistJobId(null);
  272. }
  273. } catch (e) {
  274. if (version !== this.progressVersion) return;
  275. this._recoveryFailed.set(true);
  276. this._error.set(e instanceof Error ? e.message : '暂时无法核实已有开通任务,请重新检查');
  277. } finally {
  278. this._restoring.set(false);
  279. }
  280. }
  281. /**
  282. * 发起开通。
  283. *
  284. * @returns `onboarding` 时把提示词写进 `instruction()`;`provision` 时开始轮询
  285. */
  286. /**
  287. * 重新获取本地容器的接入提示词(2026-12-03)。
  288. *
  289. * 云函数 `start` 的 onboarding 分支按 `user + name` **幂等复用**记录,
  290. * 不发工单、不碰 R730。所以这里可以绕过「开通队列」那套防重入逻辑:
  291. * 与 `start()` 的区别是不写 pending、不置 starting(不会和真正的开通互相干扰),
  292. * 只把结果写进 `instruction()` 供容器设置页展示。已过期的试用由云函数拒绝。
  293. */
  294. async reissueInstruction(agent: { name: string; planCode?: string }): Promise<string | null> {
  295. const planCode = agent.planCode === 'starter' ? 'starter' : 'trial';
  296. try {
  297. const result = await this.api.startProvision({
  298. planCode,
  299. containerName: agent.name,
  300. idempotencyKey: `reissue-${Date.now()}`,
  301. });
  302. if (result?.mode === 'onboarding' && result.instruction) {
  303. this._instruction.set(result.instruction);
  304. this._error.set(null);
  305. return result.instruction;
  306. }
  307. this._error.set(result?.message ?? '暂时无法生成接入提示词');
  308. return null;
  309. } catch (e) {
  310. this._error.set(e instanceof Error ? e.message : '暂时无法生成接入提示词');
  311. return null;
  312. }
  313. }
  314. async start(planCode: string, containerName: string): Promise<ProvisionStartResult | null> {
  315. /*
  316. * 🔴 防重入(2026-11-27):已在开通中时直接忽略。
  317. *
  318. * 等待页会全屏锁定,但套餐页的「开通」按钮在跳转前的几十毫秒内
  319. * 仍可能被连点。忽略而不是报错 —— 用户本意就是「开一次」。
  320. */
  321. if (this.startBlocked()) return null;
  322. const pending = this.readPendingStart();
  323. if (pending) {
  324. this._recoveryFailed.set(true);
  325. this._error.set(pending.planCode === planCode && pending.containerName === containerName
  326. ? '原开通请求的结果尚未确认,请先核对或安全重试原申请。'
  327. : '已有开通请求的结果尚未确认,请先恢复原任务。');
  328. return null;
  329. }
  330. const request = {
  331. planCode,
  332. containerName,
  333. idempotencyKey: `${planCode}-${Date.now()}`,
  334. };
  335. if (!this.writePendingStart(request)) {
  336. this._recoveryFailed.set(true);
  337. this._error.set('无法安全保存开通请求,请检查设备存储后重试。');
  338. return null;
  339. }
  340. return this.submitStart(request);
  341. }
  342. /** Resume the exact original request after a lost response, reusing its server idempotency key. */
  343. async retryPendingStart(): Promise<ProvisionStartResult | null> {
  344. const request = this.readPendingStart();
  345. if (!request || this.starting() || this.restoring()) return null;
  346. return this.submitStart(request);
  347. }
  348. private async submitStart(request: PendingProvisionStart): Promise<ProvisionStartResult | null> {
  349. const { planCode, containerName, idempotencyKey } = request;
  350. if (this.starting()) return null;
  351. this._startingPlan.set(planCode);
  352. this._error.set(null);
  353. /*
  354. * 🔴 不清 `_instruction`(2026-11-27 修)
  355. *
  356. * 原来这里 `set(null)` 会在点「进阶开通」的瞬间**清掉试用档的提示词**,
  357. * 用户手上正在复制的参数直接消失。
  358. *
  359. * 提示词和开通任务是两件独立的事:用户可以先拿提示词,
  360. * 再决定要不要开通进阶。两者可以同时存在。
  361. */
  362. try {
  363. const result = await this.api.startProvision({
  364. planCode,
  365. containerName,
  366. idempotencyKey,
  367. });
  368. if (result.mode === 'onboarding') {
  369. this._instruction.set(result.instruction ?? result.message ?? '');
  370. this._current.set(null);
  371. this.clearPendingStart();
  372. this._recoveryFailed.set(false);
  373. return result;
  374. }
  375. if (result.jobId) {
  376. this._current.set({
  377. jobId: result.jobId,
  378. agentId: result.agentId,
  379. planCode,
  380. status: result.status ?? 'provisioning',
  381. });
  382. // 🔴 持久化:刷新后入口页据此把用户送回等待页,而不是丢到套餐页
  383. this.persistJobId(result.jobId);
  384. this.clearPendingStart();
  385. this._recoveryFailed.set(false);
  386. this.schedulePoll();
  387. } else {
  388. this._recoveryFailed.set(true);
  389. this._error.set('暂时无法确认开通请求,请继续查看原申请。');
  390. }
  391. return result;
  392. } catch (e) {
  393. this._error.set(e instanceof Error ? e.message : '开通请求失败');
  394. // The server may already have accepted the request; keep both its key and any prior job marker.
  395. this._recoveryFailed.set(true);
  396. return null;
  397. } finally {
  398. this._startingPlan.set(null);
  399. }
  400. }
  401. /** 立即查一次状态并推进(用户点「检查进度」时调) */
  402. async refresh(): Promise<void> {
  403. if (this.restoring()) return;
  404. const job = this._current();
  405. if (!job) return;
  406. const version = ++this.progressVersion;
  407. try {
  408. const next = await this.api.fetchProvisionStatus(job.jobId);
  409. if (version !== this.progressVersion) return;
  410. this._current.set(next);
  411. // 查询成功即清掉上次的错误,否则失败态会一直粘着
  412. this._error.set(null);
  413. if (next.status === 'ready' || next.status === 'failed') {
  414. this.stopPolling();
  415. // 终态 → 清掉持久化的 jobId,入口页不再把用户送回来
  416. this.persistJobId(null);
  417. } else this.schedulePoll();
  418. } catch (e) {
  419. if (version !== this.progressVersion) return;
  420. this._error.set(e instanceof Error ? e.message : '查询失败');
  421. }
  422. }
  423. /** 重试同一任务 */
  424. async retry(): Promise<void> {
  425. const job = this._current();
  426. if (!job) return;
  427. try {
  428. await this.api.retryProvision(job.jobId);
  429. this._error.set(null);
  430. await this.refresh();
  431. } catch (e) {
  432. this._error.set(e instanceof Error ? e.message : '重试失败');
  433. }
  434. }
  435. /** 恢复一个已有任务(刷新页面后回等待页用) */
  436. async resume(jobId: string): Promise<void> {
  437. const version = ++this.progressVersion;
  438. try {
  439. const job = await this.api.fetchProvisionStatus(jobId);
  440. if (version !== this.progressVersion) return;
  441. this._current.set(job);
  442. // 恢复成功即清错,否则上一次失败的错误会一直显示
  443. this._error.set(null);
  444. if (job.status === 'ready' || job.status === 'failed') {
  445. this.persistJobId(null);
  446. } else {
  447. this.persistJobId(jobId);
  448. this.schedulePoll();
  449. }
  450. } catch (e) {
  451. if (version !== this.progressVersion) return;
  452. this._error.set(e instanceof Error ? e.message : '任务恢复失败');
  453. }
  454. }
  455. /**
  456. * 等待页专用:从 URL 的 jobId 恢复并开始轮询。
  457. *
  458. * 与 `resume()` 的区别:本方法是**幂等**的 —— 已经跟踪同一个 job 时不再重复请求,
  459. * 避免等待页 `ngOnInit` 和路由复用各触发一次。
  460. *
  461. * @param force `true` 时强制重拉(用户点「重新加载」用)。
  462. * 🔴 不加这个参数的话,失败后 `_current` 仍是旧值,
  463. * 幂等判断会直接 return,用户点重试没有任何反应。
  464. */
  465. async resumeFromUrl(jobId: string, opts?: { force?: boolean }): Promise<void> {
  466. if (!jobId) return;
  467. if (!opts?.force && this._current()?.jobId === jobId) {
  468. if (this.isRunning()) this.schedulePoll();
  469. return;
  470. }
  471. await this.resume(jobId);
  472. }
  473. // ---------- jobId 持久化 ----------
  474. /**
  475. * 🔴 把进行中的 jobId 写进 localStorage(2026-11-27)
  476. *
  477. * 为什么:`_current` 是内存 signal,**刷新就没了**。
  478. * 用户在等待页按 F5,入口页会跳 `/mobile/messages` → 被门禁拦回 `/plans`,
  479. * 用户以为「开通任务丢了」。
  480. *
  481. * 存了之后,入口页能在跳转前把用户送回 `/provision?jobId=xxx`。
  482. * 任务终结(ready/failed)时清掉,避免下次登录被莫名送回等待页。
  483. */
  484. private persistJobId(jobId: string | null): void {
  485. try {
  486. if (jobId) localStorage.setItem(ACTIVE_JOB_KEY, jobId);
  487. else localStorage.removeItem(ACTIVE_JOB_KEY);
  488. } catch {
  489. // 隐私模式 / 存储满:持久化失败不影响主流程
  490. }
  491. }
  492. /** 读持久化的 jobId(入口页用) */
  493. static readPersistedJobId(): string | null {
  494. try {
  495. return localStorage.getItem(ACTIVE_JOB_KEY);
  496. } catch {
  497. return null;
  498. }
  499. }
  500. /** 清持久化的 jobId(任务已终结时用) */
  501. static clearPersistedJobId(): void {
  502. try {
  503. localStorage.removeItem(ACTIVE_JOB_KEY);
  504. } catch {
  505. /* 隐私模式:忽略 */
  506. }
  507. }
  508. /**
  509. * 查询某个 job 是否仍在进行(入口页用)。
  510. *
  511. * 🔴 为什么入口页不能只看 localStorage 里"有没有 jobId":
  512. * 任务早就 ready 了但没清干净时,用户每次打开 App 都被送回等待页,
  513. * 看到的却是「已完成」—— 表现为「容器开通成功了却还在开通页」。
  514. *
  515. * 查询失败按「未运行」处理:宁可让用户进主界面,也不要卡在等待页。
  516. */
  517. static async isJobRunning(api: FmodeApi, jobId: string): Promise<boolean> {
  518. try {
  519. const s = await api.fetchProvisionStatus(jobId);
  520. return s.status === 'queued' || s.status === 'provisioning' || s.status === 'verifying';
  521. } catch {
  522. return false;
  523. }
  524. }
  525. /**
  526. * 是否处于「锁定态」:开通进行中。
  527. *
  528. * 🔴 语义:为 true 时**不允许用户离开等待页**。
  529. * 与 `isRunning()` 同义,单独命名是为了让调用处读起来像业务意图。
  530. */
  531. readonly isLocked = computed(() => this.isRunning());
  532. /**
  533. * 六个阶段的固定展示顺序(等待页渲染用)。
  534. *
  535. * 不直接用后端返回的 `steps`,因为:
  536. * · 后端可能只写了前 3 条,后 2 条要显示为「等待」占位
  537. * · 顺序必须稳定,不能按到达顺序跳
  538. */
  539. /**
  540. * 是否已拿到真实的阶段数据(等待页骨架态判断用)。
  541. *
  542. * 🔴 为什么需要:`stageList()` **永远返回 6 项**(固定顺序,没到的显示 pending),
  543. * 所以不能靠 `stageList().length` 判断有没有数据。
  544. * 刚进页面时全是 pending → 显示骨架更诚实,比 5 个空圆圈好看。
  545. */
  546. readonly hasStepData = computed(() => {
  547. const steps = this._current()?.steps ?? [];
  548. return steps.length > 0;
  549. });
  550. readonly stageList = computed<ProvisionStageView[]>(() => {
  551. const steps = this._current()?.steps ?? [];
  552. return STAGE_ORDER.map((stage) => {
  553. const hit = steps.filter((s) => s.stage === stage);
  554. /*
  555. * 🔴 取**最后一条**记录,但要注意 Agent 写入顺序不总是可靠的。
  556. *
  557. * 实测(2026-11-27):同一阶段可能先写 `verify/ok` 再写 `verify/running`,
  558. * 按 createdAt 排最后一条会是 running —— 界面看起来"完成的阶段又回去了"。
  559. *
  560. * 因此:**只要出现过 ok,就判定该阶段已完成**(完成是不可逆的)。
  561. */
  562. const hasOk = hit.some((s) => s.status === 'ok');
  563. const last = hit.length ? hit[hit.length - 1] : null;
  564. const status = hasOk ? 'ok' : ((last?.status ?? 'pending') as ProvisionStageView['status']);
  565. const measured = [...hit].reverse().find((s) => typeof s.elapsedSec === 'number' && s.elapsedSec > 0);
  566. const runningAt = status === 'running' && last?.at ? Date.parse(last.at) : NaN;
  567. const runningSec = Number.isFinite(runningAt)
  568. ? Math.max(0, Math.floor((Date.now() - runningAt) / 1000))
  569. : 0;
  570. return {
  571. stage,
  572. label: STAGE_LABEL[stage],
  573. status,
  574. // 用户可见文案用固定描述;Agent 原文不展示
  575. detail: status === 'pending' ? '' : STAGE_DESC[stage],
  576. durationText: measured
  577. ? `本阶段用时 ${formatDuration(measured.elapsedSec!)}`
  578. : runningSec > 0
  579. ? `本阶段已进行 ${formatDuration(runningSec)}`
  580. : '',
  581. };
  582. });
  583. });
  584. /** 按服务端任务创建时间显示真实等待时长,不推测剩余时间。 */
  585. readonly elapsedText = computed(() => {
  586. const created = this._current()?.createdAt;
  587. if (!created) return '';
  588. const createdAt = new Date(created).getTime();
  589. if (!Number.isFinite(createdAt)) return '';
  590. const elapsedSec = Math.max(0, Math.floor((Date.now() - createdAt) / 1000));
  591. return elapsedSec < 60
  592. ? `已等待 ${elapsedSec} 秒`
  593. : `已等待 ${Math.floor(elapsedSec / 60)} 分钟`;
  594. });
  595. /** 已耗时分钟数(长任务提示用) */
  596. readonly elapsedMin = computed(() => {
  597. const created = this._current()?.createdAt;
  598. if (!created) return 0;
  599. const ms = Date.now() - new Date(created).getTime();
  600. return Number.isFinite(ms) ? Math.floor(ms / 60000) : 0;
  601. });
  602. /** 清空当前任务(如从失败态开始新一次开通) */
  603. clear(): void {
  604. this.progressVersion++;
  605. this.stopPolling();
  606. this._current.set(null);
  607. this._error.set(null);
  608. this._instruction.set(null);
  609. this._recoveryFailed.set(false);
  610. }
  611. // ---------- 轮询 ----------
  612. private schedulePoll(): void {
  613. this.stopPolling();
  614. // 12 秒一次:容器创建通常几分钟,这个频率够用且不至于打爆入口层
  615. this.timer = setTimeout(() => {
  616. this.timer = null;
  617. void this.refresh();
  618. }, 12_000);
  619. }
  620. private stopPolling(): void {
  621. if (this.timer) {
  622. clearTimeout(this.timer);
  623. this.timer = null;
  624. }
  625. }
  626. }
  627. function formatDuration(seconds: number): string {
  628. if (seconds < 60) return `${seconds} 秒`;
  629. const minutes = Math.floor(seconds / 60);
  630. const remainder = seconds % 60;
  631. return remainder ? `${minutes} 分 ${remainder} 秒` : `${minutes} 分钟`;
  632. }