-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathapp.methods.session-actions.mjs
More file actions
632 lines (588 loc) · 26.9 KB
/
Copy pathapp.methods.session-actions.mjs
File metadata and controls
632 lines (588 loc) · 26.9 KB
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
import {
normalizeConfigTemplateDiffConfirmEnabled,
persistConfigTemplateDiffConfirmEnabledToStorage
} from './config-template-confirm-pref.mjs';
export function createSessionActionMethods(options = {}) {
const {
api,
apiBase
} = options;
return {
getResumeCommandTitle(session) {
return (typeof this.t === 'function' ? this.t('sessions.copyResume') : 'Copy resume command');
},
getSessionStandaloneContext() {
try {
const url = new URL(window.location.href);
if (url.pathname !== '/session') {
return { requested: false, params: null, error: '' };
}
const source = (url.searchParams.get('source') || '').trim().toLowerCase();
const sessionId = (url.searchParams.get('sessionId') || url.searchParams.get('id') || '').trim();
const filePath = (url.searchParams.get('filePath') || url.searchParams.get('path') || '').trim();
const maxMessagesRaw = (url.searchParams.get('maxMessages') || '').trim();
const maxMessages = Number(maxMessagesRaw);
let error = '';
if (!source) {
error = '缺少 source 参数';
} else if (source !== 'codex' && source !== 'claude') {
error = 'source 仅支持 codex 或 claude';
}
if (!sessionId && !filePath) {
error = error ? `${error},还缺少 sessionId 或 filePath` : '缺少 sessionId 或 filePath 参数';
}
if (error) {
return { requested: true, params: null, error };
}
return {
requested: true,
params: {
source,
sessionId,
filePath,
maxMessages: Number.isFinite(maxMessages) && maxMessages > 0 ? Math.floor(maxMessages) : 0
},
error: ''
};
} catch (_) {
return { requested: false, params: null, error: '' };
}
},
initSessionStandalone() {
const context = this.getSessionStandaloneContext();
if (!context.requested) return;
this.sessionStandalone = true;
this.mainTab = 'sessions';
this.prepareSessionTabRender();
if (context.error || !context.params) {
this.sessionStandaloneError = `会话链接参数不完整:${context.error || '参数解析失败'}`;
return;
}
const sourceLabel = context.params.source === 'codex' ? 'Codex' : 'Claude Code';
this.activeSession = {
source: context.params.source,
sourceLabel,
sessionId: context.params.sessionId,
filePath: context.params.filePath,
title: context.params.sessionId || context.params.filePath || '会话',
maxMessages: context.params.maxMessages || 50
};
this.activeSessionMessages = [];
this.activeSessionDetailError = '';
this.activeSessionDetailClipped = false;
this.cancelSessionTimelineSync();
this.sessionTimelineActiveKey = '';
this.clearSessionTimelineRefs();
this.sessionStandaloneError = '';
this.sessionStandaloneText = '';
this.sessionStandaloneTitle = this.activeSession.title || '会话';
this.sessionStandaloneSourceLabel = sourceLabel;
this.loadSessionStandalonePlain();
},
canBuildStandaloneUrl(session) {
return !!this.buildSessionStandaloneUrl(session);
},
buildSessionStandaloneUrl(session) {
if (!session) return '';
const source = typeof session.source === 'string' ? session.source.trim().toLowerCase() : '';
if (!source || (source !== 'codex' && source !== 'claude')) return '';
const sessionId = typeof session.sessionId === 'string' ? session.sessionId.trim() : '';
const filePath = typeof session.filePath === 'string' ? session.filePath.trim() : '';
if (!sessionId && !filePath) return '';
const origin = window.location.origin && window.location.origin !== 'null'
? window.location.origin
: (typeof apiBase === 'string' ? apiBase.trim() : '');
if (!origin) return '';
const params = new URLSearchParams();
params.set('source', source);
if (sessionId) params.set('sessionId', sessionId);
if (filePath) params.set('filePath', filePath);
return `${origin}/session?${params.toString()}`;
},
async copySessionLink(session) {
const url = this.buildSessionStandaloneUrl(session);
if (!url) {
this.showMessage('无法生成链接', 'error');
return;
}
const ok = this.fallbackCopyText(url);
if (ok) {
this.showMessage('已复制链接', 'success');
return;
}
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(url);
this.showMessage('已复制链接', 'success');
return;
}
} catch (_) {}
this.showMessage(this.t('toast.copy.fail'), 'error');
},
openSessionLink(session) {
const url = this.buildSessionStandaloneUrl(session);
if (!url) { this.showMessage(this.t('toast.link.fail'), 'error'); return; }
window.open(url, '_blank', 'noopener,noreferrer');
},
getSessionFilePath(session) {
const filePath = typeof session?.filePath === 'string' ? session.filePath.trim() : '';
return filePath;
},
async copySessionPath(session) {
const filePath = this.getSessionFilePath(session);
if (!filePath) {
this.showMessage('无本地文件路径', 'error');
return;
}
const ok = this.fallbackCopyText(filePath);
if (ok) {
this.showMessage('已复制路径', 'success');
return;
}
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(filePath);
this.showMessage('已复制路径', 'success');
return;
}
} catch (_) {}
this.showMessage(this.t('toast.copy.fail'), 'error');
},
getSessionExportKey(session) {
return `${session.source || 'unknown'}:${session.sessionId || ''}:${session.filePath || ''}`;
},
isResumeCommandAvailable(session) {
if (!session) return false;
const source = String(session.source || '').trim().toLowerCase();
const sessionId = typeof session.sessionId === 'string' ? session.sessionId.trim() : '';
const filePath = typeof session.filePath === 'string' ? session.filePath.trim() : '';
if (source === 'claude') {
return !!sessionId || !!this.extractClaudeResumeKeyFromFilePath(filePath);
}
if (source === 'gemini') {
return !!sessionId || !!this.extractClaudeResumeKeyFromFilePath(filePath);
}
return (source === 'codex' || source === 'codebuddy' || source === 'gemini') && !!sessionId;
},
isCloneAvailable(session) {
if (!session) return false;
const source = String(session.source || '').trim().toLowerCase();
const sessionId = typeof session.sessionId === 'string' ? session.sessionId.trim() : '';
const filePath = typeof session.filePath === 'string' ? session.filePath.trim() : '';
return source === 'codex' && (!!sessionId || !!filePath);
},
isDeleteAvailable(session) {
if (!session) return false;
const source = String(session.source || '').trim().toLowerCase();
if (source !== 'codex' && source !== 'claude') return false;
const sessionId = typeof session.sessionId === 'string' ? session.sessionId.trim() : '';
const filePath = typeof session.filePath === 'string' ? session.filePath.trim() : '';
return !!sessionId || !!filePath;
},
buildResumeCommand(session) {
const source = session && session.source ? String(session.source).trim().toLowerCase() : '';
const sessionId = session && session.sessionId ? String(session.sessionId).trim() : '';
const filePath = session && session.filePath ? String(session.filePath).trim() : '';
const resumeKey = (source === 'claude' || source === 'gemini')
? (sessionId || this.extractClaudeResumeKeyFromFilePath(filePath))
: sessionId;
const arg = this.quoteResumeArg(resumeKey);
if (source === 'codebuddy') {
return `codebuddy -r ${arg}`;
}
if (source === 'gemini') {
return `gemini -r ${arg}`;
}
if (source === 'claude') {
return `claude --dangerously-skip-permissions -r ${arg}`;
}
return `codex --yolo resume ${arg}`;
},
extractClaudeResumeKeyFromFilePath(filePath) {
const value = typeof filePath === 'string' ? filePath.trim() : '';
if (!value) return '';
const normalized = value.replace(/\\/g, '/');
const base = normalized.split('/').pop() || '';
if (!base) return '';
const lower = base.toLowerCase();
if (lower.endsWith('.jsonl')) {
return base.slice(0, -6);
}
if (lower.endsWith('.json')) {
return base.slice(0, -5);
}
return base;
},
quoteShellArg(value) {
const text = typeof value === 'string' ? value : String(value || '');
if (!text) return "''";
if (/^[a-zA-Z0-9._/:@~+=-]+$/.test(text)) return text;
const escaped = text.replace(/'/g, "'\\''");
return `'${escaped}'`;
},
quoteResumeArg(value) {
return this.quoteShellArg(value);
},
normalizeShareCommandPrefix(value) {
const normalized = typeof value === 'string' ? value.trim().toLowerCase() : '';
if (normalized === 'codexmate') {
return 'codexmate';
}
return 'npm start';
},
normalizeSessionTrashEnabled(value) {
if (value === false) return false;
const normalized = typeof value === 'string' ? value.trim().toLowerCase() : '';
if (normalized === '0' || normalized === 'false' || normalized === 'off' || normalized === 'no') {
return false;
}
return true;
},
normalizeConfigTemplateDiffConfirmEnabled(value) {
return normalizeConfigTemplateDiffConfirmEnabled(value);
},
setSessionTrashEnabled(value) {
const enabled = this.normalizeSessionTrashEnabled(value);
this.sessionTrashEnabled = enabled;
try {
localStorage.setItem('codexmateSessionTrashEnabled', enabled ? 'true' : 'false');
} catch (_) {}
},
setConfigTemplateDiffConfirmEnabled(value) {
const enabled = this.normalizeConfigTemplateDiffConfirmEnabled(value);
this.configTemplateDiffConfirmEnabled = enabled;
persistConfigTemplateDiffConfirmEnabledToStorage(enabled);
},
getShareCommandPrefixInvocation() {
const prefix = this.normalizeShareCommandPrefix(this.shareCommandPrefix);
return prefix === 'codexmate' ? 'codexmate' : 'npm start --';
},
setShareCommandPrefix(value) {
const normalized = this.normalizeShareCommandPrefix(value);
this.shareCommandPrefix = normalized;
try {
localStorage.setItem('codexmateShareCommandPrefix', normalized);
} catch (_) {}
},
fallbackCopyText(text) {
let textarea = null;
try {
textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed';
textarea.style.top = '-9999px';
textarea.style.left = '-9999px';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
return document.execCommand('copy');
} catch (_) {
return false;
} finally {
if (textarea && textarea.parentNode) {
textarea.parentNode.removeChild(textarea);
}
}
},
copyAgentsContent() {
const text = typeof this.agentsContent === 'string' ? this.agentsContent : '';
if (!text) {
this.showMessage(this.t('toast.copy.empty'), 'info');
return;
}
const ok = this.fallbackCopyText(text);
if (ok) {
this.showMessage(this.t('toast.copy.ok'), 'success');
return;
}
this.showMessage(this.t('toast.copy.fail'), 'error');
},
exportAgentsContent() {
const text = typeof this.agentsContent === 'string' ? this.agentsContent : '';
if (!text) {
this.showMessage('没有可导出内容', 'info');
return;
}
const now = new Date();
const year = String(now.getFullYear());
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hour = String(now.getHours()).padStart(2, '0');
const minute = String(now.getMinutes()).padStart(2, '0');
const second = String(now.getSeconds()).padStart(2, '0');
const fileName = `agent-${year}${month}${day}-${hour}${minute}${second}.txt`;
this.downloadTextFile(fileName, text, 'text/plain;charset=utf-8');
this.showMessage(`已导出 ${fileName}`, 'success');
},
async copyInstallCommand(cmd) {
const text = typeof cmd === 'string' ? cmd.trim() : '';
if (!text) {
this.showMessage(this.t('toast.copy.empty'), 'info');
return;
}
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
this.showMessage('已复制命令', 'success');
return;
}
} catch (_) {}
const ok = this.fallbackCopyText(text);
if (ok) {
this.showMessage('已复制命令', 'success');
return;
}
this.showMessage(this.t('toast.copy.fail'), 'error');
},
async copyResumeCommand(session) {
if (!this.isResumeCommandAvailable(session)) {
this.showMessage('不支持此操作', 'error');
return;
}
const command = this.buildResumeCommand(session);
const ok = this.fallbackCopyText(command);
if (ok) {
this.showMessage(this.t('toast.copy.ok'), 'success');
return;
}
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(command);
this.showMessage(this.t('toast.copy.ok'), 'success');
return;
}
} catch (_) {}
this.showMessage(this.t('toast.copy.fail'), 'error');
},
buildProviderShareCommand(payload) {
if (!payload || typeof payload !== 'object') return '';
const name = typeof payload.name === 'string' ? payload.name.trim() : '';
const baseUrl = typeof payload.baseUrl === 'string' ? payload.baseUrl.trim() : '';
const apiKey = typeof payload.apiKey === 'string' ? payload.apiKey : '';
const model = typeof payload.model === 'string' ? payload.model.trim() : '';
const bridge = typeof payload.bridge === 'string' ? payload.bridge.trim() : '';
if (!name || !baseUrl) return '';
const cli = this.getShareCommandPrefixInvocation();
const nameArg = this.quoteShellArg(name);
const urlArg = this.quoteShellArg(baseUrl);
const keyArg = apiKey ? this.quoteShellArg(apiKey) : '';
const switchCmd = `${cli} switch ${nameArg}`;
const bridgeArgs = bridge ? ` --bridge ${this.quoteShellArg(bridge)}` : '';
const addCmd = apiKey
? `${cli} add ${nameArg} ${urlArg} ${keyArg}${bridgeArgs}`
: `${cli} add ${nameArg} ${urlArg}${bridgeArgs}`;
const modelCmd = model ? ` && ${cli} use ${this.quoteShellArg(model)}` : '';
return `${addCmd} && ${switchCmd}${modelCmd}`;
},
buildClaudeShareCommand(payload) {
if (!payload || typeof payload !== 'object') return '';
const baseUrl = typeof payload.baseUrl === 'string' ? payload.baseUrl.trim() : '';
const apiKey = typeof payload.apiKey === 'string' ? payload.apiKey : '';
const model = typeof payload.model === 'string' && payload.model.trim()
? payload.model.trim()
: 'glm-4.7';
const targetApiRaw = typeof payload.targetApi === 'string' ? payload.targetApi.trim().toLowerCase() : '';
const targetApi = targetApiRaw === 'chat_completions' || targetApiRaw === 'chat-completions' || targetApiRaw === 'chat/completions'
? 'chat_completions'
: (targetApiRaw === 'ollama' ? 'ollama' : 'responses');
if (!baseUrl || (!apiKey && targetApi !== 'ollama')) return '';
const urlArg = this.quoteShellArg(baseUrl);
const keyArg = this.quoteShellArg(apiKey);
const modelArg = this.quoteShellArg(model);
const targetArg = targetApi !== 'responses' ? ` --target-api ${this.quoteShellArg(targetApi)}` : '';
return `${this.getShareCommandPrefixInvocation()} claude ${urlArg} ${keyArg} ${modelArg}${targetArg}`;
},
async copyProviderShareCommand(provider) {
const name = provider && typeof provider.name === 'string' ? provider.name.trim() : '';
if (!name) {
this.showMessage('参数无效', 'error');
return;
}
if (!this.shouldAllowProviderShare(provider)) {
this.showMessage('不可分享', 'info');
return;
}
if (this.providerShareLoading[name]) {
return;
}
this.providerShareLoading[name] = true;
try {
const res = await api('export-provider', { name });
if (res && res.error) {
this.showMessage(res.error, 'error');
return;
}
const command = this.buildProviderShareCommand(res && res.payload ? res.payload : null);
if (!command) {
this.showMessage('生成命令失败', 'error');
return;
}
const ok = this.fallbackCopyText(command);
if (ok) {
this.showMessage(this.t('toast.copy.ok'), 'success');
return;
}
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(command);
this.showMessage(this.t('toast.copy.ok'), 'success');
return;
}
} catch (_) {}
this.showMessage(this.t('toast.copy.fail'), 'error');
} catch (_) {
this.showMessage('生成命令失败', 'error');
} finally {
this.providerShareLoading[name] = false;
}
},
async copyClaudeShareCommand(name) {
const config = this.claudeConfigs[name];
if (!config) {
this.showMessage('配置不存在', 'error');
return;
}
if (this.claudeShareLoading[name]) return;
this.claudeShareLoading[name] = true;
try {
const res = await api('export-claude-share', { config });
if (res && res.error) {
this.showMessage(res.error, 'error');
return;
}
const command = this.buildClaudeShareCommand(res && res.payload ? res.payload : null);
if (!command) {
this.showMessage('生成命令失败', 'error');
return;
}
const ok = this.fallbackCopyText(command);
if (ok) {
this.showMessage(this.t('toast.copy.ok'), 'success');
return;
}
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(command);
this.showMessage(this.t('toast.copy.ok'), 'success');
return;
}
} catch (_) {}
this.showMessage(this.t('toast.copy.fail'), 'error');
} catch (_) {
this.showMessage('生成命令失败', 'error');
} finally {
this.claudeShareLoading[name] = false;
}
},
async cloneSession(session) {
if (!this.isCloneAvailable(session)) {
this.showMessage('不支持此操作', 'error');
return;
}
const key = this.getSessionExportKey(session);
if (this.sessionCloning[key]) {
return;
}
this.sessionCloning[key] = true;
try {
const res = await api('clone-session', {
source: session.source,
sessionId: session.sessionId,
filePath: session.filePath
});
if (res.error) {
this.showMessage(res.error, 'error');
return;
}
this.showMessage(this.t('toast.operation.success'), 'success');
if (typeof this.invalidateSessionsUsageData === 'function') {
this.invalidateSessionsUsageData({ preserveList: true });
}
try {
await this.loadSessions();
if (res.sessionId) {
const matched = this.sessionsList.find(item => item.source === 'codex' && item.sessionId === res.sessionId);
if (matched) {
await this.selectSession(matched);
}
}
} catch (_) {
// The clone already succeeded remotely; keep the success result.
}
} catch (_) {
this.showMessage('克隆失败', 'error');
} finally {
this.sessionCloning[key] = false;
}
},
async deleteSession(session) {
if (!this.isDeleteAvailable(session)) {
this.showMessage('不支持此操作', 'error');
return;
}
const useTrash = this.sessionTrashEnabled !== false;
if (!useTrash && typeof this.requestConfirmDialog === 'function') {
const confirmed = await this.requestConfirmDialog({
title: '直接删除会话',
message: '关闭回收站后,删除会话将直接永久删除,且无法恢复。',
confirmText: '直接删除',
cancelText: '取消',
danger: true
});
if (!confirmed) {
return;
}
}
const key = this.getSessionExportKey(session);
if (this.sessionDeleting[key]) {
return;
}
this.sessionDeleting[key] = true;
try {
const action = useTrash ? 'trash-session' : 'delete-session';
const res = await api(action, {
source: session.source,
sessionId: session.sessionId,
filePath: session.filePath
});
if (!res || res.error) {
this.showMessage((res && res.error) || '删除失败', 'error');
return;
}
this.removeSessionPin(session);
if (useTrash) {
this.invalidateSessionTrashRequests();
this.showMessage('已移入回收站', 'success');
if (this.sessionTrashLoadedOnce) {
this.prependSessionTrashItem(this.buildSessionTrashItemFromSession(session, res), {
totalCount: res && res.totalCount !== undefined ? res.totalCount : undefined
});
} else {
this.sessionTrashTotalCount = this.normalizeSessionTrashTotalCount(
res && res.totalCount !== undefined
? res.totalCount
: (this.normalizeSessionTrashTotalCount(this.sessionTrashTotalCount, this.sessionTrashItems) + 1),
this.sessionTrashItems
);
}
} else {
this.showMessage('已删除', 'success');
}
if (typeof this.invalidateSessionsUsageData === 'function') {
this.invalidateSessionsUsageData({ preserveList: true });
}
try {
await this.removeSessionFromCurrentList(session);
} catch (_) {
// The delete already succeeded remotely; keep the success result.
}
} catch (_) {
this.showMessage(this.t('toast.delete.fail'), 'error');
} finally {
this.sessionDeleting[key] = false;
}
}
};
}