dsh-plugin-external-session-sync 1.2.1 → 1.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -21
- package/README.md +129 -127
- package/client.js +127 -12
- package/engine.js +23 -94
- package/index.js +153 -11
- package/package.json +3 -2
- package/readers-antigravity.js +306 -0
- package/reverse.js +451 -0
- package/cleanup.js +0 -99
package/client.js
CHANGED
|
@@ -84,7 +84,6 @@ window.__ModuleLoader__.load({id:'dsh-plugin-external-session-sync',factory:(req
|
|
|
84
84
|
}
|
|
85
85
|
return h('button',{type:'button',style:button,'data-testid':'dsh-archive-old',disabled:busy,title:`归档 ${DSH_ARCHIVE_MONTHS} 个月前的 DSH 会话(置顶跳过)`,onClick:run},busy?'归档中…':'旧会话归档',wide?null:null);
|
|
86
86
|
}
|
|
87
|
-
const DELETE_CONFIRM = '删除后无法恢复,也没有备份。确定继续?';
|
|
88
87
|
/** Footer action: permanently delete the payload of archived DSH sessions. */
|
|
89
88
|
function DeleteArchivedFooterButton({wide}) {
|
|
90
89
|
const [busy,setBusy]=React.useState(false);
|
|
@@ -119,17 +118,22 @@ window.__ModuleLoader__.load({id:'dsh-plugin-external-session-sync',factory:(req
|
|
|
119
118
|
}
|
|
120
119
|
return h('button',{type:'button',style:button,'data-testid':'dsh-delete-archived',disabled:busy,title:'永久删除已归档会话的正文与存档(不可恢复)',onClick:run},busy?'删除中…':'删除已归档');
|
|
121
120
|
}
|
|
122
|
-
function Panel({useTabInfo,useWorkspaces,main=false}) {
|
|
121
|
+
function Panel({useTabInfo,useWorkspaces,useSessions,main=false}) {
|
|
123
122
|
const info=typeof useTabInfo==='function'?useTabInfo():null;
|
|
124
123
|
// Never read a service off the Context unless it is injected: Cordis throws for a
|
|
125
124
|
// service the plugin did not declare, and that throw unmounts the whole panel.
|
|
126
125
|
const useWs=typeof useWorkspaces==='function'?useWorkspaces:useNoWorkspaceState;
|
|
127
126
|
const workspaceState=useWs(state=>state) || EMPTY_WORKSPACE_STATE;
|
|
127
|
+
const useSess=typeof useSessions==='function'?useSessions:useNoSessions;
|
|
128
|
+
const sessionState=useSess(state=>state) || EMPTY_SESSIONS;
|
|
128
129
|
const pinnedSessionIds=new Set(workspaceState.pinnedSessionIds || []);
|
|
129
130
|
const archivedSessionIds=new Set(workspaceState.archivedSessionIds || []);
|
|
130
131
|
const root=React.useRef(null),request=React.useRef(0),catalogRequest=React.useRef(0),mounted=React.useRef(true);
|
|
131
132
|
const [catalog,setCatalog]=React.useState(null),[selected,setSelected]=React.useState(null),[conversation,setConversation]=React.useState(null);
|
|
132
133
|
const [source,setSource]=React.useState('codex'),[query,setQuery]=React.useState(''),[busy,setBusy]=React.useState(false),[loading,setLoading]=React.useState(false),[refreshing,setRefreshing]=React.useState(true),[notice,setNotice]=React.useState('正在读取会话列表…'),[error,setError]=React.useState(''),[archiveMonths,setArchiveMonths]=React.useState('1');
|
|
134
|
+
const [tab,setTab]=React.useState('in');
|
|
135
|
+
const [reverseRows,setReverseRows]=React.useState(null),[reverseBusy,setReverseBusy]=React.useState(false),[reverseNotice,setReverseNotice]=React.useState('');
|
|
136
|
+
const [reverseGroups,setReverseGroups]=React.useState([]),[reverseTarget,setReverseTarget]=React.useState(null),[reversePreview,setReversePreview]=React.useState([]);
|
|
133
137
|
async function load() {
|
|
134
138
|
const token=++catalogRequest.current;setRefreshing(true);setError('');
|
|
135
139
|
try {
|
|
@@ -146,7 +150,7 @@ window.__ModuleLoader__.load({id:'dsh-plugin-external-session-sync',factory:(req
|
|
|
146
150
|
const data=await load();if(!mounted.current)return;
|
|
147
151
|
const oldKeys=new Set(previous.map(i=>i.source+':'+i.id));
|
|
148
152
|
const added=data.discovered.filter(i=>!oldKeys.has(i.source+':'+i.id));
|
|
149
|
-
setNotice(`已刷新:Codex ${data.counts.codex},Claude ${data.counts.claude}`+(!initial?`;新增 ${added.length} 个会话`:'')+' · '+new Date(data.scannedAt || Date.now()).toLocaleTimeString());
|
|
153
|
+
setNotice(`已刷新:Codex ${data.counts.codex},Claude ${data.counts.claude},Antigravity ${data.counts.antigravity ?? 0}`+(!initial?`;新增 ${added.length} 个会话`:'')+' · '+new Date(data.scannedAt || Date.now()).toLocaleTimeString());
|
|
150
154
|
const target=info?.tab?.navigation?.params;
|
|
151
155
|
const next=data.discovered.find(i=>selected?i.id===selected.id&&i.source===selected.source:target?i.id===target.id&&i.source===target.source:false) || data.discovered.find(i=>i.source===source) || data.discovered[0];
|
|
152
156
|
if(next)select(next);else{setSelected(null);setConversation(null);request.current++;setLoading(false);}
|
|
@@ -204,27 +208,140 @@ window.__ModuleLoader__.load({id:'dsh-plugin-external-session-sync',factory:(req
|
|
|
204
208
|
report('archive-complete',{source,months,candidates:candidates.length,archived:result.archived.length,skippedPinned:result.skippedPinned.length,failed,deletedWorkspaces:result.deletedWorkspaces.length,ids:result.archived});
|
|
205
209
|
}catch(e){setError(e.message);setNotice('归档失败,请重试');report('archive-error',{error:e.message});}finally{setBusy(false);}
|
|
206
210
|
}
|
|
211
|
+
// Reverse sync lives behind an explicit scan + per-row confirm: it appends to another
|
|
212
|
+
// tool's history, so nothing may happen on mount or for sessions the user did not pick.
|
|
213
|
+
function visibleSessionIds(){
|
|
214
|
+
return (sessionState.ids || []).filter(id=>{
|
|
215
|
+
const summary=sessionState.byId?.[id];
|
|
216
|
+
return !!summary && !summary.blank && !summary.removed;
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
async function scanReverse(){
|
|
220
|
+
const ids=visibleSessionIds();
|
|
221
|
+
if(!ids.length){setReverseNotice('拿不到 DSH 会话列表,无法检查');return;}
|
|
222
|
+
setReverseBusy(true);setReverseNotice('正在检查可反同步的会话…');
|
|
223
|
+
try {
|
|
224
|
+
const result=await api('/reverse',{dryRun:true,sessionIds:ids});
|
|
225
|
+
const rows=(result.results || []).filter(row=>!row.error && row.turns>0);
|
|
226
|
+
setReverseRows(rows);
|
|
227
|
+
setReverseNotice(rows.length?`找到 ${rows.length} 个仅在 DSH 有新增轮次的会话`:'没有仅存在于 DSH 的新轮次');
|
|
228
|
+
report('reverse-scanned',{sessions:ids.length,candidates:rows.length,errors:(result.results||[]).filter(row=>row.error).length});
|
|
229
|
+
}catch(e){setReverseNotice('检查失败:'+e.message);report('reverse-scan-error',{error:e.message});}
|
|
230
|
+
finally{setReverseBusy(false);}
|
|
231
|
+
}
|
|
232
|
+
async function doReverse(row){
|
|
233
|
+
const title=sessionState.byId?.[row.sessionId]?.title || '未命名会话';
|
|
234
|
+
const ask=typeof window!=='undefined' && typeof window.confirm==='function'
|
|
235
|
+
? window.confirm(`把「${title}」中仅存在于 DSH 的 ${row.turns} 轮对话,追加写入 Codex 会话 ${row.threadId}?\n\n只追加、不覆盖;写入前会备份 rollout 文件。`)
|
|
236
|
+
: false;
|
|
237
|
+
if(!ask){report('reverse-cancelled',{sessionId:row.sessionId});return;}
|
|
238
|
+
setReverseBusy(true);
|
|
239
|
+
try {
|
|
240
|
+
const result=await api('/reverse',{dryRun:false,sessionIds:[row.sessionId]});
|
|
241
|
+
const done=(result.results || []).find(r=>r.verified);
|
|
242
|
+
setReverseNotice(done?`已写入 ${done.appended} 条记录(备份 ${done.backup.split('\\').pop()})`:'没有写入任何记录');
|
|
243
|
+
if(done)setReverseRows(rows=>(rows||[]).filter(r=>r.sessionId!==row.sessionId));
|
|
244
|
+
report('reverse-complete',{sessionId:row.sessionId,appended:done?.appended || 0,verified:!!done});
|
|
245
|
+
}catch(e){setReverseNotice('反同步失败:'+e.message);report('reverse-error',{error:e.message});}
|
|
246
|
+
finally{setReverseBusy(false);}
|
|
247
|
+
}
|
|
207
248
|
React.useEffect(()=>{
|
|
208
249
|
if(!catalog)return;
|
|
209
250
|
const timer=setTimeout(()=>{const rows=root.current?.querySelectorAll('[data-external-session]') || [];const archiveButton=root.current?.querySelector('[data-testid=external-sync-archive-old]');const monthSelect=root.current?.querySelector('[data-testid=external-sync-archive-months]');report('catalog-rendered',{items:catalog.discovered.length,rows:rows.length,source,visible:!!root.current?.getClientRects().length,archiveControl:!!archiveButton,archiveEnabled:!!archiveButton&&!archiveButton.disabled,monthSelector:!!monthSelect,monthOptions:monthSelect?monthSelect.options.length:0,pinnedCount:pinnedSessionIds.size,archivedCount:archivedSessionIds.size,first:catalog.discovered.filter(i=>i.source===source).slice(0,3).map(i=>({id:i.id,title:i.title}))});},60);
|
|
210
251
|
return()=>clearTimeout(timer);
|
|
211
252
|
},[catalog,source,query]);
|
|
212
253
|
const items=(catalog?.discovered||[]).filter(i=>i.source===source&&(!query || `${i.title} ${i.cwd}`.toLowerCase().includes(query.toLowerCase())));
|
|
254
|
+
async function loadReverseGroups(){
|
|
255
|
+
setReverseBusy(true);setReverseNotice('正在读取未归档会话…');
|
|
256
|
+
try{
|
|
257
|
+
const data=await api('/reverse-groups');
|
|
258
|
+
const groups=(data.groups || []).filter(group=>group.sessionIds.length);
|
|
259
|
+
setReverseGroups(groups);
|
|
260
|
+
const total=groups.reduce((sum,group)=>sum+group.sessionIds.length,0);
|
|
261
|
+
setReverseNotice('共 '+groups.length+' 个项目 / '+total+' 个未归档会话');
|
|
262
|
+
report('reverse-groups',{groups:groups.length,sessions:total,archived:data.archived || 0});
|
|
263
|
+
}catch(e){setReverseNotice('读取失败:'+e.message);report('reverse-groups-error',{error:e.message});}
|
|
264
|
+
finally{setReverseBusy(false);}
|
|
265
|
+
}
|
|
266
|
+
async function probeReverse(sessionId){
|
|
267
|
+
setReverseTarget(null);setReverseBusy(true);
|
|
268
|
+
try{
|
|
269
|
+
const data=await api('/reverse-targets',{sessionIds:[sessionId]});
|
|
270
|
+
const row=(data.rows || [])[0];
|
|
271
|
+
if(!row){setReverseNotice('没有拿到分类结果');return;}
|
|
272
|
+
setReverseTarget(row);
|
|
273
|
+
try{const preview=await api('/session-preview?id='+encodeURIComponent(sessionId)+'&maxMessages=60');setReversePreview(preview.messages || []);}
|
|
274
|
+
catch{setReversePreview([]);}
|
|
275
|
+
setReverseNotice(row.mode==='append'?(row.turns?'该会话有 '+row.turns+' 轮仅在 DSH 的新对话':'没有仅存在于 DSH 的新轮次'):row.mode==='export'?('将以 '+row.turns+' 轮新建一个 Codex 会话'):(row.error || '无法处理'));
|
|
276
|
+
report('reverse-probed',{sessionId,mode:row.mode,turns:row.turns || 0,forked:!!row.forked});
|
|
277
|
+
}catch(e){setReverseNotice('分类失败:'+e.message);}
|
|
278
|
+
finally{setReverseBusy(false);}
|
|
279
|
+
}
|
|
280
|
+
async function writeReverse(){
|
|
281
|
+
const target=reverseTarget;
|
|
282
|
+
if(!target || !(target.turns>0))return;
|
|
283
|
+
const title=sessionState.byId?.[target.sessionId]?.title || '未命名会话';
|
|
284
|
+
const what=target.mode==='append'
|
|
285
|
+
? '把「'+title+'」中仅存在于 DSH 的 '+target.turns+' 轮对话,追加写入 Codex 会话 '+target.threadId+'?'
|
|
286
|
+
: '把「'+title+'」整段('+target.turns+' 轮)导出为一个新的 Codex 会话?';
|
|
287
|
+
const ask=typeof window!=='undefined' && typeof window.confirm==='function'
|
|
288
|
+
? window.confirm(what+'\n\n追加只增不改;导出会新建 rollout 文件。')
|
|
289
|
+
: false;
|
|
290
|
+
if(!ask){report('reverse-cancelled',{sessionId:target.sessionId});return;}
|
|
291
|
+
setReverseBusy(true);
|
|
292
|
+
try{
|
|
293
|
+
const result=await api('/reverse',{dryRun:false,sessionIds:[target.sessionId]});
|
|
294
|
+
const done=(result.results || [])[0] || {};
|
|
295
|
+
setReverseNotice(done.error?('失败:'+done.error):done.mode==='export'?('已导出为新的 Codex 会话('+done.records+' 条记录)'):('已写入 '+done.appended+' 条记录(已备份)'));
|
|
296
|
+
if(done.verified)setReverseTarget(null);
|
|
297
|
+
report('reverse-complete',{sessionId:target.sessionId,mode:done.mode,appended:done.appended || 0,verified:!!done.verified});
|
|
298
|
+
}catch(e){setReverseNotice('反同步失败:'+e.message);report('reverse-error',{error:e.message});}
|
|
299
|
+
finally{setReverseBusy(false);}
|
|
300
|
+
}
|
|
213
301
|
const btn=(text,fn,disabled,testid)=>h('button',{type:'button',style:button,onClick:fn,disabled,'data-testid':testid},text);
|
|
214
302
|
return h('section',{ref:root,'data-testid':'external-sync-panel',style:{height:'100%',minHeight:0,display:'flex',flexDirection:'column',color:color.text,background:color.bg,fontSize:13}},
|
|
215
303
|
h('div',{style:{padding:'12px',borderBottom:'1px solid '+color.border,flexShrink:0}},
|
|
216
304
|
h('div',{style:{fontSize:15,fontWeight:650,marginBottom:8}},'外部会话同步与接力'),
|
|
217
|
-
h('div',{style:{display:'flex',gap:6,
|
|
218
|
-
h('
|
|
305
|
+
h('div',{role:'tablist',style:{display:'flex',gap:6,marginBottom:8}},
|
|
306
|
+
h('button',{type:'button','data-testid':'external-sync-tab-in',onClick:()=>setTab('in'),style:{...button,background:tab==='in'?color.layer:'transparent',fontWeight:tab==='in'?650:400,color:tab==='in'?color.text:color.muted}},'同步到 DSH'),
|
|
307
|
+
h('button',{type:'button','data-testid':'external-sync-tab-out',onClick:()=>setTab('out'),style:{...button,background:tab==='out'?color.layer:'transparent',fontWeight:tab==='out'?650:400,color:tab==='out'?color.text:color.muted}},'反同步到外界')),
|
|
308
|
+
h('div',{style:{display:tab==='in'?'flex':'none',gap:6,flexWrap:'wrap',alignItems:'center'}},
|
|
309
|
+
h('select',{value:source,onChange:e=>{setSource(e.target.value);const first=catalog?.discovered.find(i=>i.source===e.target.value);if(first)select(first);},style:{...button,padding:5}},h('option',{value:'codex'},`Codex (${catalog?.counts.codex ?? '…'})`),h('option',{value:'claude'},`Claude (${catalog?.counts.claude ?? '…'})`),h('option',{value:'antigravity'},`Antigravity (${catalog?.counts.antigravity ?? '…'})`)),
|
|
219
310
|
btn(refreshing?'刷新中…':'刷新',()=>refresh(),busy||refreshing,'external-sync-refresh'),btn('同步全部',()=>runSync(true),busy||refreshing||!catalog,'external-sync-all'),btn(busy?'处理中…':'同步所选',()=>runSync(false),busy||refreshing||!selected,'external-sync-selected'),
|
|
220
311
|
btn('在 DSH 继续',handoff,busy||!selected?.dshSessionId,'external-sync-handoff'),
|
|
221
312
|
h('select',{'data-testid':'external-sync-archive-months',value:archiveMonths,onChange:e=>setArchiveMonths(e.target.value),disabled:busy,style:{...button,padding:5},title:'置顶会话永不归档'},h('option',{value:'1'},'1个月前'),h('option',{value:'3'},'3个月前'),h('option',{value:'6'},'6个月前'),h('option',{value:'12'},'1年前')),
|
|
222
313
|
btn('归档旧会话',archiveOld,busy||refreshing||!catalog,'external-sync-archive-old'),
|
|
223
314
|
main?btn('在右侧查看',()=>openPanel(selected?{source:selected.source,id:selected.id}:undefined),false):null),
|
|
224
|
-
notice?h('div',{'role':'status','data-testid':'external-sync-result',style:{marginTop:8,color:'var(--dsw-alias-state-success-primary)',whiteSpace:'pre-wrap'}},notice):null,
|
|
225
|
-
error?h('div',{'role':'alert',style:{marginTop:8,color:'var(--dsw-alias-state-error-primary)',whiteSpace:'pre-wrap'}},error):null
|
|
226
|
-
|
|
227
|
-
|
|
315
|
+
tab==='in'&¬ice?h('div',{'role':'status','data-testid':'external-sync-result',style:{marginTop:8,color:'var(--dsw-alias-state-success-primary)',whiteSpace:'pre-wrap'}},notice):null,
|
|
316
|
+
tab==='in'&&error?h('div',{'role':'alert',style:{marginTop:8,color:'var(--dsw-alias-state-error-primary)',whiteSpace:'pre-wrap'}},error):null,
|
|
317
|
+
tab==='out'?h('div',{'data-testid':'external-sync-reverse',style:{marginTop:8,fontSize:12,lineHeight:1.6}},
|
|
318
|
+
h('div',{style:{display:'flex',gap:8,alignItems:'center',flexWrap:'wrap'}},
|
|
319
|
+
btn(reverseBusy?'处理中…':'读取未归档会话',loadReverseGroups,reverseBusy,'external-sync-reverse-scan'),
|
|
320
|
+
reverseNotice?h('span',{style:{color:color.muted}},reverseNotice):null),
|
|
321
|
+
h('div',{style:{marginTop:6,color:color.muted,fontSize:11}},'按项目列出全部未归档会话(含 DSH 原生会话与接力 fork)。导入会话追加到其 Codex 主线;原生会话导出为新的 Codex 会话。'),
|
|
322
|
+
reverseTarget?h('div',{'data-testid':'external-sync-reverse-target',style:{marginTop:8,padding:8,border:'1px solid '+color.border,borderRadius:6}},
|
|
323
|
+
h('div',{style:{fontWeight:600}},reverseTarget.mode==='append'?'追加到 Codex 主线':'导出为新的 Codex 会话'),
|
|
324
|
+
h('div',{style:{color:color.muted,marginTop:2}},reverseTarget.mode==='append'?('线程 '+String(reverseTarget.threadId||'').slice(0,8)+' · 待写入 '+(reverseTarget.turns||0)+' 轮'+(reverseTarget.forked?'(fork)':'')):('将新建线程 · '+(reverseTarget.turns||0)+' 轮')),
|
|
325
|
+
h('div',{style:{marginTop:6}},btn(reverseBusy?'写入中…':'确认反同步',writeReverse,reverseBusy||!(reverseTarget.turns>0),'external-sync-reverse-write'))):null):null),
|
|
326
|
+
tab==='out'?h('div',{style:{display:'flex',flex:1,minHeight:0}},
|
|
327
|
+
h('div',{style:{width:main?250:190,maxWidth:'40%',flexShrink:0,overflow:'auto',borderRight:'1px solid '+color.border,padding:6}},
|
|
328
|
+
!reverseGroups.length?h('div',{style:{padding:8,color:color.muted,fontSize:12}},reverseNotice||'点击上方「读取未归档会话」'):null,
|
|
329
|
+
reverseGroups.map(group=>h('div',{key:group.id,style:{marginBottom:8}},
|
|
330
|
+
h('div',{style:{fontSize:10,fontWeight:650,color:color.muted,padding:'2px 4px',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}},group.title||group.path),
|
|
331
|
+
group.sessionIds.map(sid=>{
|
|
332
|
+
const summary=sessionState.byId?.[sid]||{};
|
|
333
|
+
const active=reverseTarget && reverseTarget.sessionId===sid;
|
|
334
|
+
return h('button',{key:sid,type:'button','data-external-reverse':sid,onClick:()=>probeReverse(sid),title:summary.title||'',style:{display:'block',width:'100%',textAlign:'left',background:active?color.layer:'transparent',border:0,color:color.text,borderRadius:6,padding:'5px 8px',cursor:'pointer',fontSize:12,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}},summary.title||'未命名会话');
|
|
335
|
+
})))),
|
|
336
|
+
h('div',{style:{flex:1,minWidth:0,overflow:'auto',padding:12}},
|
|
337
|
+
reversePreview.length?h(React.Fragment,null,
|
|
338
|
+
h('div',{style:{fontSize:11,color:color.muted,marginBottom:8}},'最近 '+reversePreview.length+' 条消息预览'),
|
|
339
|
+
reversePreview.map((message,index)=>h('div',{key:index,style:{marginBottom:10}},
|
|
340
|
+
h('div',{style:{fontSize:10,color:color.muted}},message.role==='user'?'用户':'助手'),
|
|
341
|
+
h('div',{style:{fontSize:12,whiteSpace:'pre-wrap',lineHeight:1.55,overflowWrap:'anywhere'}},message.text))))
|
|
342
|
+
:h('div',{style:{color:color.muted,fontSize:12}},reverseTarget?'正在读取消息预览…':'左侧选择一个会话,这里会显示它的消息内容'))):null,
|
|
343
|
+
h('div',{style:{display:tab==='in'?'block':'none',padding:'8px 12px',borderBottom:'1px solid '+color.border}},h('input',{placeholder:'搜索标题或项目目录',value:query,onChange:e=>setQuery(e.target.value),style:{...button,width:'100%',boxSizing:'border-box'}})),
|
|
344
|
+
h('div',{style:{display:tab==='in'?'flex':'none',flex:1,minHeight:0}},
|
|
228
345
|
h('div',{style:{width:main?230:180,maxWidth:'35%',flexShrink:0,overflow:'auto',borderRight:'1px solid '+color.border,padding:6}},
|
|
229
346
|
items.map(i=>h('button',{key:i.source+':'+i.id,'data-external-session':i.id,type:'button',onClick:()=>select(i),title:i.title+'\n'+(i.cwd||''),style:{width:'100%',textAlign:'left',display:'block',background:selected?.id===i.id?color.layer:'transparent',border:0,color:color.text,borderRadius:6,padding:8,cursor:'pointer'}},
|
|
230
347
|
h('div',{style:{fontWeight:550,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}},i.title),h('div',{style:{fontSize:10,color:color.muted,overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis',marginTop:3}},i.cwd||'未记录目录'),h('div',{style:{fontSize:10,color:color.muted,marginTop:3}},i.dshSessionId&&pinnedSessionIds.has(i.dshSessionId)?'置顶(归档时跳过)':i.dshSessionId&&archivedSessionIds.has(i.dshSessionId)?'已归档':i.synced&&i.workspaceAttached===false?'正文已保存,需同步修复项目关联':i.upToDate?'已同步':i.synced?'源会话有更新':'未同步'))),
|
|
@@ -262,7 +379,7 @@ window.__ModuleLoader__.load({id:'dsh-plugin-external-session-sync',factory:(req
|
|
|
262
379
|
ctx.effect(()=>ctx.slots.inject('sidebar.right.pane.tab',()=>ctx.slots.register({name:'sidebar.right.pane.tab',key:ID},withBoundary(Panel))),'external-sync.body');
|
|
263
380
|
ctx.effect(()=>ctx.slots.inject('sidebar.right.pane.tab.title',()=>ctx.slots.register({name:'sidebar.right.pane.tab.title',key:ID},()=>h('span',null,'Codex / Claude 上下文'))),'external-sync.title');
|
|
264
381
|
ctx.effect(()=>{
|
|
265
|
-
report('client-mounted',{version:'1.
|
|
382
|
+
report('client-mounted',{version:'1.0.0'});
|
|
266
383
|
const initial=setTimeout(()=>{try{ctx.sidebarRight.openTab(KIND);}catch{}},500);
|
|
267
384
|
return()=>clearTimeout(initial);
|
|
268
385
|
},'external-sync.initial-panel');
|
|
@@ -270,5 +387,3 @@ window.__ModuleLoader__.load({id:'dsh-plugin-external-session-sync',factory:(req
|
|
|
270
387
|
}
|
|
271
388
|
return {apply,inject};
|
|
272
389
|
}});
|
|
273
|
-
|
|
274
|
-
// build-marker: delete-visible-1.7.3
|
package/engine.js
CHANGED
|
@@ -19,7 +19,8 @@ import {
|
|
|
19
19
|
} from './readers.js';
|
|
20
20
|
import { nativeEvents, nativeId, canonicalCwd } from './native.js';
|
|
21
21
|
import { discoverCodexThreads } from './discovery.js';
|
|
22
|
-
import {
|
|
22
|
+
import { readSessionAny } from './reverse.js';
|
|
23
|
+
import { readAntigravityConversation, listAntigravitySessionsAsync } from './readers-antigravity.js';
|
|
23
24
|
|
|
24
25
|
const visibleMessages = (events) =>
|
|
25
26
|
events.filter((event) => event.type === 'user/message' || event.type === 'assistant/message');
|
|
@@ -53,8 +54,10 @@ export class SyncEngine {
|
|
|
53
54
|
|
|
54
55
|
async discover(options = {}) {
|
|
55
56
|
const out = [];
|
|
56
|
-
|
|
57
|
-
|
|
57
|
+
// An explicit source narrows the scan to that source only; no source means all three.
|
|
58
|
+
const wants = (source) => !options.source || options.source === source;
|
|
59
|
+
if (wants('codex')) out.push(...discoverCodexThreads());
|
|
60
|
+
if (wants('claude')) {
|
|
58
61
|
for (const row of await listClaudeSessionsAsync()) {
|
|
59
62
|
// A concurrently rotated file must not break the other source's list.
|
|
60
63
|
try {
|
|
@@ -65,6 +68,10 @@ export class SyncEngine {
|
|
|
65
68
|
}
|
|
66
69
|
}
|
|
67
70
|
}
|
|
71
|
+
if (wants('antigravity')) {
|
|
72
|
+
// One SQLite database per conversation; the reader caches by size + mtime.
|
|
73
|
+
for (const row of await listAntigravitySessionsAsync()) out.push(row);
|
|
74
|
+
}
|
|
68
75
|
return out
|
|
69
76
|
.filter((row) => options.includeSubagents !== false || !row.isSubagent)
|
|
70
77
|
.map((row) => ({ ...row, cwd: canonicalCwd(row.cwd) }))
|
|
@@ -85,6 +92,7 @@ export class SyncEngine {
|
|
|
85
92
|
counts: {
|
|
86
93
|
codex: discovered.filter((row) => row.source === 'codex').length,
|
|
87
94
|
claude: discovered.filter((row) => row.source === 'claude').length,
|
|
95
|
+
antigravity: discovered.filter((row) => row.source === 'antigravity').length,
|
|
88
96
|
synced: Object.keys(this.state.entries).length,
|
|
89
97
|
},
|
|
90
98
|
discovered: filtered.map((row) => {
|
|
@@ -112,7 +120,7 @@ export class SyncEngine {
|
|
|
112
120
|
}
|
|
113
121
|
|
|
114
122
|
async descriptor(source, id) {
|
|
115
|
-
if (!['codex', 'claude'].includes(source)) throw new Error('未知会话来源');
|
|
123
|
+
if (!['codex', 'claude', 'antigravity'].includes(source)) throw new Error('未知会话来源');
|
|
116
124
|
const all = await this.discover({ source, includeSubagents: true });
|
|
117
125
|
const item = all.find((row) => row.id === id);
|
|
118
126
|
if (!item) throw new Error('找不到外部会话,请刷新列表');
|
|
@@ -124,7 +132,9 @@ export class SyncEngine {
|
|
|
124
132
|
const conversation =
|
|
125
133
|
source === 'codex'
|
|
126
134
|
? await readCodexThreadConversation(id, { maxMessages: 2000 })
|
|
127
|
-
:
|
|
135
|
+
: source === 'antigravity'
|
|
136
|
+
? readAntigravityConversation(found.file || id)
|
|
137
|
+
: await readClaudeConversation(found.file);
|
|
128
138
|
conversation.cwd = canonicalCwd(conversation.cwd || found.cwd);
|
|
129
139
|
const limit = Math.max(1, Math.min(2000, Number(maxMessages) || 100));
|
|
130
140
|
return {
|
|
@@ -174,29 +184,20 @@ export class SyncEngine {
|
|
|
174
184
|
const conversation =
|
|
175
185
|
row.source === 'codex'
|
|
176
186
|
? await readCodexThreadConversation(row.id)
|
|
177
|
-
:
|
|
187
|
+
: row.source === 'antigravity'
|
|
188
|
+
? readAntigravityConversation(row.file || row.id)
|
|
189
|
+
: await readClaudeConversation(row.file);
|
|
178
190
|
conversation.messages = conversation.messages.filter(
|
|
179
191
|
(message) => (message.role === 'user' || message.role === 'assistant') && message.text?.trim(),
|
|
180
192
|
);
|
|
181
193
|
return conversation;
|
|
182
194
|
}
|
|
183
195
|
|
|
184
|
-
/** Read a stored session log without resuming its Agent. */
|
|
185
|
-
async readStoredSession(id) {
|
|
186
|
-
const handle = await this.ctx.sessionPersistence.open(id, 'read');
|
|
187
|
-
try {
|
|
188
|
-
const { events } = await handle.read();
|
|
189
|
-
return { meta: { cwd: handle.header.cwd }, events };
|
|
190
|
-
} finally {
|
|
191
|
-
await handle.close();
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
196
|
/** Distinguish "no stored log" from "a stored log this DSH version cannot read". */
|
|
196
197
|
async usableSession(id) {
|
|
197
198
|
try {
|
|
198
199
|
if (!(await this.ctx.sessionPersistence.stat(id))) return { exists: false, corrupt: false };
|
|
199
|
-
await this.
|
|
200
|
+
await readSessionAny(this.ctx, id, { force: true });
|
|
200
201
|
return { exists: true, corrupt: false };
|
|
201
202
|
} catch (error) {
|
|
202
203
|
if (/corrupt/i.test(String(error && error.message))) return { exists: true, corrupt: true };
|
|
@@ -245,7 +246,7 @@ export class SyncEngine {
|
|
|
245
246
|
if (state.corrupt) report.recovered.push({ key, previous: previous.sessionId, reason: 'corrupt-session-log' });
|
|
246
247
|
}
|
|
247
248
|
if (reusable) {
|
|
248
|
-
const inspected = await this.
|
|
249
|
+
const inspected = await readSessionAny(this.ctx, previous.sessionId);
|
|
249
250
|
const messages = visibleMessages(inspected.events).length;
|
|
250
251
|
if (!messages) throw new Error('已同步会话没有有效消息,无法标记为同步完成');
|
|
251
252
|
if (report.dryRun) {
|
|
@@ -321,7 +322,7 @@ export class SyncEngine {
|
|
|
321
322
|
}
|
|
322
323
|
}
|
|
323
324
|
|
|
324
|
-
const inspected = await this.
|
|
325
|
+
const inspected = await readSessionAny(this.ctx, id, { force: true });
|
|
325
326
|
const count = visibleMessages(inspected.events).length;
|
|
326
327
|
if (count < conversation.messages.length) {
|
|
327
328
|
throw new Error(`DSH 还原消息数不完整 (${count}/${conversation.messages.length})`);
|
|
@@ -375,84 +376,12 @@ export class SyncEngine {
|
|
|
375
376
|
return report;
|
|
376
377
|
}
|
|
377
378
|
|
|
378
|
-
/** Archived sessions whose payload may be deleted: never pinned, live or already deleted. */
|
|
379
|
-
async deletableArchived(options = {}) {
|
|
380
|
-
const sessionsRoot = path.join(this.home, 'sessions');
|
|
381
|
-
const archived = Array.from(this.ctx.workspaceRegistry.archivedSessionIds || [], String);
|
|
382
|
-
const pinned = new Set(Array.from(this.ctx.workspaceRegistry.pinnedSessionIds || [], String));
|
|
383
|
-
const tombstones = this.state.deleted || {};
|
|
384
|
-
const wanted = Array.isArray(options.ids) ? new Set(options.ids.map(String)) : null;
|
|
385
|
-
const rows = [];
|
|
386
|
-
for (const sessionId of archived) {
|
|
387
|
-
if (pinned.has(sessionId) || tombstones[sessionId]) continue;
|
|
388
|
-
if (wanted && !wanted.has(sessionId)) continue;
|
|
389
|
-
// A chat that is currently open is never deleted out from under its agent.
|
|
390
|
-
try {
|
|
391
|
-
if (this.ctx.sessions.get(sessionId)) continue;
|
|
392
|
-
} catch {}
|
|
393
|
-
const plan = planSessionDeletion({ sessionsRoot, archivesRoot: this.archiveRoot, sessionId });
|
|
394
|
-
const entry = Object.values(this.state.entries).find((item) => item.sessionId === sessionId);
|
|
395
|
-
rows.push({ ...plan, title: entry?.title || null });
|
|
396
|
-
}
|
|
397
|
-
return rows;
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
/**
|
|
401
|
-
* Permanently delete archived session payloads. Dry run unless `dryRun:false`.
|
|
402
|
-
* The id stays in the registry's archived list and a tombstone is recorded, so the
|
|
403
|
-
* session never resurfaces as an unreadable chat.
|
|
404
|
-
*/
|
|
405
|
-
async deleteArchived(options = {}) {
|
|
406
|
-
const rows = (await this.deletableArchived(options)).sort((a, b) => b.bytes - a.bytes);
|
|
407
|
-
const limit = Math.max(1, Math.min(500, Number(options.limit) || rows.length || 1));
|
|
408
|
-
const batch = rows.slice(0, limit);
|
|
409
|
-
const bytes = batch.reduce((sum, row) => sum + row.bytes, 0);
|
|
410
|
-
if (options.dryRun !== false) {
|
|
411
|
-
return {
|
|
412
|
-
dryRun: true,
|
|
413
|
-
candidates: rows.length,
|
|
414
|
-
batch: batch.length,
|
|
415
|
-
bytes,
|
|
416
|
-
missingPayload: rows.filter((row) => !row.exists).length,
|
|
417
|
-
sample: batch.slice(0, 8).map(({ sessionId, title, bytes }) => ({ sessionId, title, bytes })),
|
|
418
|
-
};
|
|
419
|
-
}
|
|
420
|
-
this.state.deleted ||= {};
|
|
421
|
-
const journal = { startedAt: new Date().toISOString(), rows: [] };
|
|
422
|
-
let freedBytes = 0;
|
|
423
|
-
for (const row of batch) {
|
|
424
|
-
try {
|
|
425
|
-
const result = deleteSessionPayload({ sessionsRoot: path.join(this.home, 'sessions'), archivesRoot: this.archiveRoot, sessionId: row.sessionId });
|
|
426
|
-
freedBytes += result.bytes || 0;
|
|
427
|
-
this.state.deleted[row.sessionId] = { deletedAt: Date.now(), title: row.title, bytes: result.bytes || 0 };
|
|
428
|
-
for (const [key, entry] of Object.entries(this.state.entries)) if (entry.sessionId === row.sessionId) delete this.state.entries[key];
|
|
429
|
-
this.save();
|
|
430
|
-
journal.rows.push({ sessionId: row.sessionId, title: row.title, bytes: result.bytes || 0, ok: true });
|
|
431
|
-
} catch (error) {
|
|
432
|
-
journal.rows.push({ sessionId: row.sessionId, title: row.title, ok: false, error: error.message });
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
journal.finishedAt = new Date().toISOString();
|
|
436
|
-
journal.freedBytes = freedBytes;
|
|
437
|
-
fs.mkdirSync(path.join(this.home, 'external-session-sync'), { recursive: true });
|
|
438
|
-
fs.writeFileSync(path.join(this.home, 'external-session-sync', `deletions-${Date.now()}.json`), JSON.stringify(journal, null, 2));
|
|
439
|
-
const remaining = await this.deletableArchived({});
|
|
440
|
-
return {
|
|
441
|
-
dryRun: false,
|
|
442
|
-
deleted: journal.rows.filter((row) => row.ok).length,
|
|
443
|
-
failed: journal.rows.filter((row) => !row.ok),
|
|
444
|
-
freedBytes,
|
|
445
|
-
remaining: remaining.length,
|
|
446
|
-
deletedSessionIds: journal.rows.filter((row) => row.ok).map((row) => row.sessionId),
|
|
447
|
-
};
|
|
448
|
-
}
|
|
449
|
-
|
|
450
379
|
async validateSession(id) {
|
|
451
380
|
const owned = Object.values(this.state.entries).some(
|
|
452
381
|
(entry) => entry.sessionId === id || entry.previousSessionIds?.includes(id),
|
|
453
382
|
);
|
|
454
383
|
if (!owned) throw new Error('这不是同步模块创建的会话');
|
|
455
|
-
const read = await this.
|
|
384
|
+
const read = await readSessionAny(this.ctx, id, { force: true });
|
|
456
385
|
const messages = visibleMessages(read.events);
|
|
457
386
|
const resolved = await this.ctx.sessionController.resolveAgent(id);
|
|
458
387
|
if (resolved.error) throw resolved.error;
|
|
@@ -481,7 +410,7 @@ export class SyncEngine {
|
|
|
481
410
|
/** Does this stored session open with a protected system head? Uses the public reader. */
|
|
482
411
|
async inspectHead(sessionId) {
|
|
483
412
|
try {
|
|
484
|
-
const read = await this.
|
|
413
|
+
const read = await readSessionAny(this.ctx, sessionId);
|
|
485
414
|
const first = read.events.find(
|
|
486
415
|
(event) => event.surfaceOp === 'append' || ['system/message', 'user/message', 'developer/message', 'assistant/message', 'tool/result'].includes(event.type),
|
|
487
416
|
);
|