"use client"; import { useEffect, useRef, useState } from 'react'; import type { Change, Document, Id, Json, OperationIntent } from '@/lib/canvas-core/types'; import type { ProjectEngine } from '@/lib/canvas-runtime/workspace'; import type { RecoverySession } from '@/lib/canvas-runtime/engine'; import type { ConflictPlan, RecoveryChoice } from '@/lib/canvas-runtime/conflicts'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogTitle } from '@/components/ui/dialog'; function message(error:unknown){ const code=(error as {code?:string;message?:string})?.code??(error as Error)?.message; if(code==='recovery_waiting_for_receipts')return '还有请求正在确认。请关闭此窗口,重试同步后再处理。'; if(code==='recovery_read_behind_receipt')return '服务端读取尚未包含已确认的修改,请稍后重新检查。'; if(code?.endsWith('receipt_interpreter_unavailable')||code==='recovery_receipt_missing')return '暂时无法验证原成功回执,修改和原请求仍已保留。请稍后重试。'; if(code==='recovery_in_progress')return '上一次处理尚未结束。可先恢复编辑,再重新检查。'; if(code==='recovery_choices_incomplete')return '请为每一项修改选择处理方式。'; if(code==='stale_incarnation')return '服务端已删除或替换了这个元素。可以放弃这项本地修改。'; if(code==='operation_context_changed')return '元素所属分区已改变,请重新预览这项修改。'; if(code==='ownership_conflict')return '元素已移入其它分区,当前坐标需要重新确认,暂时无法直接保留。'; if(code==='recovery_identity_collision')return '这个身份已在服务端使用,不能覆盖另一份内容。可以放弃本地创建,或重新创建一个元素。'; if(code==='stale_endpoint')return '连线所指元素已删除或进入新的生命周期,请重新选择端点。'; if(code==='unsupported_presentation_units'||code==='invalid_presentation_units')return '这个元素的展示单位暂时无法转换,原内容已保留,请确认展示格式后重试。'; if(code==='unsupported_coordinate_path')return '这条曲线使用未知坐标格式,当前无法安全转换归属,原路径仍已保留。'; if(code==='history_replay_interpreter_unavailable'||code==='history_transition_interpreter_unavailable'||code==='operation_interpreter_unavailable')return '这份修改或恢复记录来自当前无法解析的版本,原内容和请求已保留。请更新应用后重试。'; if(code==='recovery_history_adoption_evidence_missing')return '这次恢复缺少完整历史步骤,暂时无法安全继续处理;原内容和请求已保留。'; if(code==='recovery_history_traversal_order')return '这些撤销或重做有先后顺序,不能跳过前一项继续处理后一项。请重新选择。'; if(code==='recovery_history_traversal_conflict')return '服务端内容与这项历史记录已有冲突,暂时无法安全调整撤销或重做;原内容和历史均已保留。'; if(code?.startsWith('recovery_history')||code==='recovery_record_replacement_not_supported')return '这批修改含结构或撤销操作,暂时无法自动处理。原内容和历史均已保留。'; if(code==='recovery_action_requires_new_command')return '生成任务需要重新手动发起。可以在这里放弃尚未执行的请求。'; if(code==='forbidden'||code==='unauthorized'||code==='identity_changed')return '当前账号无法读取或修改此画布,请确认权限后重试。'; return '处理未完成,当前修改仍已保留。请重试,或恢复编辑后稍后处理。'; } function PreviewValue({value}:{value:Json|undefined}){ if(value===undefined)return 未设置; const text=typeof value==='string'?value:JSON.stringify(value); return text.length>240?
{text.slice(0,240)}…(展开全文)
{text}
:{text}; } const fieldLabel=(field:string)=>({'data.title':'标题','data.text':'正文',geometry:'位置与尺寸',path:'连线路径'}[field]??(field.startsWith('data.')?'内容字段':'元素关系')); function StructureReview({change,document}:{change:Exclude;document:Document}){ const current=change.kind==='element'?document.elements.get(change.id):document.canvases.get(change.id),kind=change.kind==='element'?'元素':'分区'; const title=change.kind==='element'?(change.after?.data.title??change.before?.data.title??change.id):change.id; return
{change.after===null?'删除':change.before===null?'创建':'调整'}{kind} · {String(title)}
服务端:{current?:不存在}
本地请求:{change.after?:删除此{kind}}
; } function PlanStructureReview({plan}:{plan:ConflictPlan}){ const changes=plan.operationIds.flatMap(id=>plan.operations.get(id)!.changes),structural=changes.filter(change=>change.kind!=='field'||['ownerCanvasId','source','target','path'].includes(change.field)); if(!structural.length)return null; const elements=structural.filter(change=>change.kind==='element'&&change.after===null).length,canvases=structural.filter(change=>change.kind==='canvas'&&change.after===null).length; return
关联结构变更 {structural.length} 项 · 删除 {elements} 个元素、{canvases} 个分区(展开查看) {structural.map((change,index)=>
{change.kind==='field'?fieldLabel(change.field):change.kind==='element'?'元素':'分区'} · {change.kind==='field'?change.target.id:change.id}
修改前:
修改后:
)}
; } export function HeadlessRecoveryDialog({engine,close}:{engine:ProjectEngine;close():void}){ const owner=useRef(undefined),[session,setSession]=useState(),[records,setRecords]=useState([]); const [choices,setChoices]=useState(new Map()),[plan,setPlan]=useState(),[error,setError]=useState(''),[busy,setBusy]=useState(true),[frozen,setFrozen]=useState(false); useEffect(()=>{ let live=true; Promise.resolve().then(()=>live?engine.prepareRecovery():undefined).then(async session=>{if(!session)return;if(!live){await session.cancel();return;}owner.current=session;setSession(session);setRecords([...engine.getSnapshot().runtime.ledger.operations.values()].filter(record=>session.pendingOperationIds.includes(record.intent.id)&&record.intent.operationType!=='asset.upload').sort((a,b)=>a.intent.sequence-b.intent.sequence).map(record=>record.intent));}).catch(error=>{if(live)setError(message(error));}).finally(()=>{if(live)setBusy(false);}); return()=>{live=false;void owner.current?.cancel().catch(()=>{/* Engine retains the failed durable barrier; retry/cancelRecovery can finish it. */});}; },[engine]); async function cancel(){if(busy&&session)return;setBusy(true);try{await engine.cancelRecovery();close();}catch(error){setError(message(error));}finally{setBusy(false);}} async function apply(){if(!session||busy)return;setBusy(true);setError('');setFrozen(true);try{const result=plan?await session.resolve(plan):await session.apply();if(result.status==='rejected'){setFrozen(false);setError(message({code:result.code}));return;}close();}catch(error){setError(message(error));}finally{setBusy(false);}} const canonical=session?.canonical.document; return {if(!open)void cancel();}}>{if(busy&&session)event.preventDefault();}}> 处理同步修改 检查期间暂停编辑。逐项选择要保留的修改,预览后再应用;原内容和撤销记录会保留备份。 {busy&&!session&&

正在等待同步并读取最新内容…

} {!!session?.acknowledgedRequestIds.length&&

已找回 {session.acknowledgedRequestIds.length} 个成功回执,仅处理后续尚未同步的修改。

} {session&&records.length===0&&

没有待处理的本地修改,可以采用服务端最新内容。

} {session&&records.map((intent,index)=>
修改 {index+1}{intent.origin==='undo'?' · 未同步的撤销':intent.origin==='redo'?' · 未同步的重做':''}{intent.operationType==='run.start'?' · 尚未受理的生成':intent.operationType==='run.cancel'?' · 尚未确认的取消':''} {intent.changes.map((change,changeIndex)=>{if(change.kind!=='field')return ;const element=canonical?.elements.get(change.target.id),key=change.field.startsWith('data.')?change.field.slice(5):undefined,value=key===undefined?(element as unknown as Record|undefined)?.[change.field]:element?.data[key],proposed=plan?.document.elements.get(change.target.id),proposedValue=key===undefined?(proposed as unknown as Record|undefined)?.[change.field]:proposed?.data[key];return
{fieldLabel(change.field)}
服务端:{element?:'元素已不存在'}
本地:{change.afterPresent===false?'移除此字段':}
{plan&&
处理后:{proposed?:'元素已不存在'}
}
;})}
)} {plan&&

方案已生成:保留 {plan.audit.decisions.filter(item=>item.choice==='keep-local').length} 项,放弃 {plan.audit.decisions.filter(item=>item.choice==='discard-local').length} 项。撤销记录由 {engine.getSnapshot().history.undo.length} 项调整为 {plan.history.undo.length} 项,重做记录由 {engine.getSnapshot().history.redo.length} 项调整为 {plan.history.redo.length} 项。

} {plan&&} {error&&

{error}

} {session&&records.length>0&&} {session&&}
; }