dsh-plugin-external-session-sync 0.0.0-stage → 1.2.1

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/client.js ADDED
@@ -0,0 +1,274 @@
1
+ // Codex thread-index merge release: panel refreshes against official state_5.sqlite records.
2
+ window.__ModuleLoader__.load({id:'dsh-plugin-external-session-sync',factory:(require)=>{
3
+ const React=require('react');
4
+ const h=React.createElement;
5
+ const ID='dsh-plugin-external-session-sync',PANEL_ID='dsh-plugin-codex-sync',KIND='external-session-sync',API='/external-session-sync';
6
+ fetch(API+'/client-state',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-DSH-Sync':'1'},body:JSON.stringify({kind:'client-imported'})}).catch(()=>{});
7
+ let runtime,verifyId;
8
+ const color={bg:'var(--dsw-alias-bg-base)',layer:'var(--dsw-alias-bg-layer-1)',border:'var(--dsw-alias-border-l1)',text:'var(--dsw-alias-label-primary)',muted:'var(--dsw-alias-label-secondary)'};
9
+ const button={font:'inherit',color:color.text,background:color.layer,border:'1px solid '+color.border,borderRadius:7,padding:'6px 10px',cursor:'pointer'};
10
+ async function api(path,body) {
11
+ const controller=new AbortController();
12
+ const timeoutMs=path.startsWith('/status')?20000:180000;
13
+ const timer=setTimeout(()=>controller.abort(),timeoutMs);
14
+ try {
15
+ let response;
16
+ try {
17
+ response=await fetch(API+path,{credentials:'same-origin',cache:'no-store',signal:controller.signal,...(body===undefined?{}:{method:'POST',headers:{'Content-Type':'application/json','X-DSH-Sync':'1'},body:JSON.stringify(body)})});
18
+ } catch(error) {
19
+ if(error.name==='AbortError')throw new Error(`请求超时(${Math.round(timeoutMs/1000)} 秒),大历史导入可能较慢,请稍后重试或分批同步`);
20
+ throw new Error('无法连接同步服务:'+error.message);
21
+ }
22
+ let text;
23
+ try { text=await response.text(); }
24
+ catch(error) {
25
+ if(error.name==='AbortError')throw new Error('读取响应超时,请稍后重试');
26
+ throw new Error('读取响应失败:'+error.message);
27
+ }
28
+ let value;
29
+ try { value=JSON.parse(text); }
30
+ catch { throw new Error(`同步服务返回了非 JSON 响应(HTTP ${response.status})${text?(':'+text.slice(0,160)):''}`); }
31
+ if(!response.ok)throw new Error(value.error || '请求失败 '+response.status);
32
+ return value;
33
+ } finally { clearTimeout(timer); }
34
+ }
35
+ function report(kind,details={}) {api('/client-state',{kind,...details,...(verifyId?{verificationId:verifyId}:{})}).catch(()=>{});}
36
+ function Glyph({size=16}) {return h('span',{'aria-hidden':true,style:{fontSize:size,lineHeight:1}},'↻');}
37
+ function OpenButton({wide=true}) {return h('button',{type:'button',style:button,'data-testid':'external-sync-open',title:'打开外部会话同步',onClick:()=>openPanel()},h(Glyph),wide?' 会话同步':null);}
38
+ function openPanel(params) {
39
+ runtime.layout.selectPanel(null);
40
+ try {runtime.sidebarRight.openTab(KIND,params?{params}:undefined);report('opened-right');}
41
+ catch(e) {runtime.layout.selectPanel(PANEL_ID);report('opened-main',{reason:e.message});}
42
+ }
43
+ function NativeMarker({sessionId}) {
44
+ const ref=React.useRef(null);
45
+ React.useEffect(()=>{const timer=setTimeout(()=>{if(ref.current?.getClientRects().length)report('native-session-visible',{sessionId});},250);return()=>clearTimeout(timer);},[sessionId]);
46
+ return h('button',{ref,type:'button',style:button,onClick:()=>openPanel(),title:'查看 Codex / Claude 上下文'},'会话同步');
47
+ }
48
+ const EMPTY_WORKSPACE_STATE={items:[],pinnedSessionIds:[],archivedSessionIds:[]};
49
+ function useNoWorkspaceState(){return EMPTY_WORKSPACE_STATE;}
50
+ const EMPTY_SESSIONS={ids:[],byId:{}};
51
+ function useNoSessions(){return EMPTY_SESSIONS;}
52
+ const DSH_ARCHIVE_MONTHS=1;
53
+ /** Footer action: archive old NATIVE DSH sessions only (never the external sources). */
54
+ function ArchiveFooterButton({wide,useSessions,useWorkspaces}) {
55
+ const useSessionsHook=typeof useSessions==='function'?useSessions:useNoSessions;
56
+ const useWorkspacesHook=typeof useWorkspaces==='function'?useWorkspaces:useNoWorkspaceState;
57
+ const sessions=useSessionsHook(state=>state) || EMPTY_SESSIONS;
58
+ const workspaceState=useWorkspacesHook(state=>state) || EMPTY_WORKSPACE_STATE;
59
+ const [busy,setBusy]=React.useState(false);
60
+ React.useEffect(()=>{report('dsh-archive-button-mounted',{wide:!!wide});},[]);
61
+ async function run() {
62
+ if(busy)return;
63
+ const cutoff=Date.now()-DSH_ARCHIVE_MONTHS*30*24*60*60*1000;
64
+ const pinned=new Set(workspaceState.pinnedSessionIds || []);
65
+ const archived=new Set(workspaceState.archivedSessionIds || []);
66
+ const targets=(sessions.ids || []).filter(id=>{
67
+ const summary=sessions.byId?.[id];
68
+ if(!summary || summary.blank || summary.removed)return false;
69
+ if(pinned.has(id) || archived.has(id))return false;
70
+ const at=Number(summary.updatedAt || 0);
71
+ return at>0 && at<cutoff;
72
+ });
73
+ if(!targets.length){report('dsh-archive-empty',{skippedPinned:pinned.size});return;}
74
+ const ask=typeof window!=='undefined' && typeof window.confirm==='function'
75
+ ? window.confirm(`将归档 ${targets.length} 个超过 ${DSH_ARCHIVE_MONTHS} 个月未活动的 DSH 会话。\n置顶会话会跳过,归档后可在归档列表恢复。继续?`)
76
+ : false;
77
+ if(!ask){report('dsh-archive-cancelled',{count:targets.length});return;}
78
+ setBusy(true);
79
+ try {
80
+ const result=await api('/archive',{sessionIds:targets,deleteEmptyWorkspaces:true});
81
+ report('dsh-archive-complete',{requested:targets.length,archived:result.archived.length,skippedPinned:result.skippedPinned.length,failed:result.failed.length,deletedWorkspaces:result.deletedWorkspaces.length});
82
+ }catch(error){report('dsh-archive-error',{error:error.message});}
83
+ finally{setBusy(false);}
84
+ }
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
+ }
87
+ const DELETE_CONFIRM = '删除后无法恢复,也没有备份。确定继续?';
88
+ /** Footer action: permanently delete the payload of archived DSH sessions. */
89
+ function DeleteArchivedFooterButton({wide}) {
90
+ const [busy,setBusy]=React.useState(false);
91
+ React.useEffect(()=>{report('dsh-delete-button-mounted',{wide:!!wide});},[]);
92
+ function say(message) {
93
+ try { if (typeof window!=='undefined' && typeof window.alert==='function') window.alert(message); } catch {}
94
+ }
95
+ async function run() {
96
+ if(busy)return;
97
+ setBusy(true);
98
+ try {
99
+ const plan=await api('/delete-archived',{dryRun:true});
100
+ if(!plan.candidates){say('没有可删除的已归档会话。');report('dsh-delete-empty',{});return;}
101
+ const mb=(plan.bytes/1048576).toFixed(1);
102
+ const ask=typeof window!=='undefined' && typeof window.confirm==='function'
103
+ ? window.confirm(`将永久删除 ${plan.candidates} 个已归档会话(约 ${mb} MB)。\n置顶、正在打开、已删除的会话会跳过。删除后无法恢复,也没有备份。继续?`)
104
+ : false;
105
+ if(!ask){report('dsh-delete-cancelled',{count:plan.candidates});return;}
106
+ const again=typeof window!=='undefined' && typeof window.confirm==='function'
107
+ ? window.confirm(`再次确认:永久删除 ${plan.candidates} 个已归档会话,不可恢复。`)
108
+ : false;
109
+ if(!again){report('dsh-delete-cancelled',{count:plan.candidates,stage:'second'});return;}
110
+ const result=await api('/delete-archived',{dryRun:false});
111
+ const freed=(result.freedBytes/1048576).toFixed(2);
112
+ say(`已删除 ${result.deleted} 个会话,释放 ${freed} MB。${result.remaining>0?`\n仍有 ${result.remaining} 个可继续清理。`:''}${result.failed.length?`\n失败 ${result.failed.length} 个。`:''}`);
113
+ report('dsh-delete-complete',{deleted:result.deleted,freedBytes:result.freedBytes,remaining:result.remaining,failed:result.failed.length});
114
+ }catch(error){
115
+ say('删除失败:'+error.message);
116
+ report('dsh-delete-error',{error:error.message});
117
+ }
118
+ finally{setBusy(false);}
119
+ }
120
+ return h('button',{type:'button',style:button,'data-testid':'dsh-delete-archived',disabled:busy,title:'永久删除已归档会话的正文与存档(不可恢复)',onClick:run},busy?'删除中…':'删除已归档');
121
+ }
122
+ function Panel({useTabInfo,useWorkspaces,main=false}) {
123
+ const info=typeof useTabInfo==='function'?useTabInfo():null;
124
+ // Never read a service off the Context unless it is injected: Cordis throws for a
125
+ // service the plugin did not declare, and that throw unmounts the whole panel.
126
+ const useWs=typeof useWorkspaces==='function'?useWorkspaces:useNoWorkspaceState;
127
+ const workspaceState=useWs(state=>state) || EMPTY_WORKSPACE_STATE;
128
+ const pinnedSessionIds=new Set(workspaceState.pinnedSessionIds || []);
129
+ const archivedSessionIds=new Set(workspaceState.archivedSessionIds || []);
130
+ const root=React.useRef(null),request=React.useRef(0),catalogRequest=React.useRef(0),mounted=React.useRef(true);
131
+ const [catalog,setCatalog]=React.useState(null),[selected,setSelected]=React.useState(null),[conversation,setConversation]=React.useState(null);
132
+ 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');
133
+ async function load() {
134
+ const token=++catalogRequest.current;setRefreshing(true);setError('');
135
+ try {
136
+ const data=await api('/status');
137
+ if(!Array.isArray(data.discovered) || !data.counts)throw new Error('会话列表响应不完整,请重试');
138
+ if(mounted.current && token===catalogRequest.current)setCatalog(data);
139
+ return data;
140
+ }finally{if(mounted.current && token===catalogRequest.current)setRefreshing(false);}
141
+ }
142
+ async function refresh(initial=false) {
143
+ const started=Date.now();const previous=catalog?.discovered || [];
144
+ setNotice(initial?'正在读取会话列表…':'正在刷新会话列表…');
145
+ try {
146
+ const data=await load();if(!mounted.current)return;
147
+ const oldKeys=new Set(previous.map(i=>i.source+':'+i.id));
148
+ 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());
150
+ const target=info?.tab?.navigation?.params;
151
+ 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
+ if(next)select(next);else{setSelected(null);setConversation(null);request.current++;setLoading(false);}
153
+ report('catalog-refreshed',{items:data.discovered.length,codex:data.counts.codex,claude:data.counts.claude,elapsedMs:Date.now()-started,added:added.length,initial,mode:main?'main':'right',newest:data.discovered.slice(0,3).map(i=>({id:i.id,title:i.title}))});
154
+ }catch(e){if(mounted.current){setError(e.message);setNotice('刷新失败,可重试;上次加载的列表已保留');report('catalog-refresh-error',{error:e.message});}}
155
+ }
156
+ React.useEffect(()=>{mounted.current=true;refresh(true);return()=>{mounted.current=false;catalogRequest.current++;request.current++;};},[]);
157
+ async function select(item) {
158
+ const token=++request.current;setSelected(item);setSource(item.source);setLoading(true);setError('');setConversation(null);
159
+ try {const data=await api('/conversation?source='+item.source+'&id='+encodeURIComponent(item.id)+'&maxMessages=100');if(token!==request.current)return;setConversation(data);}
160
+ catch(e){if(token===request.current)setError(e.message);}finally{if(token===request.current)setLoading(false);}
161
+ }
162
+ React.useEffect(()=>{
163
+ if(!conversation)return;
164
+ const timer=setTimeout(()=>{
165
+ const visible=!!root.current?.getClientRects().length;
166
+ const nodes=root.current?.querySelectorAll('[data-external-message]') || [];
167
+ report('context-rendered',{source:conversation.source,id:conversation.id,messages:conversation.messages.length,total:conversation.totalMessages,domMessages:nodes.length,visible,chars:Array.from(nodes).reduce((sum,n)=>sum+n.textContent.length,0)});
168
+ },60);return()=>clearTimeout(timer);
169
+ },[conversation]);
170
+ async function runSync(all=false) {
171
+ if(!all && !selected)return;
172
+ setBusy(true);setError('');setNotice('正在读取并导入 '+(all?'所有会话':'所选会话')+'…');
173
+ try {
174
+ const result=await api('/sync',all?{source}:{source:selected.source,ids:[selected.id]});
175
+ const repaired=result.repaired?.length || 0;
176
+ const ready=[...result.imported,...result.skipped].find(item=>item.id && item.workspaceAttached);
177
+ setNotice(`同步完成:新增 ${result.imported.length},已同步 ${result.skipped.length},修复项目关联 ${repaired},失败 ${result.failed.length}`+(!all&&ready?`\n${ready.title}(${ready.messages} 条消息)已加入项目「${ready.workspaceTitle}」。可点击“在 DSH 继续”。`:'')+(result.imported.find(i=>i.warning)?.warning?'\n'+result.imported.find(i=>i.warning).warning:''));
178
+ const data=await load();
179
+ if(selected)setSelected(data.discovered.find(i=>i.source===selected.source&&i.id===selected.id) || selected);
180
+ if(result.failed.length)setError(result.failed.slice(0,3).map(i=>i.title+': '+i.error).join('\n'));
181
+ report('sync-complete',{imported:result.imported.length,skipped:result.skipped.length,failed:result.failed.length,ids:result.imported.map(i=>i.id),mode:all?'all':'selected'});
182
+ }catch(e){setError(e.message);setNotice('同步失败,请查看原因');report('sync-error',{error:e.message});}finally{setBusy(false);}
183
+ }
184
+ async function handoff() {
185
+ if(!selected?.dshSessionId)return;
186
+ setBusy(true);setError('');
187
+ try {const result=await api('/validate?id='+encodeURIComponent(selected.dshSessionId));runtime.layout.selectPanel(null);runtime.uiWorkspace.openSession(selected.dshSessionId);report('handoff-opened',{sessionId:selected.dshSessionId,messageCount:result.messageCount,derivedMessages:result.derivedMessages,agentAvailable:result.agentAvailable});}
188
+ catch(e){setError(e.message);report('handoff-error',{error:e.message});}finally{setBusy(false);}
189
+ }
190
+ async function archiveOld() {
191
+ if(!catalog)return;
192
+ const months=Math.max(1,Number(archiveMonths)||1),cutoff=Date.now()-months*30*24*60*60*1000;
193
+ const candidates=catalog.discovered.filter(item=>item.source===source && item.synced && item.dshSessionId && !archivedSessionIds.has(item.dshSessionId) && Number(item.updatedAt||0)<cutoff);
194
+ const pinned=candidates.filter(item=>pinnedSessionIds.has(item.dshSessionId));
195
+ const targets=candidates.filter(item=>!pinnedSessionIds.has(item.dshSessionId));
196
+ if(!targets.length){setNotice(`没有符合条件的会话;候选 ${candidates.length},置顶跳过 ${pinned.length}`);return;}
197
+ setBusy(true);setError('');setNotice(`正在归档 ${targets.length} 个超过 ${months} 个月的会话…`);
198
+ try {
199
+ const result=await api('/archive',{sessionIds:targets.map(item=>item.dshSessionId),pinnedSessionIds:[...pinnedSessionIds],deleteEmptyWorkspaces:true});
200
+ const failed=result.failed?.length || 0;
201
+ setNotice(`归档完成:${result.archived.length} 个;置顶跳过 ${result.skippedPinned.length} 个;空项目删除 ${result.deletedWorkspaces.length} 个;失败 ${failed} 个`);
202
+ if(failed)setError(result.failed.slice(0,3).map(item=>item.id+': '+item.error).join('\n'));
203
+ await load();
204
+ 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
+ }catch(e){setError(e.message);setNotice('归档失败,请重试');report('archive-error',{error:e.message});}finally{setBusy(false);}
206
+ }
207
+ React.useEffect(()=>{
208
+ if(!catalog)return;
209
+ 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
+ return()=>clearTimeout(timer);
211
+ },[catalog,source,query]);
212
+ const items=(catalog?.discovered||[]).filter(i=>i.source===source&&(!query || `${i.title} ${i.cwd}`.toLowerCase().includes(query.toLowerCase())));
213
+ const btn=(text,fn,disabled,testid)=>h('button',{type:'button',style:button,onClick:fn,disabled,'data-testid':testid},text);
214
+ 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
+ h('div',{style:{padding:'12px',borderBottom:'1px solid '+color.border,flexShrink:0}},
216
+ h('div',{style:{fontSize:15,fontWeight:650,marginBottom:8}},'外部会话同步与接力'),
217
+ h('div',{style:{display:'flex',gap:6,flexWrap:'wrap',alignItems:'center'}},
218
+ 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 ?? '…'})`)),
219
+ 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
+ btn('在 DSH 继续',handoff,busy||!selected?.dshSessionId,'external-sync-handoff'),
221
+ 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
+ btn('归档旧会话',archiveOld,busy||refreshing||!catalog,'external-sync-archive-old'),
223
+ 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
+ h('div',{style:{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'}})),
227
+ h('div',{style:{display:'flex',flex:1,minHeight:0}},
228
+ h('div',{style:{width:main?230:180,maxWidth:'35%',flexShrink:0,overflow:'auto',borderRight:'1px solid '+color.border,padding:6}},
229
+ 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
+ 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?'源会话有更新':'未同步'))),
231
+ !items.length?h('div',{style:{padding:8,color:color.muted}},refreshing?'正在读取会话列表…':!catalog&&error?'列表加载失败,请点击刷新重试':query?'没有匹配的会话':'尚未发现会话,请刷新'):null),
232
+ h('div',{style:{flex:1,minWidth:0,overflow:'auto',padding:14}},
233
+ loading?h('div',{style:{color:color.muted}},'读取聊天上下文…'):conversation?h(React.Fragment,null,
234
+ h('h3',{style:{margin:'0 0 4px',fontSize:15}},conversation.title),h('div',{style:{fontSize:11,color:color.muted,marginBottom:12,overflowWrap:'anywhere'}},conversation.cwd||'无工作目录'),
235
+ conversation.totalMessages>conversation.messages.length?h('p',{style:{color:color.muted,fontSize:11}},`显示最近 ${conversation.messages.length} 条;导入会保存完整文本历史。`):null,
236
+ conversation.messages.map((m,index)=>h('article',{key:index,'data-external-message':m.role,style:{padding:'10px 0',borderBottom:'1px solid '+color.border}},h('div',{style:{fontSize:11,color:color.muted,marginBottom:5}},m.role==='user'?'你':source==='codex'?'Codex':'Claude'),h('div',{style:{whiteSpace:'pre-wrap',lineHeight:1.65,overflowWrap:'anywhere'}},m.text)))):h('p',{style:{color:color.muted}},'选择一个会话,在右侧查看上下文。'))));
237
+ }
238
+ // A render failure inside the panel must stay a readable message in the pane
239
+ // instead of silently collapsing to an empty surface.
240
+ class PanelBoundary extends React.Component {
241
+ constructor(props){super(props);this.state={error:null};}
242
+ static getDerivedStateFromError(error){return {error:error||new Error('未知错误')};}
243
+ componentDidCatch(error){report('panel-render-error',{error:String((error&&error.message)||error)});}
244
+ render(){
245
+ if(!this.state.error)return this.props.children;
246
+ return h('div',{role:'alert','data-testid':'external-sync-render-error',style:{padding:14,fontSize:12,lineHeight:1.6,color:'var(--dsw-alias-state-error-primary)',whiteSpace:'pre-wrap'}},'同步面板渲染出错:'+(this.state.error.message||String(this.state.error)));
247
+ }
248
+ }
249
+ const withBoundary=component=>props=>h(PanelBoundary,null,component(props));
250
+ const inject=['slots','sidebarRight','sidebarRightTabs','uiWorkspace','layout'];
251
+ function apply(ctx) {
252
+ report('client-apply-enter');
253
+ try {
254
+ runtime=ctx;
255
+ ctx.effect(()=>ctx.sidebarRightTabs.register({id:ID,kind:KIND,title:()=> 'Codex / Claude 上下文',priority:'extension',guide:[{id:'open',order:10,title:()=> '外部会话同步',description:()=> '查看历史并在 DSH 接手'}]}),'external-sync.tab');
256
+ ctx.effect(()=>ctx.slots.inject('sidebar.panellist',()=>ctx.slots.register({name:'sidebar.panellist',id:PANEL_ID,order:35,priority:-10,label:'Codex 同步'},Glyph)),'external-sync.nav');
257
+ ctx.effect(()=>ctx.slots.inject('main',()=>ctx.slots.register({name:'main',key:PANEL_ID},withBoundary(props=>h(Panel,{...props,main:true})))),'external-sync.main');
258
+ ctx.effect(()=>ctx.slots.inject('sidebar.footer.action',()=>ctx.slots.register({name:'sidebar.footer.action',id:ID+'.footer',order:35,label:'外部会话同步'},OpenButton)),'external-sync.footer');
259
+ ctx.effect(()=>ctx.slots.inject('sidebar.footer.action',()=>ctx.slots.register({name:'sidebar.footer.action',id:ID+'.footer.archive',order:36,label:'旧会话归档'},ArchiveFooterButton)),'external-sync.footer-archive');
260
+ ctx.effect(()=>ctx.slots.inject('sidebar.footer.action',()=>ctx.slots.register({name:'sidebar.footer.action',id:ID+'.footer.delete',order:37,label:'删除已归档'},DeleteArchivedFooterButton)),'external-sync.footer-delete');
261
+ ctx.effect(()=>ctx.slots.inject('conversation.session.header.utilities',()=>ctx.slots.register({name:'conversation.session.header.utilities',id:ID+'.header',order:35,label:'会话同步'},NativeMarker)),'external-sync.header');
262
+ 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
+ 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
+ ctx.effect(()=>{
265
+ report('client-mounted',{version:'1.2.1'});
266
+ const initial=setTimeout(()=>{try{ctx.sidebarRight.openTab(KIND);}catch{}},500);
267
+ return()=>clearTimeout(initial);
268
+ },'external-sync.initial-panel');
269
+ } catch(error) {report('client-apply-error',{error:error.message});throw error;}
270
+ }
271
+ return {apply,inject};
272
+ }});
273
+
274
+ // build-marker: delete-visible-1.7.3
@@ -0,0 +1,6 @@
1
+ # Bundle patch for dsh-plugin-external-session-sync.
2
+ # Installing this bundle inserts one Host row that also carries the browser half
3
+ # declared under `dsh.client` in package.json.
4
+ - insert:
5
+ - id: external-session-sync-native
6
+ name: dsh-plugin-external-session-sync
package/discovery.js ADDED
@@ -0,0 +1,43 @@
1
+ import fs from 'node:fs';
2
+ import {listCodexSessions,listCodexThreadsFromDb} from './readers.js';
3
+
4
+ function head(file) {
5
+ let fd;
6
+ try {
7
+ fd=fs.openSync(file,'r');
8
+ const buffer=Buffer.alloc(64*1024);
9
+ const size=fs.readSync(fd,buffer,0,buffer.length,0);
10
+ for(const line of buffer.toString('utf8',0,size).split('\n').slice(0,12)) {
11
+ try {const event=JSON.parse(line);if(event.type==='session_meta')return event.payload || {};}catch{}
12
+ }
13
+ }catch{}finally{if(fd!==undefined)fs.closeSync(fd);}
14
+ return {};
15
+ }
16
+
17
+ // Scan directories ONCE per request; do not rescan the entire tree per thread.
18
+ // Include fresh rollouts even while Codex is still committing its SQLite row.
19
+ export function discoverCodexThreads() {
20
+ let rows=[];
21
+ try {rows=listCodexThreadsFromDb();}catch{}
22
+ const groups=new Map(rows.map(row=>[row.id,{...row,files:[]}]));
23
+ const metadata=new Map(rows.map(row=>[row.id,{...row,rolloutPath:row.file}]));
24
+ for(const rollout of listCodexSessions({threads:metadata})) {
25
+ let group=groups.get(rollout.id);
26
+ if(!group) {
27
+ const meta=head(rollout.file);
28
+ group={...rollout,cwd:meta.cwd || rollout.cwd,createdAt:Date.parse(meta.timestamp)||rollout.startedAt,title:rollout.title || null,isSubagent:!!(meta.agent_path || meta.parent_thread_id),files:[]};
29
+ groups.set(rollout.id,group);
30
+ }
31
+ group.files.push(rollout.file);
32
+ }
33
+ return [...groups.values()].map(row=>{
34
+ // Honor an index pointer outside the usual directories as well.
35
+ if(row.file && !row.files.some(file=>file.replace(/^\\\\\?\\/,'')===row.file.replace(/^\\\\\?\\/,'')) && fs.existsSync(row.file))row.files.push(row.file);
36
+ let totalBytes=0,newestMtime=row.updatedAt || 0,latest=row.file || null;
37
+ for(const file of row.files) {
38
+ try {const stat=fs.statSync(file);totalBytes+=stat.size;if(stat.mtimeMs>=newestMtime){newestMtime=stat.mtimeMs;latest=file;}}catch{}
39
+ }
40
+ const {files,...item}=row;
41
+ return {...item,file:latest,source:'codex',bytes:totalBytes || undefined,updatedAt:newestMtime || null,rolloutCount:files.length,revision:`${row.id}:${row.updatedAt || 0}:${newestMtime}:${totalBytes}:${row.userMessages || 0}:${row.assistantMessages || 0}`};
42
+ });
43
+ }