File size: 64,787 Bytes
caf8059
 
 
 
 
5ca3c16
 
 
caf8059
 
 
5ca3c16
 
caf8059
 
 
 
 
 
 
 
 
8f4045a
caf8059
 
8f4045a
 
 
 
 
 
caf8059
115b94d
caf8059
 
 
 
 
 
 
 
 
5ca3c16
 
 
caf8059
 
5ca3c16
caf8059
 
 
 
 
 
5ca3c16
 
 
 
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115b94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caf8059
 
 
 
 
 
 
 
 
 
 
 
5ca3c16
 
 
115b94d
8f4045a
5ca3c16
 
 
 
 
 
 
 
 
caf8059
 
 
 
 
 
 
 
 
8f4045a
 
115b94d
 
 
 
 
 
 
 
 
 
 
8f4045a
 
115b94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caf8059
115b94d
caf8059
8f4045a
115b94d
 
8f4045a
 
caf8059
115b94d
 
 
8f4045a
caf8059
115b94d
caf8059
 
 
 
 
 
 
 
8f4045a
caf8059
 
 
 
 
115b94d
 
 
8f4045a
5ca3c16
115b94d
caf8059
 
 
 
 
5ca3c16
 
115b94d
caf8059
115b94d
8f4045a
caf8059
 
115b94d
 
5ca3c16
caf8059
115b94d
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115b94d
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
8f4045a
caf8059
 
 
8f4045a
 
 
caf8059
 
 
8f4045a
 
caf8059
 
 
 
 
 
 
5ca3c16
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ca3c16
 
 
caf8059
5ca3c16
caf8059
 
8f4045a
caf8059
5ca3c16
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ca3c16
 
 
caf8059
 
 
 
 
8f4045a
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// API bridge for the existing conversational workbench; no replacement shell.
export const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
export let session = null;
export let scenarios = [];
export let skills = [];
export let modelCatalog = {models:[]};
export let productSkills = [];
export const skillIcon = kind => ({business:'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 21V5h10v16M14 10h6v11M8 9h2m-2 4h2m-2 4h2M2 21h20"/></svg>',web:'<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="2" y="4" width="20" height="16" rx="3"/><path d="M2 9h20M9 12l-3 3 3 3m6-6 3 3-3 3"/></svg>',pdf:'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14 2H5v20h14V7zM14 2v6h5M8 12h8m-8 4h8m-8 3h5"/></svg>'}[kind]||'');
let epoch = 0, selectedSkill = () => {}, openDetails = () => {};
let currentDelivery = null;
export const developmentPresets = [
  {id:'business-app',name:'开发 · Java 业务应用(ERP模板)',knowledge:'erp'},
  {id:'webapp',name:'开发 · 网页应用(计算器模板)',knowledge:'java-basics'},
  {id:'pdf',name:'开发 · PDF 读取与解析',knowledge:'java-integration'}
];
// The authoritative brief is delivered by the backend and archived with the run.
export const javaDevelopmentPrompt = scenario => scenarios.find(s=>s.id===scenario)?.requirement || '';
export const businessPresets = [
  {id:'erp-order-assistant',scenario:'erp',name:'ERP 订单助手',base:'erp',description:'采购订单查询、收货登记与状态复查',prompt:'查询最新完成的3笔采购订单,哪些仍未付款?'},
  {id:'wms-stock-assistant',scenario:'wms',name:'WMS 库存助手',base:'wms',description:'库存查询、出入库登记与数量复查',prompt:'查询SKU-DEMO-001的库存,然后登记入库5件并复查'},
  {id:'equipment-workorder-assistant',scenario:'equipment',name:'设备工单助手',base:'equipment',description:'工单查询、开始处理、完工与状态复查',prompt:'查询WO-DEMO-001工单,开始处理并复查状态'}
];
export async function api(path, body, method = body === undefined ? 'GET' : 'POST', releaseWait = 0) {
  const response = await fetch(path, {method, credentials:'same-origin', headers:{'Content-Type':'application/json', ...(session?.csrf ? {'X-CSRF-Token':session.csrf} : {})}, ...(body === undefined ? {} : {body:JSON.stringify(body)})});
  const result = await response.json();
  if (!response.ok) {
    if(path==='/api/preview'&&method==='POST'&&result.code==='SANDBOX_RELEASING'&&releaseWait<6){
      const owner=session?.actor?.user_id;await new Promise(resolve=>setTimeout(resolve,2000));
      if(session?.actor?.user_id!==owner)throw Error('会话已切换,请从当前用户的工程重新打开。');
      return api(path,body,method,releaseWait+1);
    }
    const error=new Error(`${result.message || '请求失败'} (${result.code || response.status})`);
    error.status=response.status;error.code=result.code;error.details=result.details;throw error;
  }
  return result;
}
export async function authenticate(username) {
  dismiss();
  await api('/api/session/login',{username,password:'VibeCoding@2026'});
  const nextSession = await api('/api/session');
  const nextScenarios = await api('/api/scenarios');
  const nextSkills = await api('/api/java-skills');
  const nextModels = await api('/api/models');
  const library = await api('/api/skill-library');
  session=nextSession;scenarios=nextScenarios;skills=nextSkills;modelCatalog=nextModels;productSkills=library.items;
  return session;
}
export async function refreshModels(){modelCatalog=await api('/api/models');return modelCatalog;}
export async function initialize(username, onSelect, onOpenDetails) {
  selectedSkill = onSelect;openDetails=onOpenDetails||(()=>{});
  return authenticate(username);
}
export const skillOptions = () => [
  ...businessPresets.map(s => ({...s,kind:'business'})),
  // The fixed calculator scenario remains for historical examples; editable work uses webapp.
  ...scenarios.filter(s => !['calculator','erp-orders'].includes(s.id)).map(s => ({id:s.id,scenario:s.id,name:productSkills.find(p=>p.id===s.id)?.name||s.name,description:'Java17 · 独立测试 · 有界修复'})),
  ...scenarios.filter(s => s.id==='erp-orders').map(s => ({id:s.id,scenario:'business-app',name:'Java 业务应用(原ERP模板)',description:'当前需求决定业务内容'})),
  ...skills.filter(s => !['calculator','erp-orders'].includes(s.scenario)).map(s => ({...s,description:'已验证源码基线 · '+s.source_digest.slice(0,12)}))
];
export function dismiss() { ++epoch; }
function safeSource(url) { if(typeof url!=='string'||!url.trim())return null;try { const parsed=new URL(url,location.origin);return ['https:','http:'].includes(parsed.protocol) ? parsed.href : null; } catch { return null; } }
function toolEvidence(call) {
  return `<li><strong>${esc(call.name||call.tool||call.tool_name||call.method||'业务工具')}</strong> · ${esc(call.status||'已返回')}${call.elapsed_ms!==undefined?` · ${esc(call.elapsed_ms)} ms`:''}${call.record_count!==undefined?` · ${esc(call.record_count)} 条`:''}<div>${[call.transport?`传输:${call.transport}`:'',call.protocol?`协议:${call.protocol}`:'',call.request_id?`请求:${call.request_id}`:'',call.audit_id?`审计:${call.audit_id}`:''].filter(Boolean).map(esc).join(' · ')}</div>${call.result_digest?`<div class="business-digest">结果摘要:${esc(call.result_digest)}</div>`:''}</li>`;
}
const businessStatus = value => ({COMPLETED:'已完成',CLOSED:'已关闭',TO_RECEIVE:'待收货',TO_BILL:'待开票',OPEN:'待处理',IN_PROGRESS:'处理中',DONE:'已完成'}[value] || value || '—');
const displayValue = value => value === null || value === undefined ? '—' : typeof value === 'object' ? Object.values(value).filter(v=>typeof v!=='object').join(' / ') : String(value);
function rowsTable(rows,scenario) {
  if(!Array.isArray(rows)||!rows.length)return '';
  const columns = scenario==='erp'
    ? [['订单','order_no'],['供应商','supplier'],['状态','status'],['已收 / 订购','quantities'],['未付金额','outstanding_cents']]
    : scenario==='wms'
      ? [['物料','sku','sku_id','id'],['名称','name','description'],['库存','on_hand','quantity','stock_qty'],['预留','reserved','reserved_qty'],['可用','available','available_qty'],['版本','version']]
      : [['工单','work_order','work_order_no','order_no','work_order_id','id'],['设备','equipment','equipment_name','equipment_id'],['事项','title','description'],['状态','status'],['版本','version']];
  const used=columns.filter(([,key,...aliases])=>key==='quantities'||rows.some(r=>[key,...aliases].some(k=>r[k]!==undefined)));
  return `<div class="business-table-scroll"><table class="business-table"><thead><tr>${used.map(([title])=>`<th scope="col">${esc(title)}</th>`).join('')}</tr></thead><tbody>${rows.map(row=>`<tr>${used.map(([,key,...aliases])=>{

    let value=[key,...aliases].map(k=>row[k]).find(v=>v!==undefined);

    if(key==='status')value=businessStatus(value);

    if(key==='quantities')value=`${row.received_qty ?? '—'} / ${row.ordered_qty ?? '—'}`;

    if(key==='outstanding_cents')value=Number.isFinite(Number(value)) ? `¥${(Number(value)/100).toFixed(2)}` : '—';

    return `<td>${esc(displayValue(value))}</td>`;

  }).join('')}</tr>`).join('')}</tbody></table></div>`;
}
export function businessText(result) {
  const records=result.records||result.orders||[];
  return [result.answer||'已读取本地演示知识库。',...records.map(r=>[r.order_no||r.sku||r.work_order||r.work_order_no||r.id,r.status?businessStatus(r.status):r.quantity!==undefined?`库存 ${r.quantity}`:'',r.outstanding_cents===undefined?'':`未付金额 ¥${(r.outstanding_cents/100).toFixed(2)}`].filter(Boolean).join(' · '))].join('\n');
}
export function renderBusinessMessage(result,index,actionState={},resetState={}) {
  const scenario=result.scenario||'erp', preset=businessPresets.find(p=>p.scenario===scenario), records=result.records||result.orders||[];
  const steps=(result.steps||[]).map(step=>typeof step==='string'?step:[step.role,step.title,step.description,step.instruction].filter(Boolean).join(':'));
  const diagnoses=(result.diagnosis||[]).filter(d=>d.actions?.length);
  const action=result.action;
  const before=result.before ? (Array.isArray(result.before)?result.before:[result.before]) : [];
  const readback=result.readback ? (Array.isArray(result.readback)?result.readback:[result.readback]) : [];
  const calls=result.tool_calls||[];
  const suggestions=result.suggestions||(!action&&scenario==='erp' ? ['查询PO-2026-1003,登记剩余收货并复查状态'] : []);
  const reset=`<details class="business-reset"><summary>重复演示</summary><p>仅重置当前登录用户的${esc(preset?.name||'当前场景')}演示数据,保留操作记录。</p><button type="button" class="drawer-button" data-business-reset="${index}" data-business-scenario="${esc(scenario)}" ${['submitting','completed'].includes(resetState.status)?'disabled':''}>${resetState.status==='completed'?'已重置 · 结果见下方':resetState.status==='submitting'?'正在重置…':resetState.status==='unknown'?'核对上次重置结果':'重置本场景演示数据'}</button>${resetState.error?`<p class="business-error" role="status">${esc(resetState.error)}</p>`:''}</details>`;
  return `<section class="business-result" aria-label="${esc(preset?.name||'业务助手')}结果"><div class="business-origin"><span>本地演示知识库</span><span>${esc(preset?.name||'业务助手')}</span></div><p class="business-answer">${esc(result.answer||'已完成本次查询。')}</p>${rowsTable(records,scenario)}${diagnoses.length?`<ul class="business-diagnosis">${diagnoses.map(d=>`<li><strong>${esc(d.order_no)}</strong> · ${esc(d.actions.join(' '))}</li>`).join('')}</ul>`:''}${result.before&&result.readback?`<details class="business-evidence"><summary>查看本次操作前后与回读记录</summary><p>操作前</p>${rowsTable(before,scenario)}<p>写入后重新读取</p>${rowsTable(readback,scenario)}</details>`:''}${steps.length?`<details class="business-procedure"><summary>相关操作工序</summary><ol>${steps.map(step=>`<li>${esc(step)}</li>`).join('')}</ol></details>`:''}${action?`<div class="business-action"><strong>${esc(action.label||'确认登记')}</strong><p>${esc(action.entity_id||action.order_no||'')}${action.parameters?.quantity!==undefined||action.quantity!==undefined ? ` · 数量 ${esc(action.parameters?.quantity??action.quantity)}` : ''} · 将更新本地演示数据并重新查询</p><button type="button" class="drawer-button" data-business-confirm="${index}" ${actionState.status==='submitting'||actionState.status==='completed'?'disabled':''}>${actionState.status==='completed'?'已登记 · 结果见下方':actionState.status==='submitting'?'正在登记并回读…':actionState.status==='unknown'?'核对上次登记结果':esc(action.label||'确认登记')}</button>${actionState.error?`<p class="business-error" role="status">${esc(actionState.error)}</p>`:''}</div>`:''}${suggestions.length?`<div class="business-followups">${suggestions.map(prompt=>`<button type="button" class="drawer-button" data-business-prompt="${esc(typeof prompt==='string'?prompt:prompt.question)}" data-business-scenario="${esc(scenario)}">${esc(typeof prompt==='string'?prompt:prompt.label||prompt.question)}</button>`).join('')}</div>`:''}<details class="business-evidence"><summary>知识依据与工具调用证据${calls.length?` · ${calls.length} 次`:''}</summary><p>知识版本:${esc(result.knowledge_version||'本地演示数据')}<br>查询记录:${esc(result.audit_id||result.request_id||'—')}</p>${calls.length?`<ol>${calls.map(toolEvidence).join('')}</ol>`:''}${(result.citations||[]).map(c=>{const url=safeSource(c.url);return `<p>${url?`<a href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(c.title||c.id)}</a>`:esc(c.title||c.id)}${c.version?` · ${esc(c.version)}`:''}${c.text?`<br>${esc(c.text)}`:''}</p>`;}).join('')}</details><div class="business-development"><button type="button" class="drawer-button" data-develop-scenario="${esc(scenario)}">基于此场景开发 Java ${scenario==='erp'?'网站':'服务'}</button><small>打开开发对话并填入详细需求,确认后开始生成代码。</small></div>${reset}</section>`;
}
export const statusText = value => ({waiting_limit:'已安全暂停',waiting_approval:'等待下一步确认',waiting_budget:'等待预算批准',started:'开始',waiting:'等待确认',queued:'排队中',working:'执行中',verified:'技术通过 · 待验收',unknown:'结果未知 · 不自动重放',failed:'失败',cancelled:'已取消',starting:'沙箱启动中',ready:'运行中',closed:'已关闭',running:'模型回复中',completed:'已完成',rejected:'模型拒绝'}[value] || value);
const readableStage=value=>String(value||'').replace(/sandbox_environment/g,'隔离环境启动').replace(/sandbox_build/g,'Java 编译').replace(/sandbox_test/g,'独立接口测试').replace(/sandbox_preview/g,'运行回执核验').replace(/resource_queue/g,'资源排队').replace(/\bstart\b/g,'接收开发需求').replace(/\bbuild\b/g,'隔离编译').replace(/\btest\b/g,'独立测试');

export function renderScope(scope,index,error='',busy=false){
  const c=scope.card,items=values=>`<ul>${values.map(v=>`<li>${esc(v)}</li>`).join('')}</ul>`;
  return `<article class="delivery-card scope-card" aria-label="首版范围卡" data-scope-id="${esc(scope.id)}"><strong>${scope.base_run?'新版本范围与验收确认':'首版范围卡'} · 第 ${esc(scope.version)} 版</strong>

    <p>尚未发起模型调用。${scope.base_run?'这是基于原任务的新一轮,可能新增费用;原需求、失败、用量和验收记录保持原样。':'一句话需求不会自动扩展为完整系统。确认前保持等待,不会因没有回复而开始。'}</p>

    <p><b>我理解的问题:</b>${esc(c.problem)}</p><p><b>首版功能:</b>${esc((c.objects||[]).join('、'))}</p>${items(c.functions)}

    ${c.explicit_features?.length?`<p>原文明确要求保留:${esc(c.explicit_features.join('、'))}</p>`:''}

    <p><b>暂时不做:</b>${esc(c.excluded.join('、')||'不额外加入原文以外的功能')}</p><p><b>待确认假设:</b></p>${items(c.assumptions)}

    <p><b>怎样验收:</b></p>${items(c.acceptance)}${c.questions.length?`<p><b>会改变设计的问题(可补充后再开始):</b></p>${items(c.questions)}`:''}

    ${scope.base_run?`<p>原任务:${esc(scope.base_run)}。本轮受影响测试:${esc(scope.affected_tests.join('、'))}。需要先说明新增或缩小哪些范围,再确认新基线。</p>`:''}

    <p>${esc(c.implementation_policy)};知识库规则仅作候选。</p>

    ${c.phases?.length>1?`<p><b>本轮分期方案:</b></p>${items(c.phases.map((phase,n)=>`第 ${n+1} 阶段:${phase.join('、')}`))}<p>本次仅批准第1阶段,其余需求保留在后续计划,不删除、不自动执行。</p>`:''}

    ${c.deferred_acceptance?.length?`<p><b>后续阶段保留的验收:</b></p>${items(c.deferred_acceptance)}<p>这些要求仍保留在原需求,未执行前不算通过。</p>`:''}

    ${c.budget_estimate?`<p><b>预算判断:</b>原需求预计 ${esc(c.budget_estimate.original_estimated_tokens)} Token;本方案预计 ${esc(c.budget_estimate.estimated_tokens)} Token;任务预算 ${esc(c.budget_estimate.task_token_limit)} Token,规划阈值 ${esc(c.budget_estimate.planning_allowance)} Token,保留 ${esc(c.budget_estimate.reserve_percent)}% 余量。${c.budget_estimate.fits?(c.execution_mode==='original'?'预算可覆盖,保留原需求全部功能。':'原方案超出规划阈值或你已主动调整范围,请确认本轮差异及保留的后续需求。'):'当前预算连本轮方案也无法覆盖,请调整需求或申请预算,尚未调用模型。'}这是后端规则估算,不是实际 Token 或完成保证;执行前仍校验阶段上下文与剩余预算。</p>`:''}

    ${c.resource_budget?`<p><b>本阶段预算:</b>最多 ${esc(c.resource_budget.max_model_calls)} 次实际模型请求(含重试和切换),${esc(c.resource_budget.max_tokens)} Token 累计输入输出;最多 ${esc(c.resource_budget.max_repairs)} 轮自动修复,活动执行 ${esc(c.resource_budget.max_seconds)} 秒。预算不足时参考 ${esc(c.resource_budget.max_features)} 个功能、${esc(c.resource_budget.max_acceptance)} 个验收点分期,预算足够时不强行缩减。阶段上下文:设计 ${esc(c.resource_budget.design_context)}、生成 ${esc(c.resource_budget.code_context)}、修复 ${esc(c.resource_budget.repair_context)} Token;对应输出预留上限 ${esc(c.resource_budget.design_output)} / ${esc(c.resource_budget.code_output)} / ${esc(c.resource_budget.repair_output)}。估算不代表实际扣费,无可靠价格时不显示人民币。${esc(c.phase_rule)}</p>`:''}

    <label for="scope-supplement-${index}">补充或调整本轮需求</label><textarea id="scope-supplement-${index}" rows="3" maxlength="3000" placeholder="只补充会改变本轮设计的内容;原需求会保留"></textarea>

    ${error?`<p role="status">${esc(error)}</p>`:''}<div class="runtime-actions"><button class="drawer-button" data-scope-start="${index}" ${busy||c.can_start===false||(scope.base_run&&!scope.supplements.length)?'disabled':''}>${c.execution_mode==='adjusted'?'按修改后的方案执行':'按原需求执行'}</button><button class="drawer-button" data-scope-focus="${index}">继续补充需求</button><button class="drawer-button" data-scope-update="${index}" ${busy?'disabled':''}>提交补充并更新范围卡</button></div>

    ${c.can_start===false?'<p>请先补充业务对象、核心操作或重要权限规则,不能通过开始按钮跳过。</p>':''}<p>批准只限当前版本;开始后将冻结需求并调用所选模型,可能新增用量,仍受任务预算约束。</p></article>`;
}
export function jobText(job) {
  const evidence = job.evidence?.manifest;
  return `${statusText(job.status)}\n任务:${job.id}\n阶段:${job.cursor ?? '—'}/${job.stages?.length ?? '—'};模型修复 ${job.repairs ?? 0} 次;模型调用 ${job.model_calls?.length ?? 0} 次${job.error ? '\n原因:'+job.error : ''}${evidence ? '\n源码摘要:'+evidence.source.source_digest+'\n测试和 Java Web 预览已通过。可在当前对话查看修改文件、设计文档、下载制品或打开网站预览。人工验收尚未完成。' : ''}`;
}
function eventTime(value) {
  if(value===undefined||value===null||value==='')return '未提供时间';
  const date=new Date(typeof value==='number'&&value<1e12?value*1000:value);
  return Number.isNaN(date.valueOf())?String(value):date.toLocaleString('zh-CN',{timeZone:'Asia/Ulaanbaatar',hour12:false});
}
function diagnosticText(value) {
  return typeof value==='string'?value:JSON.stringify(value,null,2);
}
const duration=seconds=>{const n=Math.max(0,Math.floor(Number(seconds)||0));return n<60?`${n} 秒`:`${Math.floor(n/60)} 分 ${n%60} 秒`;};
export function renderPendingMessage(job,active,error='') {
  const p=job?.progress||{},observed=job?.observed_at||active.startedAt;
  const title=error?'状态读取中断,正在重连':readableStage(p.headline)||(active.kind==='java'?'正在提交开发任务':active.kind==='business-action'?'正在登记并回读':'正在等待服务端响应');
  return `<div class="loading-reply waiting-feedback" role="status" data-pending-clock data-started="${esc(active.startedAt)}" data-observed="${esc(observed)}" data-elapsed="${esc(p.elapsed_seconds||0)}" data-stage-elapsed="${esc(p.stage_elapsed_seconds||0)}" data-job="${!!job}" data-queued="${job?.status==='queued'}"><strong><span class="execution-pulse" aria-hidden="true"></span> ${esc(title)}</strong><span data-pending-time aria-live="off"></span><span>${esc(error||p.detail||'请求已提交,等待真实结果;请勿重复发送。')}</span><small data-pending-freshness aria-live="off"></small><small data-pending-delay></small></div>`;
}
export function tickJobClocks() {
  for(const line of document.querySelectorAll('[data-pending-clock]')){
    const delta=Math.max(0,(Date.now()-Number(line.dataset.observed))/1000),hasJob=line.dataset.job==='true';
    const elapsed=hasJob?Number(line.dataset.elapsed)+delta:(Date.now()-Number(line.dataset.started))/1000;
    line.querySelector('[data-pending-time]').textContent=`已等待 ${duration(elapsed)}`;
    line.querySelector('[data-pending-freshness]').textContent=hasJob?`最近读取:${duration(delta)}前 · 自动核对同一任务,不会重复提交`:'正在等待服务端首次回执;尚不能确认执行结果';
    line.querySelector('[data-pending-delay]').textContent=delta>12&&hasJob?'状态连接暂未更新,正在重连;这不代表任务已失败。':Number(line.dataset.stageElapsed)+delta>=60?(line.dataset.queued==='true'?'仍在排队等待执行器,本任务尚未开始编译。':'当前步骤等待较久,尚未收到完成结果;可展开上方执行记录查看最近心跳。'):'';
  }
  for(const card of document.querySelectorAll('[data-job-clock]')){
    const active=card.dataset.active==='true',delta=active?Math.max(0,(Date.now()-Number(card.dataset.observed))/1000):0;
    card.querySelector('[data-total-time]').textContent=duration(Number(card.dataset.elapsed)+delta);
    card.querySelector('[data-stage-time]').textContent=duration(Number(card.dataset.stageElapsed)+delta);
    const fresh=card.querySelector('[data-freshness]');
    fresh.textContent=active?(delta>12?`已 ${duration(delta)} 未刷新,正在核对连接;尚不能确认新结果。`:`${duration(delta)}前读取服务端状态`):'结果已保存,可随时重新查看';
    card.classList.toggle('connection-stale',active&&delta>12);
  }
}
function failureReason(job){
  const check=job.failure_details?.budget_check;
  const reasons={JAVA_TEST_FAILED:'独立接口或业务断言未通过。原源码和诊断已保存,不能凭页面能打开就算通过。',MODEL_CALL_BUDGET_EXCEEDED:'实际模型请求次数达到本轮上限;未发起下一次调用。',RUN_TIME_BUDGET_EXCEEDED:'本轮活动执行时间不足,下一阶段尚未启动。',RESOURCE_QUEUE_TIMEOUT:'等待实例执行位超时,尚未启动新工作。',SANDBOX_BOOT_FAILED:'隔离环境启动失败,生成代码未运行;需核对环境,不触发代码盲修。',ISOLATION_UNAVAILABLE:'隔离执行环境不可用,未回退宿主执行;需先修复环境。',MODEL_QUOTA_REJECTED:'供应商配额拒绝;这与平台阶段上限、任务总预算不同,尚不能据此推断账户余额。',MODEL_OUTPUT_LIMIT:'输出空间不足以返回完整结果;已保存本次用量,停止无效重复生成。',STAGE_CONTEXT_BUDGET_EXCEEDED:'当前阶段上限不足,本次调用尚未发起。可核对本次限额调整申请;完整需求与日志保留。',TASK_TOKEN_BUDGET_EXCEEDED:'任务剩余 Token 额度不足。查看已结算与预留用量;不会自动增加预算。',MODEL_CONTEXT_LIMIT_EXCEEDED:'超过已配置的模型上下文窗口。请缩小相关上下文。',CONTEXT_BUDGET_EXCEEDED:'旧版本预算预检拒绝;需核对阶段上下文和任务剩余额度,不能据此认定总预算耗尽。',JAVA_BUILD_FAILED:'Java 编译失败。展开真实诊断查看文件、行号及错误;保留失败源码进行定向修复。'};
  const transport={CONNECT_TIMEOUT:'连接建立超时',READ_TIMEOUT:'等待读取供应商响应超时',WRITE_TIMEOUT:'发送模型请求超时',POOL_TIMEOUT:'等待连接资源超时',CONNECTION_INTERRUPTED:'与供应商的连接中断',REMOTE_PROTOCOL_ERROR:'供应商连接协议中断'};
  const reason=job.failure_details?.reason_code||job.model_calls?.findLast(c=>c.state==='unknown')?.metadata?.reason_code;
  if(job.status==='unknown'&&transport[reason])return `${transport[reason]}(${reason})。结果与费用仍需核对,未自动重放。`;
  const detail=reasons[job.error]||job.error;
  if(job.error==='BUDGET_DECLINED')return '你已拒绝追加预算,任务保持停止;原额度未改变,记录已保留。';
  if(job.error==='MODEL_OUTPUT_INVALID')return '模型响应未符合输出契约,候选未应用。已结算用量与结构诊断已保留;没有通过验证的完整制品。';
  if(['MODEL_QUOTA_REJECTED','MODEL_REQUEST_REJECTED'].includes(job.error)){
    const call=job.model_calls?.findLast(c=>c.state==='rejected'),m=call?.metadata||{};
    return `供应商拒绝了模型请求${m.http_status?'(HTTP '+m.http_status+')':''}${m.provider_error_code?',原因代码:'+m.provider_error_code:''}。这不是任务上下文预算不足。请核对该模型的开通权限、免费额度或计费设置;未生成源码时尚未开始编译测试。当前任务已停止,未自动重新调用;开启付费或更换调用须明确确认。`;
  }
  return `${check?'失败阶段:'+check.stage+';':''}${detail||''}`;
}
export function renderBudgetApproval(job,index,modal=false,busy=false){
  const b=job.budget_request||job.limit_request;
  const saved='原需求、调用记录和暂停原因'+(job.source?'、候选源码':'')+(job.diagnostics?'、诊断':'');
  if(job.status==='waiting_limit'&&!b)return `<article class="delivery-card" data-budget-card><strong>任务已安全暂停</strong><p>停止原因:${esc(job.error)}。后台没有新工作继续启动。${esc(saved)}已保存。环境错误或硬上限不能靠增加模型预算解决;需要核对环境或安排新的范围版本,原失败不会变成通过。</p></article>`;
  if(!b)return '';
  if(b.mode==='overdraft')return `<article class="delivery-card budget-approval" data-budget-card="${esc(job.id)}" aria-label="先行执行追加预算"><strong>已先行执行一步 · 申请追加 12,000 Token</strong><p>当前状态:${esc(statusText(job.status))}。先行调用:${esc(readableStage(b.stage))},模型 ${esc(b.model)};这是先行执行产生的申请,尚未补入正式预算。未决定前不叠加新的模型请求。</p><p>正式总预算 ${esc(b.before.max_tokens)} → ${esc(b.after.max_tokens)} Token;本次请求输出预留 ${esc(b.output_reservation)} Token,输入输出安全预留合计 ${esc(b.planned_call_reservation)}。阶段上限 ${esc(b.stage_before)} → ${esc(b.stage_limit)};调用次数 ${esc(b.before.max_model_calls)} → ${esc(b.after.max_model_calls)};修复次数 ${esc(b.before.max_repairs)} → ${esc(b.after.max_repairs)}。</p><p>已结算 ${esc(job.usage?.settled_tokens??0)} Token;未结算预留 ${esc(job.usage?.reserved_tokens??0)} Token。超出正式预算的已结算或预留 ${esc(job.usage?.overdraft_tokens??0)} Token;预留不是实际扣费。已发请求可能已计费,拒绝不能撤回已消耗用量;拒绝会中断后续执行。批准只补入上述预算,不重复已发请求,未知结果仍不重放。</p>${job.simulation?'<p>受控模拟验证,不连接供应商,不代表真实应用生成。</p>':''}${job.jobError?`<p role="alert">${esc(job.jobError)}</p>`:''}<button type="button" class="drawer-button" data-job-budget="${index}" data-budget-digest="${esc(b.digest)}" data-accept="true" ${busy?'disabled':''}>批准追加并继续</button><button type="button" class="drawer-button" data-job-budget="${index}" data-budget-digest="${esc(b.digest)}" data-accept="false" ${busy?'disabled':''}>拒绝追加并中断任务</button>${modal?'':`<button type="button" class="drawer-button" data-budget-open="${index}">打开预算确认框</button>`}</article>`;
  if(b.limit_kind)return `<article class="delivery-card" data-budget-card aria-label="当前任务资源限额审批"><strong>本轮资源限额确认 · 任务保持暂停</strong><p>停止步骤:${esc(readableStage(b.resume_step))};原因:${esc(b.reason)}。后台已停止推进,${esc(saved)}已保存。</p><p>恢复同一任务的上述步骤,模型:${esc(b.model)};路由 ${esc(Object.entries(b.routes||{}).map(([stage,model])=>stage+' → '+model).join(';'))}。批准后可能新增模型费用;不是重放未知调用。</p><p>实际调用 ${esc(b.calls)} 次;已结算 ${esc(b.settled_tokens)} Token;未结算预留 ${esc(b.reserved_tokens)} Token;活动耗时 ${esc(b.active_seconds.toFixed(2))} 秒;修复 ${esc(b.repairs)} 轮。</p><p>本次限额前 → 后:模型调用 ${esc(b.before.max_model_calls)} → ${esc(b.after.max_model_calls)};总 Token ${esc(b.before.max_tokens)} → ${esc(b.after.max_tokens)};修复轮数 ${esc(b.before.max_repairs)} → ${esc(b.after.max_repairs)};活动时间 ${esc(b.before.max_seconds)} → ${esc(b.after.max_seconds)} 秒。</p><p>仅批准当前任务本次增加,账本不会重置;阶段上下文、模型硬限制、供应商余额仍分别校验。无可靠价格不估填人民币。版本 ${esc(b.task_revision)},过期须重新确认。</p>${job.jobError?`<p role="status">${esc(job.jobError)}</p>`:''}<button class="drawer-button" data-job-budget="${index}" data-accept="true" data-budget-digest="${esc(b.digest)}" ${busy?'disabled':''}>批准本次增加并继续</button><button class="drawer-button" data-job-budget="${index}" data-accept="false" data-budget-digest="${esc(b.digest)}" ${busy?'disabled':''}>暂不继续</button>${modal?'':`<button class="drawer-button" data-budget-open="${index}">打开预算确认框</button>`}</article>`;
  const valid=Number.isSafeInteger(b.task_revision)&&typeof b.model==='string'&&Number.isSafeInteger(b.input_bound);
  const heading=b.token_increment===12000?'申请追加 12,000 Token':({stage:'仅调整当前阶段上限',task:'调整当前任务总预算',stage_and_task:'调整当前阶段上限和任务总预算'}[b.adjustment]||'预算申请需重新核对');
  const n=value=>Number.isSafeInteger(value)?esc(value):'未提供';
  return `<article class="delivery-card budget-approval" data-budget-card="${esc(job.id)}" aria-label="当前任务预算审批"><strong>任务已暂停 · ${esc(heading)}</strong>${job.simulation?'<p>受控模拟:调用和用量为测试夹具,不连接供应商;上下文填充仅用于触发预算边界。</p>':''}<p>当前阶段:${esc(b.stage_title||b.stage)}。暂停原因:${esc(failureReason(job))}</p>

    <p><b>恢复步骤:</b>${esc(b.resume_step||b.stage)};<b>拟使用模型:</b>${esc(b.model||'需后端重新核对')}。</p>

    <dl class="budget-numbers"><div><dt>阶段上限(前 → 后)</dt><dd>${n(b.current_stage_limit)} → ${n(b.stage_limit)} Token;调整 +${n(b.stage_delta)}</dd></div>

    <div><dt>预计输入(安全上界)</dt><dd>${n(b.input_bound)} Token,包含 ${n(b.safety_tokens)} 安全余量</dd></div><div><dt>拟预留输出</dt><dd>${n(b.output_reservation)} Token</dd></div><div><dt>本次调用拟预留合计</dt><dd>${n(b.planned_call_reservation)} Token(估算,非实际扣费)</dd></div>

    <div><dt>任务总预算(前 → 后)</dt><dd>${n(b.current_task_limit)} → ${n(b.task_limit)} Token;调整 +${n(b.task_delta)}</dd></div><div><dt>任务当前剩余</dt><dd>${n(b.task_remaining)} Token;已结算 ${n(b.settled_tokens)},未结算预留 ${n(b.reserved_tokens)}</dd></div>

    <div><dt>模型上下文硬限制</dt><dd>${b.model_context_limit_verified?n(b.model_context_limit)+' Token(不能通过审批突破)':'未配置可核实数值;不代表无限,仍执行网关硬保护'}</dd></div><div><dt>供应商余额</dt><dd>未查询,不属于本次预算调整</dd></div></dl>

    <p>${b.token_increment===12000?'本次只追加 12,000 Token,保留完整需求和页面;批准后检查并继续下一步。若仍不足,会再次申请,不会自动增加。':b.adjustment==='stage'?'任务总预算足够,本次不增加总预算,无需据此充值。':'仅在明确批准后调整上列任务预算,不会更改供应商账户或自动充值。'}建议值由后端预检计算,不是实际消耗。</p>

    <p>仅展示 Token;暂无可靠价格依据,不估填人民币费用。仅授权当前任务本次调整,不更改全局默认限制;调用上限仍为 ${n(b.model_call_limit)} 次。未知调用、模型硬限制和环境故障不能靠批准重试。</p>

    <p>申请版本 ${n(b.task_revision)};有效至 ${b.expires_at?esc(eventTime(b.expires_at)):'需重新核对'}。过期或任务变化后须重新计算并再次确认。</p>

    ${job.jobError?`<p role="alert">${esc(job.jobError)}</p>`:''}

    <div class="budget-actions"><button type="button" class="drawer-button" data-job-budget="${index}" data-budget-digest="${esc(b.digest)}" data-accept="true" ${busy?'disabled':''}>${valid?'批准本次调整并继续':'重新计算预算申请(不调用模型)'}</button><button type="button" class="drawer-button" data-job-budget="${index}" data-budget-digest="${esc(b.digest)}" data-accept="false" ${busy?'disabled':''}>暂不继续</button>${!modal?`<button type="button" class="drawer-button" data-budget-open="${index}">打开预算确认框</button>`:''}</div></article>`;
}
function tokenUsageDetails(calls){
  if(!calls.length)return '';
  const purposes={chat:'普通对话',design:'需求分析与技术设计',code:'生成源码',repair:'依据编译或测试诊断修复',diagnose:'定位失败原因',code_review:'代码检视'};
  const count=n=>Number.isSafeInteger(n)&&n>=0?esc(n):'未提供';
  return `<details class="development-diagnostics token-usage-details" data-detail="token-usage"><summary>展开 Token 消耗明细 · 按模型与用途</summary><div class="token-usage-scroll"><table><thead><tr><th>用途 / 模型</th><th>输入</th><th>输出</th><th>已结算合计</th><th>估算预留</th></tr></thead><tbody>${calls.map((c,i)=>{

    const m=c.metadata||{},settled=c.state==='settled',pending=['unknown','reserved'].includes(c.state);

    return `<tr><td>第${i+1}次 · ${esc(purposes[m.stage]||m.stage||'历史调用')} ${m.retry_of?'(已知输出恢复)':''}<br><small>${esc(m.model||c.provider)} · ${esc({settled:'已结算',rejected:'供应商拒绝',unknown:'结果未知',reserved:'等待回执'}[c.state]||c.state)}</small></td><td>${settled?count(m.input_tokens):pending?'待核对':'未提供'}</td><td>${settled?count(m.output_tokens):pending?'待核对':'未提供'}</td><td>${pending?'未结算':count(c.charged)}</td><td>${pending?count(c.reservation):'—'}</td></tr>`;

  }).join('')}</tbody></table></div><small>单位:Token。输入为本阶段发送的需求、接口及必要上下文;输出为返回的方案或源码。缓存、思考等未单独提供,不估填,也不重复计入总量。预留是估算上界,不是实际扣费;编译和网页操作本身不产生模型 Token。</small></details>`;
}
function progressCard(job,error){
  const p=job.progress||{},active=['queued','working'].includes(job.status),verified=job.status==='verified';
  const headline=job.auto_recovery?.next_run_id?'当前候选未通过,已自动转入恢复任务':readableStage(p.headline)||(verified?'开发完成 · 技术通过':active?'正在执行,尚未结束':statusText(job.status));
  const project=job.project;
  const calls=job.model_calls||[],settled=calls.reduce((sum,c)=>sum+(c.charged||0),0),held=calls.reduce((sum,c)=>sum+(c.charged==null?c.reservation:0),0);
  const usage=job.usage;
  const stoppedStage=(job.timeline||[]).findLast(e=>e.stage===p.stage&&e.status==='started')?.title||p.stage||job.budget_request?.stage||'参见执行记录';
  return `<article class="execution-card" data-state="${esc(job.status)}" data-job-clock data-active="${active}" data-observed="${esc(job.observed_at||Date.now())}" data-elapsed="${esc(p.elapsed_seconds||0)}" data-stage-elapsed="${esc(p.stage_elapsed_seconds||0)}" role="status" aria-live="polite">

    ${active&&p.short_message?`<p class="execution-short">${esc(p.short_message)}</p>`:''}

    <strong class="execution-headline">${active?'<span class="execution-pulse" aria-hidden="true"></span>':''}${esc(headline)}</strong>

    <p class="execution-usage" aria-label="本任务实际用量">共消耗 <strong>${esc(usage?.settled_tokens??settled)}</strong> Token(已结算) · 估算预留 ${esc(usage?.reserved_tokens??held)} Token(未结算)${usage?(usage.token_limit===null?` · 不限用量 · 调用 ${esc(usage.calls)} 次`:` · 剩余 ${esc(usage.remaining_tokens)} / ${esc(usage.token_limit)} Token · 调用 ${esc(usage.calls)} / ${esc(usage.call_limit)} 次`):''}</p>
    ${tokenUsageDetails(calls)}

    ${calls.some(c=>['unknown','reserved'].includes(c.state))?'<p>实际总消耗尚未确认:以上已结算部分不包含未结算调用,不能按零费用处理。</p>':''}

    ${active||job.status==='unknown'?'<small>用量随供应商回执更新;等待期间的预留不是实际扣费。金额尚无可信账单。</small>':''}

    <p>${esc(p.detail||(active?'任务仍在执行,收到独立验证结果后显示是否通过。':'以本次运行证据为准。'))}</p>

    ${['waiting_budget','failed','unknown','cancelled'].includes(job.status)?`<p class="execution-stop-info">停止步骤:${esc(readableStage(stoppedStage))}。后台状态:${job.status==='waiting_budget'?'已暂停,等待你批准额度;没有模型调用在继续。':job.status==='unknown'?'平台不再推进此任务;供应商是否完成仍未知,不能自动重放。':'已停止推进本任务。'}已保存:原需求、调用记录${job.source?'、候选源码':''}${job.diagnostics?'、失败诊断':''}。下一步:${job.status==='waiting_budget'?'核对对话最下方预算申请,批准本次调整或暂不继续。':job.status==='unknown'?'读取原记录并核对供应商用量;独立新任务会新增调用及可能的费用。':'展开诊断与用量记录,确认后再决定是否创建关联修复任务。'}</p>`:''}

    ${job.design_summary?`<p class="execution-plan-preview"><strong>实施方案:</strong>${esc(job.design_summary.slice(0,320))}${job.design_summary.length>320?'…(展开上方实施方案查看全文)':''}</p>`:''}

    <div class="execution-times"><span>总耗时 <b data-total-time></b></span>${active?'<span>当前步骤 <b data-stage-time></b></span>':'<span hidden data-stage-time></span>'}<span data-freshness></span></div>

    ${p.last_heartbeat_at&&active?`<p class="execution-heartbeat">最近执行器心跳:${esc(eventTime(p.last_heartbeat_at))} · 等待实际结果,不代表测试通过</p>`:''}

    ${error?`<p class="development-error">${esc(error)}</p>`:''}

    ${project?`<div class="execution-project"><strong>本轮工程已建立</strong><p>${esc(project.directory)}</p><span>${esc(project.files.filter(f=>f.change!=='unchanged').length)} 个新增或修改文件</span><p>预览地址:<a href="${esc(project.preview_url)}" target="_blank" rel="noopener noreferrer">${esc(new URL(project.preview_url,location.origin).href)}</a></p></div>`:''}

    <a class="drawer-button" href="/api/jobs/${encodeURIComponent(job.id)}/record">下载本次运行记录</a>

  </article>`;
}
export function renderJobMessage(job,index,error='',confirmNew=false) {
  const timeline=Array.isArray(job.timeline)?job.timeline:[];
  const source=job.evidence?.manifest?.source||job.source;
  const test=job.evidence?.manifest?.test;
  const complete=job.status==='verified';
  const attrs=`data-kind="run" data-ref="${esc(job.id)}"`;
  return `<section class="development-result" data-run-id="${esc(job.id)}" aria-label="Java 开发进度">

    ${job.simulation?`<p class="development-meta">${job.simulation_kind==='model-only-real-sandbox'?'受控模型夹具与模拟用量,不连接供应商;构建与测试使用真实隔离执行器,结果以回执为准。':'受控模拟验收:本任务调用和用量为测试账目,不连接供应商,不代表真实生成或编译结果。'}</p>`:''}

    ${confirmNew?`<article class="delivery-card" role="group" aria-label="独立新任务费用确认"><strong>这将新建独立任务,不是恢复原调用</strong><p>将再次向模型发起调用,可能新增费用;原任务、未知结果及费用预留继续保存。是否授权?</p><button class="drawer-button" data-job-repair-confirm="${index}">确认新建并允许新增调用</button><button class="drawer-button" data-job-repair-dismiss="${index}">取消,不发起调用</button></article>`:''}

    ${complete?`<article class="result-preview-ready"><span class="result-preview-icon">✓</span><div><strong>应用已生成,可以预览</strong><p>打开实际应用并验证业务操作,工程与本轮文件在下方查看。</p></div>${previewAction(job.scenario,attrs)}</article>`:job.status==='unknown'?`<article class="result-no-preview"><strong>本次尚未生成可预览的应用</strong><p>${job.failure_category==='transport_timeout'?'模型请求传输超时,未取得可信的完整结果。':['SANDBOX_TIMEOUT','VM_RESULT_UNKNOWN'].includes(job.error)?'隔离编译与测试未取得可信的完成回执,尚无通过验证的应用。':'模型请求结果未知,尚无可信的完成制品。'}原请求与费用记录保留,不会自动重试。</p><button type="button" class="drawer-button" data-job-repair="${index}">新建独立任务(新增调用,可能计费)</button></article>`:''}

    <div class="development-heading"><strong>${esc(scenarios.find(s=>s.id===job.scenario)?.name||job.scenario)} · Java 开发</strong><span class="development-status">${job.auto_recovery?.next_run_id?'本轮失败 · 已自动转入恢复任务':esc(statusText(job.status))}</span></div>

    ${job.budget_policy?.mode==='unlimited-usage-v1'?'<p class="development-meta">本地任务不限用量,底部显示实际 Token;未知结果不重放。</p>':job.budget_policy?.mode==='one-call-overdraft-v1'?'<p class="development-meta">额度不足时先行一步并申请追加;批准补入预算,拒绝停止后续,未知结果不重放。</p>':job.auto_recovery?`<p class="development-meta">自动恢复已开启 · 本任务最多2次诊断修复,必要时额外续修1轮;原失败和费用保留,未知结果不重放。${job.auto_recovery.error?'恢复未能安排:'+esc(job.auto_recovery.error):job.auto_recovery.attempt?' 当前为最后一轮自动续修。':''}</p>`:''}
    <p class="development-meta">任务 ${esc(job.id)} · 模型调用 ${esc(job.model_calls?.length??0)} 次 · 模型修复 ${esc(job.repairs??0)} 次</p>

    ${job.model_calls?.length?`<details class="development-diagnostics" data-detail="models"><summary>本任务实际模型与用量</summary><ul>${job.model_calls.map(call=>`<li>${esc(call.metadata?.stage||'历史阶段')} · ${esc(call.metadata?.model||call.provider)} · ${esc(call.state)} · ${call.charged===null?'用量待核对':esc(call.charged)+' Token'}${call.metadata?.requested_output_tokens?` · 输出上限 ${esc(call.metadata.requested_output_tokens)}`:''}${call.metadata?.error?` · ${esc(call.metadata.error)}`:''}</li>`).join('')}</ul></details>`:''}

    ${job.evidence?.manifest?.repair_origin?`<p class="development-meta">本制品由 Codex 接管修复后独立验证。原模型任务 ${esc(job.evidence.manifest.repair_origin.generation_run)} 保留原结果。</p>`:''}

    ${job.evidence?.manifest?.continuation_origin?`<p class="development-meta">平台修复后的模型续作;原任务 ${esc(job.evidence.manifest.continuation_origin.generation_run)} 保留原结果。</p>`:''}

    ${job.recovery_of?`<p class="development-meta">依据任务 ${esc(job.recovery_of)} 继续修复;原源码、错误与用量记录保留。</p>`:''}

    ${job.design_summary?`<details class="development-diagnostics execution-plan" data-detail="plan"><summary>实施方案 · 模型已生成</summary><p>${esc(job.design_summary)}</p></details>`:''}

    ${job.failure_analysis?`<details class="development-diagnostics" data-detail="analysis"><summary>故障定位建议 · 以独立复测为准</summary><p>${esc(job.failure_analysis.summary)}</p></details>`:''}

    ${timeline.length?`<details class="development-diagnostics" data-detail="events"><summary>执行记录 · 已保存 ${esc(timeline.length)} 条 · 最新:${esc(readableStage(timeline.at(-1).title))}</summary><ol class="development-timeline">${timeline.map(event=>`<li data-stage="${esc(event.stage)}" data-status="${esc(event.status)}"><div class="development-event-heading"><strong>${esc(readableStage(event.title||event.stage))}</strong><span>${esc(event.status==='active'?'执行器心跳':statusText(event.status))}</span></div><time>${esc(eventTime(event.at))}</time>${event.detail?`<p>${esc(typeof event.detail==='string'?event.detail:diagnosticText(event.detail))}</p>`:''}</li>`).join('')}</ol></details>`:'<p class="development-meta">等待服务端执行事件。</p>'}

    ${progressCard(job,error)}

    ${job.error?`<p class="development-error" role="status">${job.error==='BUDGET_DECLINED'?'已拒绝追加,正在停止后续步骤;在途请求仍需结算:':['queued','working'].includes(job.status)?'最近一轮验证发现问题,正在修复与复测:':'本次结果:'}${esc(failureReason(job))}</p>`:''}

    ${job.budget_checks?.length?`<details class="development-diagnostics" data-detail="budget"><summary>上下文与预算分项(含输出预留)</summary><pre>${esc(JSON.stringify(job.budget_checks,null,2))}</pre></details>`:''}

    ${job.followups?.length?`<article class="delivery-card"><strong>本任务已有后续修复记录</strong><p>原结果与费用记录保留。以下读取新任务的真实代码和验证结果,不会重新调用模型。</p>${job.followups.map(next=>`<button type="button" class="drawer-button" data-job-followup="${index}" data-run-id="${esc(next.id)}">查看后续任务 · ${esc(statusText(next.status))}</button>`).join('')}</article>`:''}

    ${job.diagnostics?`<details class="development-diagnostics" data-detail="diagnostics"><summary>${complete?'修复前诊断(已保留)':'真实诊断输出'}</summary><pre>${esc(diagnosticText(job.diagnostics))}</pre></details>`:''}

    ${!complete&&source?.files?.['website/index.html']?`<article class="delivery-card"><strong>页面已生成,可先查看界面草稿</strong><p>Java 接口与业务结果仍待独立验证;草稿不连接后台,不代表测试通过。无需等待完整测试或新建沙箱。</p><a class="drawer-button" href="${esc(new URL('/draft-preview/'+encodeURIComponent(job.id)+'/',session?.preview_origin||location.origin).href)}" target="_blank" rel="noopener noreferrer">先看界面草稿(未验收)</a></article>`:''}

    <div class="runtime-actions"><a class="drawer-button" href="/api/jobs/${encodeURIComponent(job.id)}/snapshot">下载已保存内容${source?'(代码和文档)':'(需求及已有文档)'}</a><span class="development-meta">可在测试期间或中止后下载;不会重新调用模型,未验证内容会明确标记。</span></div>

    ${complete?`<article class="delivery-card"><strong>工程与测试记录</strong><p>技术测试通过,实际业务仍待验收。查看本轮修改和设计文档。</p><div class="runtime-actions">${button('查看修改文件','delivery',attrs+' data-view="files"')}${button('设计文档','delivery',attrs+' data-view="docs"')}<a class="drawer-button" href="/api/export/run/${encodeURIComponent(job.id)}">导出工程备份</a></div></article>`:source?`<div class="runtime-actions">${button('查看当前代码与文档','delivery',attrs+' data-view="files"')}<span class="development-meta">${['queued','working'].includes(job.status)?'候选源码已生成,正在等待独立验证结果。':'本轮候选未通过独立验证。'}</span></div>`:''}

    <button type="button" class="drawer-button development-refresh" data-job-refresh="${index}">重新读取任务进度</button>

    ${job.status==='failed'&&!job.resource_limits&&!['BUDGET_DECLINED','MODEL_QUOTA_REJECTED','MODEL_REQUEST_REJECTED'].includes(job.error)&&job.model_calls?.every(call=>['settled','rejected'].includes(call.state))?`<button type="button" class="drawer-button" data-job-repair="${index}">创建关联修复任务(新增调用,可能计费)</button>`:''}

  </section>`;
}
function changesLabel(file) {
  const labels={added:'新增',modified:'修改',unchanged:'未变更',deleted:'删除',generated:'生成'};
  return [labels[file.change]||file.change||'',Number.isFinite(file.additions)?`+${file.additions}`:'',Number.isFinite(file.deletions)?`−${file.deletions}`:''].filter(Boolean).join(' · ');
}
function renderDeliveryFile(index=0,view='source') {
  if(!currentDelivery)return;
  const {data,kind,reference}=currentDelivery;
  const file=data.files[index];if(!file)return;
  currentDelivery.file=index;currentDelivery.view=view;
  const isDoc=/\.(md|txt|rst)$/i.test(file.path);
  const text=view==='diff'?file.diff:file.content;
  const code=view==='diff'&&typeof text==='string'?text.split('\n').map(line=>`<span class="${line.startsWith('+')&&!line.startsWith('+++')?'diff-added':line.startsWith('-')&&!line.startsWith('---')?'diff-removed':''}">${esc(line)}</span>`).join('\n'):esc(text===undefined||text===null?(view==='diff'?'服务端未提供此文件的差异。':'此文件未提供文本内容。'):typeof text==='string'?text:JSON.stringify(text,null,2));
  const summary=typeof data.summary==='string'?data.summary:diagnosticText(data.summary||{});
  panel('本轮工程与文件变更',`<p class="delivery-summary">${esc(summary)}</p>${data.project?`<div class="execution-project"><strong>工程已保存在本机</strong><p>${esc(data.project.directory)}</p><p>预览地址:<a href="${esc(data.project.preview_url)}" target="_blank" rel="noopener noreferrer">${esc(new URL(data.project.preview_url,location.origin).href)}</a></p></div>`:''}<p class="delivery-digest">任务 ${esc(data.run_id)}<br>源码摘要 ${esc(data.source_digest||'尚未形成验证摘要')}</p>

    <div class="delivery-file-list" role="list" aria-label="交付文件">${data.files.map((item,i)=>`<button type="button" class="delivery-file${i===index?' selected':''}" data-delivery-file="${i}" role="listitem"><strong>${esc(item.path)}</strong><small>${esc(changesLabel(item))}${item.origin?` · ${esc(item.origin)}`:''}</small></button>`).join('')}</div>

    <div class="delivery-file-heading"><strong>${esc(file.path)}</strong><small>${esc(file.language||'text')} · ${esc(changesLabel(file))} · ${esc({'model-generated':'模型生成','codex-reviewed-repair':'Codex接管修复','platform-template':'平台页面模板','platform-validation':'平台验收文档','run-record':'本次需求原文','platform-contract':'固定接口与依赖契约'}[file.origin]||file.origin||'来源未标记')}</small></div>

    <div class="runtime-actions delivery-view-tabs">${button(isDoc?'查看文档':'查看内容','file-source')}${button('查看差异','file-diff')}</div>

    <pre class="delivery-code${isDoc&&view!=='diff'?' delivery-document':''}" data-delivery-content="${esc(view)}"><code>${code}</code></pre>

    ${file.sha256?`<p class="delivery-digest">文件 SHA256 ${esc(file.sha256)}</p>`:''}

    ${data.validation?`<details><summary>独立验证与运行证据</summary>${json(data.validation)}</details>`:''}

    <div class="runtime-actions">${kind==='run'?`<a class="drawer-button" href="/api/jobs/${encodeURIComponent(reference)}/snapshot">下载已保存代码和文档</a>`:''}${data.verified===false?'<span>候选尚未验证,完整运行预览等待测试;可先下载已保存内容。</span>':`${previewAction(data.scenario,`data-kind="${esc(kind)}" data-ref="${esc(reference)}"`)}<a class="drawer-button" href="/api/export/${encodeURIComponent(kind)}/${encodeURIComponent(reference)}">下载制品</a>`}</div>`);
}
export async function showDelivery(kind,reference,view='files') {
  const ticket=++epoch;openDetails();panel('读取开发交付','<p>正在读取服务端保存的源码、文档与差异…</p>');
  try {
    const data=await api(`/api/deliveries/${encodeURIComponent(kind)}/${encodeURIComponent(reference)}`);
    if(kind==='run'&&data.verified&&!data.project)data.project=await api(`/api/jobs/${encodeURIComponent(reference)}/project`,{});
    if(ticket!==epoch)return;
    if(!Array.isArray(data.files)||!data.files.length){panel('代码与文档交付','<p>此任务尚未产生可查看的文件。</p>');return;}
    currentDelivery={data,kind,reference};
    const documentIndex=view==='docs'?data.files.findIndex(file=>/\.(md|txt|rst)$/i.test(file.path)):-1;
    renderDeliveryFile(documentIndex>=0?documentIndex:0);
  } catch(error) {if(ticket===epoch)panel('交付读取未完成',`<p>${esc(error.message)}</p>`);}
}
async function showSitePreview(kind,reference,button) {
  const url=new URL('/preview-launch/?kind='+encodeURIComponent(kind)+'&reference='+encodeURIComponent(reference),session?.preview_origin||location.origin).href;
  const previewWindow=window.open(url,'_blank');if(previewWindow)previewWindow.opener=null;
  const label=button.textContent,owner=session?.actor?.user_id;button.textContent='正在打开应用…';
  try {
    // A PDF can require separate compile/test and interactive VM boots. Waiting
    // must cover the existing 15-minute lease, without restarting either VM.
    let state=await api('/api/preview',{kind,reference});const lease=state.id,started=Date.now(),deadline=started+900000;
    while(state.status==='starting'&&Date.now()<deadline){
      await new Promise(resolve=>setTimeout(resolve,2000));
      if(session?.actor?.user_id!==owner)throw Error('会话已切换,请从当前用户的工程重新打开。');
      state=await api('/api/preview?preview_id='+encodeURIComponent(lease));if(state.id!==lease)throw Error('预览已切换,请从当前工程重新打开。');
      if(state.status==='starting'&&Date.now()-started>=100000)button.textContent='正在核验预览状态';
    }
    if(state.status!=='ready')throw Error('应用预览暂未就绪,请在工作台运行记录中查看结果后重试。');
    if(!previewWindow){button.textContent='打开应用';button.title='请允许浏览器打开新窗口,然后再次点击。';return;}
  } catch(error){if(previewWindow)previewWindow.close();button.title=error.message;throw error;}
  finally{if(button.textContent!=='打开应用')button.textContent=label;}
}
function button(label, action, attrs='') { return `<button class="drawer-button" data-runtime="${action}" ${attrs}>${esc(label)}</button>`; }
function previewAction(scenario,attrs) { return ['erp','erp-orders','business-app','calculator','pdf','webapp'].includes(scenario)?button('打开网站预览','site',attrs):button('运行沙箱预览','preview',attrs); }
function artifactActions(kind, ref, scenario=ref) {
  const attrs=`data-kind="${esc(kind)}" data-ref="${esc(ref)}"`;
  return `<div class="runtime-actions">${button('查看代码与文档','delivery',attrs)}${previewAction(scenario,attrs)}${button('生成 Java 技能','generate',attrs)}<a href="/api/export/${kind}/${encodeURIComponent(ref)}">下载制品</a></div>`;
}
function json(value) { return `<pre>${esc(JSON.stringify(value,null,2))}</pre>`; }
function panel(title, html) {
  document.getElementById('drawerTitle').textContent=title;
  document.getElementById('drawerBody').innerHTML=`<section class="runtime-panel">${html}<p id="runtimeError" role="status"></p></section>`;
}
export async function show(view) {
  const business=businessPresets.find(p=>p.scenario===view);
  if(business){dismiss();selectedSkill(business.id);return;}
  const ticket=++epoch;
  panel('正在读取', '<p>正在读取当前用户的真实数据…</p>');
  try {
    if (view==='examples') {
      const library=await api('/api/skill-library');if(ticket!==epoch)return;productSkills=library.items;
      panel('Skill 工具',`<p class="skill-library-intro">三个编程 Skill,一张卡片对应一个真实工作流。选择后在原对话编辑需求并发送。</p><div class="product-skill-grid">${productSkills.map(s=>`<button class="product-skill-card" data-runtime="library-select" data-ref="${esc(s.id)}"><span class="product-skill-icon ${esc(s.icon)}">${skillIcon(s.icon)}</span><strong>${esc(s.name)}</strong><p>${esc(s.description)}</p><small>${esc(s.node_count)} 个节点 · r${esc(s.revision)}</small><span class="skill-card-select">选择并编辑需求 →</span></button>`).join('')}</div><div class="skill-library-footer"><a href="/admin/" target="_blank" rel="noopener">编辑 Skill 工作流 ↗</a>${button('工程源码基线','baselines')}</div>`);
    } else if(view==='baselines') {
      const examples=await api('/api/examples'); skills=await api('/api/java-skills'); if(ticket!==epoch)return;
      panel('工程与源码基线', `<p>各场景共用 Agent、Harness 和隔离运行链路。技术通过仍待用户验收。</p>${examples.map(e=>`<article class="resource-card"><h3>${esc(scenarios.find(s=>s.id===e.scenario)?.name||e.scenario)}</h3><p>源码 ${esc(e.evidence.manifest.source.source_digest.slice(0,16))}…</p>${e.evidence.manifest.repair_origin ? '<p>模型候选未完成;由 Codex 接管修复后独立验证通过。原失败任务与调用记录保留。</p>' : ''}${artifactActions('example',e.scenario)}</article>`).join('')}<h3>保存的工程源码基线</h3>${skills.map(s=>`<article class="resource-card"><h3>${esc(s.name)}</h3><p>${esc(s.id)}</p>${button('在当前对话选用','select',`data-ref="${s.id}"`)}${button('重新验证并预览','preview',`data-kind="skill" data-ref="${s.id}"`)}<a href="/api/java-skills/${s.id}/export">下载技能包</a></article>`).join('')||'<p>从已验证实例或任务生成技能,包含 SKILL.md、接口、源码和证据。</p>'}`);
    } else if(view==='jobs') {
      const jobs=await api('/api/jobs'); if(ticket!==epoch)return;
      panel('任务与证据', button('刷新','refresh-jobs')+jobs.map(j=>`<article class="resource-card"><h3>${esc(scenarios.find(s=>s.id===j.scenario)?.name||j.scenario)}</h3><pre>${esc(jobText(j))}</pre>${button('打开任务对话','open-job',`data-ref="${j.id}"`)}${button('读取完整证据','evidence',`data-ref="${j.id}"`)}${j.status==='verified'?artifactActions('run',j.id,j.scenario):['queued','working'].includes(j.status)?button('取消我的任务','cancel',`data-ref="${j.id}"`):''}</article>`).join('')+(jobs.length?'':'<p>当前用户尚无可见任务。选择 Skill 后在对话中提交需求。</p>'));
    } else if(view==='preview') {
      let state;try {state=await api('/api/preview');}catch(error){panel('运行沙箱',`<p>当前没有活动应用预览。</p><p>从成功任务的“打开网站预览”进入实际应用。</p>`);return;}
      if(ticket!==epoch)return;
      const pool=await api('/api/previews');
      const cards=pool.items.filter(item=>['starting','ready'].includes(item.status)).map(item=>`<article class="resource-card"><strong>${esc(scenarios.find(s=>s.id===item.scenario)?.name||item.scenario)}</strong><p>${esc(statusText(item.status))}</p><a class="drawer-button" href="${esc(item.url||new URL('/preview-launch/?kind='+encodeURIComponent(item.kind)+'&reference='+encodeURIComponent(item.reference),session.preview_origin).href)}" target="_blank" rel="noopener noreferrer">打开应用</a>${button('关闭此预览','close-preview',`data-ref="${esc(item.id)}"`)}</article>`).join('');
      const paths={erp:'/api/purchase/quote?quantity=3&unitPrice=125.50&department=sales',wms:'/api/stock?sku=DEMO',equipment:'/health'};
      panel('运行沙箱',`${cards}<p>${esc(statusText(state.status))} · ${esc(state.scenario)} · 到期自动释放</p><p>每个预览独占无网卡虚拟机;其他用户不能操作。当前支持 ${esc(pool.capacity)} 个独立应用预览,编程构建使用独立执行槽。</p>${button('刷新状态','refresh-preview')}${button('关闭我的预览','close-preview')}<form id="previewRequest" data-preview-id="${esc(state.id)}"><label>方法<select id="previewMethod"><option>GET</option><option>POST</option></select></label><label>接口路径<input id="previewPath" value="${esc(paths[state.scenario])}" maxlength="501"></label><button class="drawer-button" ${state.status==='ready'?'':'disabled'}>调用 Java 接口</button></form><div id="previewResult"></div><details><summary>隔离及验证证据</summary>${json(state)}</details>`);
      if(state.status==='starting')setTimeout(()=>{if(ticket===epoch&&!document.getElementById('drawer').hidden)show('preview');},3000);
    } else if(view==='admin') {
      const data=await api('/api/admin'); if(ticket!==epoch)return;
      panel('管理状态',`<p>配置、实际调用用量和未知结果预留。企业 SSO 及目标部署环境尚未配置。</p>${json(data)}`);
    } else if(view==='account') {
      panel('本地演示登录', '<p>保留原三用户入口,点击左下角人员即可切换。</p><p>林晓:programmer(程序员)<br>周宁:manager(管理员)<br>陈敏:tester(测试工程师)</p><p>本地演示密码:<code>VibeCoding@2026</code></p><p>这三个公开演示账号使用服务端会话与项目 ACL,只用于本机验证。既有 admin 账号未重置。</p>');
    }
  } catch(error) { if(ticket===epoch)panel('操作未完成',`<p>${esc(error.message)}</p>`); }
}
document.addEventListener('click',async event=>{
  const file=event.target.closest('[data-delivery-file]');
  if(file){renderDeliveryFile(Number(file.dataset.deliveryFile));return;}
  const b=event.target.closest('[data-runtime]');if(!b)return;
  b.disabled=true;
  try {
    const action=b.dataset.runtime;
    if(action==='delivery')await showDelivery(b.dataset.kind,b.dataset.ref,b.dataset.view||'files');
    if(action==='site')await showSitePreview(b.dataset.kind,b.dataset.ref,b);
    if(action==='file-source')renderDeliveryFile(currentDelivery?.file||0,'source');
    if(action==='file-diff')renderDeliveryFile(currentDelivery?.file||0,'diff');
    if(action==='preview'){await api('/api/preview',{kind:b.dataset.kind,reference:b.dataset.ref});await show('preview');}
    if(action==='generate'){await api('/api/java-skills',{kind:b.dataset.kind,reference:b.dataset.ref});await show('baselines');}
    if(action==='library-select'){selectedSkill(b.dataset.ref);}
    if(action==='baselines')await show('baselines');
    if(action==='select'){selectedSkill(b.dataset.ref);}
    if(action==='refresh-jobs')await show('jobs');
    if(action==='refresh-preview')await show('preview');
    if(action==='close-preview'){await api('/api/preview'+(b.dataset.ref?'?preview_id='+encodeURIComponent(b.dataset.ref):''),undefined,'DELETE');await show('preview');}
    if(action==='cancel'){await api(`/api/jobs/${b.dataset.ref}/cancel`,{});await show('jobs');}
    if(action==='open-job')document.dispatchEvent(new CustomEvent('open-recorded-job',{detail:b.dataset.ref}));
    if(action==='evidence'){const result=await api(`/api/jobs/${b.dataset.ref}`);panel('任务证据',json(result));}
  }catch(error){const out=document.getElementById('runtimeError');if(out)out.textContent=error.message;else if(b.dataset.runtime==='site'){let feedback=b.parentElement.querySelector('.preview-feedback');if(!feedback){feedback=document.createElement('p');feedback.className='preview-feedback';feedback.setAttribute('role','status');b.parentElement.append(feedback);}feedback.textContent='应用暂未打开,请稍后重试或查看运行记录。';}}
  finally{b.disabled=false;}
});
document.addEventListener('submit',async event=>{
  if(event.target.id!=='previewRequest')return;
  event.preventDefault();const b=event.target.querySelector('button');b.disabled=true;
  try {
      const r=await api('/api/preview/request',{method:document.getElementById('previewMethod').value,path:document.getElementById('previewPath').value,preview_id:event.target.dataset.previewId});
      document.getElementById('previewResult').innerHTML=json(r);
  }catch(error){document.getElementById('runtimeError').textContent=error.message;}
  finally{b.disabled=false;}
});