codexmate 0.0.19 → 0.0.20

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.
Files changed (67) hide show
  1. package/README.en.md +8 -4
  2. package/README.md +8 -4
  3. package/cli/config-health.js +338 -0
  4. package/cli.js +1136 -584
  5. package/lib/cli-models-utils.js +186 -27
  6. package/lib/cli-network-utils.js +117 -101
  7. package/package.json +8 -1
  8. package/web-ui/app.js +381 -5532
  9. package/web-ui/index.html +15 -2231
  10. package/web-ui/logic.agents-diff.mjs +386 -0
  11. package/web-ui/logic.claude.mjs +108 -0
  12. package/web-ui/logic.mjs +5 -793
  13. package/web-ui/logic.runtime.mjs +124 -0
  14. package/web-ui/logic.sessions.mjs +263 -0
  15. package/web-ui/modules/api.mjs +69 -0
  16. package/web-ui/modules/app.computed.dashboard.mjs +113 -0
  17. package/web-ui/modules/app.computed.index.mjs +13 -0
  18. package/web-ui/modules/app.computed.session.mjs +141 -0
  19. package/web-ui/modules/app.constants.mjs +15 -0
  20. package/web-ui/modules/app.methods.agents.mjs +493 -0
  21. package/web-ui/modules/app.methods.claude-config.mjs +174 -0
  22. package/web-ui/modules/app.methods.codex-config.mjs +640 -0
  23. package/web-ui/modules/app.methods.index.mjs +86 -0
  24. package/web-ui/modules/app.methods.install.mjs +157 -0
  25. package/web-ui/modules/app.methods.navigation.mjs +478 -0
  26. package/web-ui/modules/app.methods.openclaw-core.mjs +514 -0
  27. package/web-ui/modules/app.methods.openclaw-editing.mjs +337 -0
  28. package/web-ui/modules/app.methods.openclaw-persist.mjs +251 -0
  29. package/web-ui/modules/app.methods.providers.mjs +265 -0
  30. package/web-ui/modules/app.methods.runtime.mjs +323 -0
  31. package/web-ui/modules/app.methods.session-actions.mjs +457 -0
  32. package/web-ui/modules/app.methods.session-browser.mjs +435 -0
  33. package/web-ui/modules/app.methods.session-timeline.mjs +441 -0
  34. package/web-ui/modules/app.methods.session-trash.mjs +419 -0
  35. package/web-ui/modules/app.methods.startup-claude.mjs +406 -0
  36. package/web-ui/partials/index/layout-footer.html +69 -0
  37. package/web-ui/partials/index/layout-header.html +337 -0
  38. package/web-ui/partials/index/modal-config-template-agents.html +125 -0
  39. package/web-ui/partials/index/modal-confirm-toast.html +32 -0
  40. package/web-ui/partials/index/modal-health-check.html +72 -0
  41. package/web-ui/partials/index/modal-openclaw-config.html +275 -0
  42. package/web-ui/partials/index/modal-skills.html +184 -0
  43. package/web-ui/partials/index/modals-basic.html +196 -0
  44. package/web-ui/partials/index/panel-config-claude.html +100 -0
  45. package/web-ui/partials/index/panel-config-codex.html +237 -0
  46. package/web-ui/partials/index/panel-config-openclaw.html +84 -0
  47. package/web-ui/partials/index/panel-market.html +174 -0
  48. package/web-ui/partials/index/panel-sessions.html +387 -0
  49. package/web-ui/partials/index/panel-settings.html +166 -0
  50. package/web-ui/source-bundle.cjs +233 -0
  51. package/web-ui/styles/base-theme.css +373 -0
  52. package/web-ui/styles/controls-forms.css +354 -0
  53. package/web-ui/styles/feedback.css +108 -0
  54. package/web-ui/styles/health-check-dialog.css +144 -0
  55. package/web-ui/styles/layout-shell.css +330 -0
  56. package/web-ui/styles/modals-core.css +449 -0
  57. package/web-ui/styles/navigation-panels.css +381 -0
  58. package/web-ui/styles/openclaw-structured.css +266 -0
  59. package/web-ui/styles/responsive.css +416 -0
  60. package/web-ui/styles/sessions-list.css +414 -0
  61. package/web-ui/styles/sessions-preview.css +405 -0
  62. package/web-ui/styles/sessions-toolbar-trash.css +243 -0
  63. package/web-ui/styles/sessions-usage.css +276 -0
  64. package/web-ui/styles/skills-list.css +298 -0
  65. package/web-ui/styles/skills-market.css +335 -0
  66. package/web-ui/styles/titles-cards.css +407 -0
  67. package/web-ui/styles.css +16 -4668
package/web-ui/logic.mjs CHANGED
@@ -1,793 +1,5 @@
1
- // 逻辑纯函数:供 Web UI 与单元测试共享
2
- export const DEFAULT_API_BODY_LIMIT_BYTES = 4 * 1024 * 1024;
3
- const LARGE_DIFF_LINE_LIMIT = 3000;
4
- const LARGE_DIFF_SYNC_LOOKAHEAD = 64;
5
-
6
- function measureUtf8ByteLength(input) {
7
- const text = typeof input === 'string' ? input : String(input ?? '');
8
- if (typeof TextEncoder === 'function') {
9
- return new TextEncoder().encode(text).length;
10
- }
11
- if (typeof Buffer !== 'undefined' && typeof Buffer.byteLength === 'function') {
12
- return Buffer.byteLength(text, 'utf8');
13
- }
14
- return unescape(encodeURIComponent(text)).length;
15
- }
16
-
17
- function buildApiRequestByteLength(action, params) {
18
- return measureUtf8ByteLength(JSON.stringify({ action, params }));
19
- }
20
-
21
- function normalizeDiffText(input) {
22
- const safe = typeof input === 'string' ? input : '';
23
- const withoutBom = safe.charCodeAt(0) === 0xFEFF ? safe.slice(1) : safe;
24
- return withoutBom.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
25
- }
26
-
27
- function splitDiffLines(input) {
28
- let normalized = normalizeDiffText(input);
29
- if (!normalized) return [];
30
- if (normalized.endsWith('\n')) {
31
- normalized = normalized.slice(0, -1);
32
- }
33
- if (!normalized) return [];
34
- return normalized.split('\n');
35
- }
36
-
37
- function buildDiffLcsMatrix(beforeLines, afterLines) {
38
- const rows = beforeLines.length + 1;
39
- const cols = afterLines.length + 1;
40
- const matrix = Array.from({ length: rows }, () => new Array(cols).fill(0));
41
- for (let i = 1; i < rows; i += 1) {
42
- const beforeLine = beforeLines[i - 1];
43
- for (let j = 1; j < cols; j += 1) {
44
- if (beforeLine === afterLines[j - 1]) {
45
- matrix[i][j] = matrix[i - 1][j - 1] + 1;
46
- } else {
47
- const up = matrix[i - 1][j];
48
- const left = matrix[i][j - 1];
49
- matrix[i][j] = up >= left ? up : left;
50
- }
51
- }
52
- }
53
- return matrix;
54
- }
55
-
56
- function countDiffStats(lines) {
57
- let added = 0;
58
- let removed = 0;
59
- let unchanged = 0;
60
- for (const line of lines) {
61
- if (line.type === 'add') {
62
- added += 1;
63
- } else if (line.type === 'del') {
64
- removed += 1;
65
- } else {
66
- unchanged += 1;
67
- }
68
- }
69
- return { added, removed, unchanged };
70
- }
71
-
72
- function buildCollapsedContextLine(hiddenCount) {
73
- return {
74
- type: 'context',
75
- value: `... ${hiddenCount} unchanged lines ...`,
76
- oldNumber: null,
77
- newNumber: null
78
- };
79
- }
80
-
81
- function compactContextRuns(lines, contextSize = 3) {
82
- const compacted = [];
83
- const keepCount = Number.isFinite(contextSize) ? Math.max(1, Math.floor(contextSize)) : 3;
84
- let index = 0;
85
- while (index < lines.length) {
86
- if (!lines[index] || lines[index].type !== 'context') {
87
- compacted.push(lines[index]);
88
- index += 1;
89
- continue;
90
- }
91
- const start = index;
92
- while (index < lines.length && lines[index] && lines[index].type === 'context') {
93
- index += 1;
94
- }
95
- const run = lines.slice(start, index);
96
- if (run.length <= keepCount * 2 + 1) {
97
- compacted.push(...run);
98
- continue;
99
- }
100
- compacted.push(...run.slice(0, keepCount));
101
- compacted.push(buildCollapsedContextLine(run.length - keepCount * 2));
102
- compacted.push(...run.slice(-keepCount));
103
- }
104
- return compacted;
105
- }
106
-
107
- function buildExactDiffLines(beforeLines, afterLines) {
108
- const matrix = buildDiffLcsMatrix(beforeLines, afterLines);
109
- const lines = [];
110
- let i = beforeLines.length;
111
- let j = afterLines.length;
112
- while (i > 0 || j > 0) {
113
- if (i > 0 && j > 0 && beforeLines[i - 1] === afterLines[j - 1]) {
114
- lines.push({
115
- type: 'context',
116
- value: beforeLines[i - 1],
117
- oldNumber: i,
118
- newNumber: j
119
- });
120
- i -= 1;
121
- j -= 1;
122
- continue;
123
- }
124
- const canAdd = j > 0;
125
- const canDel = i > 0;
126
- if (canAdd && (!canDel || matrix[i][j - 1] >= matrix[i - 1][j])) {
127
- lines.push({
128
- type: 'add',
129
- value: afterLines[j - 1],
130
- oldNumber: null,
131
- newNumber: j
132
- });
133
- j -= 1;
134
- continue;
135
- }
136
- if (canDel) {
137
- lines.push({
138
- type: 'del',
139
- value: beforeLines[i - 1],
140
- oldNumber: i,
141
- newNumber: null
142
- });
143
- i -= 1;
144
- }
145
- }
146
- lines.reverse();
147
- return lines;
148
- }
149
-
150
- function findSyncPointInWindow(beforeLines, afterLines, beforeIndex, afterIndex, maxBeforeOffset, maxAfterOffset) {
151
- if (maxBeforeOffset <= 0 && maxAfterOffset <= 0) {
152
- return null;
153
- }
154
-
155
- for (let offset = 1; offset <= maxAfterOffset; offset += 1) {
156
- if (beforeLines[beforeIndex] === afterLines[afterIndex + offset]) {
157
- return { beforeIndex, afterIndex: afterIndex + offset };
158
- }
159
- }
160
- for (let offset = 1; offset <= maxBeforeOffset; offset += 1) {
161
- if (beforeLines[beforeIndex + offset] === afterLines[afterIndex]) {
162
- return { beforeIndex: beforeIndex + offset, afterIndex };
163
- }
164
- }
165
-
166
- const maxDistance = maxBeforeOffset + maxAfterOffset;
167
- for (let distance = 2; distance <= maxDistance; distance += 1) {
168
- const beforeStart = Math.max(1, distance - maxAfterOffset);
169
- const beforeEnd = Math.min(maxBeforeOffset, distance - 1);
170
- for (let beforeOffset = beforeStart; beforeOffset <= beforeEnd; beforeOffset += 1) {
171
- const afterOffset = distance - beforeOffset;
172
- if (beforeLines[beforeIndex + beforeOffset] === afterLines[afterIndex + afterOffset]) {
173
- return {
174
- beforeIndex: beforeIndex + beforeOffset,
175
- afterIndex: afterIndex + afterOffset
176
- };
177
- }
178
- }
179
- }
180
- return null;
181
- }
182
-
183
- function findNextSyncPoint(beforeLines, afterLines, beforeIndex, afterIndex, lookahead = LARGE_DIFF_SYNC_LOOKAHEAD) {
184
- const remainingBefore = Math.max(0, beforeLines.length - beforeIndex - 1);
185
- const remainingAfter = Math.max(0, afterLines.length - afterIndex - 1);
186
- const maxWindow = Math.max(remainingBefore, remainingAfter);
187
- if (maxWindow <= 0) {
188
- return null;
189
- }
190
-
191
- const initialWindow = Number.isFinite(lookahead)
192
- ? Math.max(1, Math.floor(lookahead))
193
- : LARGE_DIFF_SYNC_LOOKAHEAD;
194
- let window = Math.min(maxWindow, initialWindow);
195
- while (window > 0) {
196
- const syncPoint = findSyncPointInWindow(
197
- beforeLines,
198
- afterLines,
199
- beforeIndex,
200
- afterIndex,
201
- Math.min(window, remainingBefore),
202
- Math.min(window, remainingAfter)
203
- );
204
- if (syncPoint) {
205
- return syncPoint;
206
- }
207
- if (window >= maxWindow) {
208
- return null;
209
- }
210
- window = Math.min(maxWindow, window * 2);
211
- }
212
- return null;
213
- }
214
-
215
- function buildLargeDiffLines(beforeLines, afterLines) {
216
- const rawLines = [];
217
- let beforeIndex = 0;
218
- let afterIndex = 0;
219
-
220
- while (beforeIndex < beforeLines.length && afterIndex < afterLines.length) {
221
- if (beforeLines[beforeIndex] === afterLines[afterIndex]) {
222
- rawLines.push({
223
- type: 'context',
224
- value: beforeLines[beforeIndex],
225
- oldNumber: beforeIndex + 1,
226
- newNumber: afterIndex + 1
227
- });
228
- beforeIndex += 1;
229
- afterIndex += 1;
230
- continue;
231
- }
232
-
233
- const syncPoint = findNextSyncPoint(beforeLines, afterLines, beforeIndex, afterIndex);
234
- if (!syncPoint) {
235
- rawLines.push({
236
- type: 'del',
237
- value: beforeLines[beforeIndex],
238
- oldNumber: beforeIndex + 1,
239
- newNumber: null
240
- });
241
- rawLines.push({
242
- type: 'add',
243
- value: afterLines[afterIndex],
244
- oldNumber: null,
245
- newNumber: afterIndex + 1
246
- });
247
- beforeIndex += 1;
248
- afterIndex += 1;
249
- continue;
250
- }
251
-
252
- while (beforeIndex < syncPoint.beforeIndex) {
253
- rawLines.push({
254
- type: 'del',
255
- value: beforeLines[beforeIndex],
256
- oldNumber: beforeIndex + 1,
257
- newNumber: null
258
- });
259
- beforeIndex += 1;
260
- }
261
- while (afterIndex < syncPoint.afterIndex) {
262
- rawLines.push({
263
- type: 'add',
264
- value: afterLines[afterIndex],
265
- oldNumber: null,
266
- newNumber: afterIndex + 1
267
- });
268
- afterIndex += 1;
269
- }
270
- }
271
-
272
- while (beforeIndex < beforeLines.length) {
273
- rawLines.push({
274
- type: 'del',
275
- value: beforeLines[beforeIndex],
276
- oldNumber: beforeIndex + 1,
277
- newNumber: null
278
- });
279
- beforeIndex += 1;
280
- }
281
- while (afterIndex < afterLines.length) {
282
- rawLines.push({
283
- type: 'add',
284
- value: afterLines[afterIndex],
285
- oldNumber: null,
286
- newNumber: afterIndex + 1
287
- });
288
- afterIndex += 1;
289
- }
290
-
291
- return {
292
- lines: compactContextRuns(rawLines),
293
- stats: countDiffStats(rawLines)
294
- };
295
- }
296
-
297
- export function buildLineDiff(beforeText, afterText) {
298
- const beforeLines = splitDiffLines(beforeText);
299
- const afterLines = splitDiffLines(afterText);
300
- const result = (beforeLines.length > LARGE_DIFF_LINE_LIMIT || afterLines.length > LARGE_DIFF_LINE_LIMIT)
301
- ? buildLargeDiffLines(beforeLines, afterLines)
302
- : {
303
- lines: buildExactDiffLines(beforeLines, afterLines),
304
- stats: null
305
- };
306
- const stats = result.stats || countDiffStats(result.lines);
307
- return {
308
- lines: result.lines,
309
- stats,
310
- oldLineCount: beforeLines.length,
311
- newLineCount: afterLines.length,
312
- truncated: false
313
- };
314
- }
315
-
316
- export function buildAgentsDiffPreview(options = {}) {
317
- const beforeText = normalizeDiffText(options.baseContent);
318
- const afterText = normalizeDiffText(options.content);
319
- const diff = buildLineDiff(beforeText, afterText);
320
- return {
321
- ...diff,
322
- truncated: !!diff.truncated,
323
- hasChanges: diff.truncated
324
- ? beforeText !== afterText
325
- : (diff.stats.added > 0 || diff.stats.removed > 0)
326
- };
327
- }
328
-
329
- export function buildAgentsDiffPreviewRequest(options = {}) {
330
- const contextRaw = typeof options.context === 'string' ? options.context.trim() : '';
331
- const context = contextRaw || 'codex';
332
- const params = {
333
- content: typeof options.content === 'string' ? options.content : '',
334
- lineEnding: options.lineEnding === '\r\n' ? '\r\n' : '\n',
335
- context
336
- };
337
- if (context === 'openclaw-workspace') {
338
- const fileName = typeof options.fileName === 'string' ? options.fileName.trim() : '';
339
- if (fileName) {
340
- params.fileName = fileName;
341
- }
342
- }
343
-
344
- const maxRequestBytes = Number.isFinite(options.maxRequestBytes)
345
- ? Math.max(1024, Math.floor(options.maxRequestBytes))
346
- : DEFAULT_API_BODY_LIMIT_BYTES;
347
- const hasBaseContent = typeof options.baseContent === 'string';
348
- const paramsWithBaseContent = hasBaseContent
349
- ? { ...params, baseContent: options.baseContent }
350
- : params;
351
- if (!hasBaseContent) {
352
- return {
353
- params,
354
- omittedBaseContent: false,
355
- exceedsBodyLimit: buildApiRequestByteLength('preview-agents-diff', params) > maxRequestBytes
356
- };
357
- }
358
- if (buildApiRequestByteLength('preview-agents-diff', paramsWithBaseContent) <= maxRequestBytes) {
359
- return {
360
- params: paramsWithBaseContent,
361
- omittedBaseContent: false,
362
- exceedsBodyLimit: false
363
- };
364
- }
365
- return {
366
- params,
367
- omittedBaseContent: true,
368
- exceedsBodyLimit: buildApiRequestByteLength('preview-agents-diff', params) > maxRequestBytes
369
- };
370
- }
371
-
372
- export function isAgentsDiffPreviewPayloadTooLarge(result = {}) {
373
- const status = Number(result && result.status);
374
- const errorCode = result && typeof result.errorCode === 'string' ? result.errorCode : '';
375
- return status === 413 || errorCode === 'payload-too-large';
376
- }
377
-
378
- export function shouldApplyAgentsDiffPreviewResponse(options = {}) {
379
- const requestToken = options && options.requestToken;
380
- const activeRequestToken = options && options.activeRequestToken;
381
- if (!requestToken || requestToken !== activeRequestToken) {
382
- return false;
383
- }
384
- if (!options || !options.isVisible) {
385
- return false;
386
- }
387
- const requestFingerprint = typeof options.requestFingerprint === 'string' ? options.requestFingerprint : '';
388
- const currentFingerprint = typeof options.currentFingerprint === 'string' ? options.currentFingerprint : '';
389
- return requestFingerprint === currentFingerprint;
390
- }
391
-
392
- export function normalizeClaudeValue(value) {
393
- return typeof value === 'string' ? value.trim() : '';
394
- }
395
-
396
- export function normalizeClaudeConfig(config) {
397
- const safe = config && typeof config === 'object' ? config : {};
398
- return {
399
- apiKey: normalizeClaudeValue(safe.apiKey),
400
- baseUrl: normalizeClaudeValue(safe.baseUrl),
401
- model: normalizeClaudeValue(safe.model),
402
- authToken: normalizeClaudeValue(safe.authToken),
403
- useKey: normalizeClaudeValue(safe.useKey),
404
- externalCredentialType: normalizeClaudeValue(safe.externalCredentialType)
405
- };
406
- }
407
-
408
- export function normalizeClaudeSettingsEnv(env) {
409
- const safe = env && typeof env === 'object' ? env : {};
410
- const apiKey = normalizeClaudeValue(safe.ANTHROPIC_API_KEY);
411
- const authToken = normalizeClaudeValue(safe.ANTHROPIC_AUTH_TOKEN);
412
- const useKey = normalizeClaudeValue(safe.CLAUDE_CODE_USE_KEY);
413
- return {
414
- apiKey,
415
- baseUrl: normalizeClaudeValue(safe.ANTHROPIC_BASE_URL),
416
- model: normalizeClaudeValue(safe.ANTHROPIC_MODEL) || 'glm-4.7',
417
- authToken,
418
- useKey,
419
- externalCredentialType: apiKey
420
- ? ''
421
- : (authToken ? 'auth-token' : (useKey ? 'claude-code-use-key' : ''))
422
- };
423
- }
424
-
425
- function normalizeClaudeComparableUrl(value) {
426
- const trimmed = normalizeClaudeValue(value);
427
- if (!trimmed) return '';
428
- return trimmed.replace(/\/+$/g, '');
429
- }
430
-
431
- function hasClaudeCredential(config = {}) {
432
- return !!(config.apiKey || config.authToken || config.useKey);
433
- }
434
-
435
- export function matchClaudeConfigFromSettings(claudeConfigs = {}, env = {}) {
436
- const normalizedSettings = normalizeClaudeSettingsEnv(env);
437
- if (!normalizedSettings.baseUrl || !normalizedSettings.model || !hasClaudeCredential(normalizedSettings)) {
438
- return '';
439
- }
440
- const comparableSettingsUrl = normalizeClaudeComparableUrl(normalizedSettings.baseUrl);
441
- const entries = Object.entries(claudeConfigs || {});
442
- for (const [name, config] of entries) {
443
- const normalizedConfig = normalizeClaudeConfig(config);
444
- if (!normalizedConfig.baseUrl || !normalizedConfig.model) {
445
- continue;
446
- }
447
- if (normalizeClaudeComparableUrl(normalizedConfig.baseUrl) !== comparableSettingsUrl
448
- || normalizedConfig.model !== normalizedSettings.model) {
449
- continue;
450
- }
451
- if (normalizedSettings.apiKey && normalizedConfig.apiKey === normalizedSettings.apiKey) {
452
- return name;
453
- }
454
- if (!normalizedSettings.apiKey
455
- && normalizedConfig.apiKey === ''
456
- && normalizedConfig.externalCredentialType
457
- && normalizedConfig.externalCredentialType === normalizedSettings.externalCredentialType) {
458
- return name;
459
- }
460
- }
461
- return '';
462
- }
463
-
464
- export function findDuplicateClaudeConfigName(claudeConfigs = {}, config) {
465
- const normalized = normalizeClaudeConfig(config);
466
- if (!normalized.baseUrl || !normalized.model) {
467
- return '';
468
- }
469
- const comparableUrl = normalizeClaudeComparableUrl(normalized.baseUrl);
470
- const isExternal = !normalized.apiKey && !!normalized.externalCredentialType;
471
- if (!normalized.apiKey && !isExternal) {
472
- return '';
473
- }
474
- const entries = Object.entries(claudeConfigs || {});
475
- for (const [name, existing] of entries) {
476
- const normalizedExisting = normalizeClaudeConfig(existing);
477
- if (!normalizedExisting.baseUrl || !normalizedExisting.model) {
478
- continue;
479
- }
480
- if (normalizeClaudeComparableUrl(normalizedExisting.baseUrl) !== comparableUrl
481
- || normalizedExisting.model !== normalized.model) {
482
- continue;
483
- }
484
- if (normalized.apiKey && normalizedExisting.apiKey === normalized.apiKey) {
485
- return name;
486
- }
487
- if (isExternal
488
- && !normalizedExisting.apiKey
489
- && normalizedExisting.externalCredentialType === normalized.externalCredentialType) {
490
- return name;
491
- }
492
- }
493
- return '';
494
- }
495
-
496
- export function formatLatency(result) {
497
- if (!result) return '';
498
- if (!result.ok) return result.status ? `ERR ${result.status}` : 'ERR';
499
- const ms = typeof result.durationMs === 'number' ? result.durationMs : 0;
500
- return `${ms}ms`;
501
- }
502
-
503
- export function buildSpeedTestIssue(name, result) {
504
- if (!name || !result) return null;
505
- if (result.error) {
506
- const error = String(result.error || '');
507
- const errorLower = error.toLowerCase();
508
- if (error === 'Provider not found') {
509
- return {
510
- code: 'remote-speedtest-provider-missing',
511
- message: `提供商 ${name} 未找到,无法测速`,
512
- suggestion: '检查配置是否存在该 provider'
513
- };
514
- }
515
- if (error === 'Provider missing URL' || error === 'Missing name or url') {
516
- return {
517
- code: 'remote-speedtest-baseurl-missing',
518
- message: `提供商 ${name} 缺少 base_url`,
519
- suggestion: '补全 base_url 后重试'
520
- };
521
- }
522
- if (errorLower.includes('invalid url')) {
523
- return {
524
- code: 'remote-speedtest-invalid-url',
525
- message: `提供商 ${name} 的 base_url 无效`,
526
- suggestion: '请设置为 http/https 的完整 URL'
527
- };
528
- }
529
- if (errorLower.includes('timeout')) {
530
- return {
531
- code: 'remote-speedtest-timeout',
532
- message: `提供商 ${name} 远程测速超时`,
533
- suggestion: '检查网络或 base_url 是否可达'
534
- };
535
- }
536
- return {
537
- code: 'remote-speedtest-unreachable',
538
- message: `提供商 ${name} 远程测速失败:${error || '无法连接'}`,
539
- suggestion: '检查网络或 base_url 是否可用'
540
- };
541
- }
542
-
543
- const status = typeof result.status === 'number' ? result.status : 0;
544
- if (status === 401 || status === 403) {
545
- return {
546
- code: 'remote-speedtest-auth-failed',
547
- message: `提供商 ${name} 远程测速鉴权失败(401/403)`,
548
- suggestion: '检查 API Key 或认证方式'
549
- };
550
- }
551
- if (status >= 400) {
552
- return {
553
- code: 'remote-speedtest-http-error',
554
- message: `提供商 ${name} 远程测速返回异常状态: ${status}`,
555
- suggestion: '检查 base_url 或服务状态'
556
- };
557
- }
558
- return null;
559
- }
560
-
561
- export async function runLatestOnlyQueue(initialTarget, options = {}) {
562
- const perform = typeof options.perform === 'function'
563
- ? options.perform
564
- : async () => {};
565
- const consumePending = typeof options.consumePending === 'function'
566
- ? options.consumePending
567
- : () => '';
568
- let currentTarget = typeof initialTarget === 'string' ? initialTarget.trim() : '';
569
- let lastError = '';
570
-
571
- while (currentTarget) {
572
- try {
573
- await perform(currentTarget);
574
- lastError = '';
575
- } catch (e) {
576
- lastError = e && e.message ? e.message : 'queue task failed';
577
- }
578
- const queued = String(consumePending() || '').trim();
579
- if (!queued || queued === currentTarget) {
580
- break;
581
- }
582
- currentTarget = queued;
583
- }
584
-
585
- return {
586
- lastTarget: currentTarget,
587
- lastError
588
- };
589
- }
590
-
591
- export function shouldForceCompactLayoutMode(options = {}) {
592
- const viewportWidth = Number(options.viewportWidth || 0);
593
- const screenWidth = Number(options.screenWidth || 0);
594
- const screenHeight = Number(options.screenHeight || 0);
595
- const shortEdge = Number(options.shortEdge || (screenWidth > 0 && screenHeight > 0 ? Math.min(screenWidth, screenHeight) : 0));
596
- const maxTouchPoints = Number(options.maxTouchPoints || 0);
597
- const userAgent = typeof options.userAgent === 'string' ? options.userAgent : '';
598
- const isMobileUa = typeof options.isMobileUa === 'boolean'
599
- ? options.isMobileUa
600
- : /(Android|iPhone|iPad|iPod|Mobile)/i.test(userAgent);
601
- const coarsePointer = !!options.coarsePointer;
602
- const noHover = !!options.noHover;
603
- const isSmallPhysicalScreen = shortEdge > 0 && shortEdge <= 920;
604
- const isNarrowViewport = viewportWidth > 0 && viewportWidth <= 960;
605
- const pointerSuggestsTouchOnly = coarsePointer && noHover;
606
-
607
- if (isMobileUa) {
608
- return isNarrowViewport || isSmallPhysicalScreen;
609
- }
610
- if (!pointerSuggestsTouchOnly) {
611
- return false;
612
- }
613
- if (maxTouchPoints <= 0) {
614
- return false;
615
- }
616
- return isSmallPhysicalScreen;
617
- }
618
-
619
- // Session filtering helpers
620
- export function isSessionQueryEnabled(source) {
621
- const normalized = normalizeSessionSource(source, '');
622
- return normalized === 'codex' || normalized === 'claude' || normalized === 'all';
623
- }
624
-
625
- export function normalizeSessionSource(source, fallback = 'all') {
626
- const normalized = typeof source === 'string'
627
- ? source.trim().toLowerCase()
628
- : '';
629
- if (normalized === 'codex' || normalized === 'claude' || normalized === 'all') {
630
- return normalized;
631
- }
632
- return fallback;
633
- }
634
-
635
- export function normalizeSessionPathFilter(pathFilter) {
636
- return typeof pathFilter === 'string' ? pathFilter.trim() : '';
637
- }
638
-
639
- export function buildSessionFilterCacheState(source, pathFilter) {
640
- return {
641
- source: normalizeSessionSource(source, 'all'),
642
- pathFilter: normalizeSessionPathFilter(pathFilter)
643
- };
644
- }
645
-
646
- export function buildSessionListParams(options = {}) {
647
- const {
648
- source = 'all',
649
- pathFilter = '',
650
- query = '',
651
- roleFilter = 'all',
652
- timeRangePreset = 'all',
653
- limit = 200
654
- } = options;
655
- const queryValue = isSessionQueryEnabled(source) ? query : '';
656
- return {
657
- source,
658
- pathFilter,
659
- query: queryValue,
660
- queryMode: 'and',
661
- queryScope: 'content',
662
- contentScanLimit: 50,
663
- roleFilter,
664
- timeRangePreset,
665
- limit,
666
- forceRefresh: true
667
- };
668
- }
669
-
670
- export function normalizeSessionMessageRole(role) {
671
- const value = typeof role === 'string' ? role.trim().toLowerCase() : '';
672
- if (value === 'user' || value === 'assistant' || value === 'system') {
673
- return value;
674
- }
675
- return 'assistant';
676
- }
677
-
678
- function toRoleMeta(role) {
679
- if (role === 'user') {
680
- return { role: 'user', roleLabel: 'User', roleShort: 'U' };
681
- }
682
- if (role === 'assistant') {
683
- return { role: 'assistant', roleLabel: 'Assistant', roleShort: 'A' };
684
- }
685
- if (role === 'system') {
686
- return { role: 'system', roleLabel: 'System', roleShort: 'S' };
687
- }
688
- return { role: 'mixed', roleLabel: 'Mixed', roleShort: 'M' };
689
- }
690
-
691
- function clampTimelinePercent(percent) {
692
- return Math.max(6, Math.min(94, percent));
693
- }
694
-
695
- export function formatSessionTimelineTimestamp(timestamp) {
696
- const value = typeof timestamp === 'string' ? timestamp.trim() : '';
697
- if (!value) return '';
698
-
699
- // 优先按 ISO/常见时间串抽取,避免本地时区格式差异导致的展示抖动。
700
- const matched = value.match(/^(\d{4})-(\d{2})-(\d{2})[T\s](\d{2}):(\d{2})(?::(\d{2}))?/);
701
- if (matched) {
702
- const second = matched[6] || '00';
703
- return `${matched[2]}-${matched[3]} ${matched[4]}:${matched[5]}:${second}`;
704
- }
705
-
706
- return value;
707
- }
708
-
709
- export function buildSessionTimelineNodes(messages = [], options = {}) {
710
- const list = Array.isArray(messages) ? messages : [];
711
- const getKey = typeof options.getKey === 'function'
712
- ? options.getKey
713
- : ((_message, index) => `msg-${index}`);
714
- const total = list.length;
715
- const rawMaxMarkers = Number(options.maxMarkers);
716
- const maxMarkers = Number.isFinite(rawMaxMarkers)
717
- ? Math.max(1, Math.min(80, Math.floor(rawMaxMarkers)))
718
- : 30;
719
-
720
- const buildSingleNode = (message, index) => {
721
- const role = normalizeSessionMessageRole(message && (message.normalizedRole || message.role));
722
- const roleMeta = toRoleMeta(role);
723
- const key = String(getKey(message, index) || `msg-${index}`);
724
- const displayTime = formatSessionTimelineTimestamp(message && message.timestamp ? message.timestamp : '');
725
- const title = displayTime
726
- ? `#${index + 1} · ${roleMeta.roleLabel} · ${displayTime}`
727
- : `#${index + 1} · ${roleMeta.roleLabel}`;
728
- const percent = total <= 1 ? 0 : (index / (total - 1)) * 100;
729
- return {
730
- key,
731
- role: roleMeta.role,
732
- roleLabel: roleMeta.roleLabel,
733
- roleShort: roleMeta.roleShort,
734
- displayTime,
735
- title,
736
- percent,
737
- safePercent: clampTimelinePercent(percent)
738
- };
739
- };
740
-
741
- if (total <= maxMarkers) {
742
- return list.map((message, index) => buildSingleNode(message, index));
743
- }
744
-
745
- const nodes = [];
746
- const bucketWidth = total / maxMarkers;
747
- for (let bucket = 0; bucket < maxMarkers; bucket += 1) {
748
- let start = Math.floor(bucket * bucketWidth);
749
- if (nodes.length && start <= nodes[nodes.length - 1].endIndex) {
750
- start = nodes[nodes.length - 1].endIndex + 1;
751
- }
752
- if (start >= total) {
753
- break;
754
- }
755
- let end = Math.floor((bucket + 1) * bucketWidth) - 1;
756
- end = Math.max(start, Math.min(total - 1, end));
757
- const targetIndex = Math.min(total - 1, start + Math.floor((end - start) / 2));
758
- const targetMessage = list[targetIndex] || null;
759
- const key = String(getKey(targetMessage, targetIndex) || `msg-${targetIndex}`);
760
- const percent = total <= 1 ? 0 : (targetIndex / (total - 1)) * 100;
761
- const messagesInGroup = end - start + 1;
762
- const roleSet = new Set();
763
- for (let i = start; i <= end; i += 1) {
764
- roleSet.add(normalizeSessionMessageRole(list[i] && (list[i].normalizedRole || list[i].role)));
765
- }
766
- const roleValue = roleSet.size === 1 ? Array.from(roleSet)[0] : 'mixed';
767
- const roleMeta = toRoleMeta(roleValue);
768
- const firstTime = formatSessionTimelineTimestamp(list[start] && list[start].timestamp ? list[start].timestamp : '');
769
- const lastTime = formatSessionTimelineTimestamp(list[end] && list[end].timestamp ? list[end].timestamp : '');
770
- let displayTime = '';
771
- if (firstTime && lastTime) {
772
- displayTime = firstTime === lastTime ? firstTime : `${firstTime} ~ ${lastTime}`;
773
- } else {
774
- displayTime = firstTime || lastTime;
775
- }
776
- const titleBase = `#${start + 1}-${end + 1} · ${messagesInGroup} msgs · ${roleMeta.roleLabel}`;
777
- const title = displayTime ? `${titleBase} · ${displayTime}` : titleBase;
778
- nodes.push({
779
- key,
780
- role: roleMeta.role,
781
- roleLabel: roleMeta.roleLabel,
782
- roleShort: roleMeta.roleShort,
783
- displayTime,
784
- title,
785
- percent,
786
- safePercent: clampTimelinePercent(percent),
787
- startIndex: start,
788
- endIndex: end,
789
- messageCount: messagesInGroup
790
- });
791
- }
792
- return nodes;
793
- }
1
+ // 逻辑纯函数兼容出口:内部按职责拆分,外部保持原有导入路径不变
2
+ export * from './logic.agents-diff.mjs';
3
+ export * from './logic.claude.mjs';
4
+ export * from './logic.runtime.mjs';
5
+ export * from './logic.sessions.mjs';