@isdou/dsh-journal 0.0.0-stage → 0.1.4
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/LICENSE +10 -0
- package/README.md +118 -2
- package/assets/preview.png +0 -0
- package/client.js +528 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +6 -0
- package/index.js +84 -0
- package/lib/collector.js +226 -0
- package/lib/preferences.js +26 -0
- package/lib/range.js +86 -0
- package/lib/report-store.js +103 -0
- package/lib/report.js +328 -0
- package/lib/storage-location.js +76 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +73 -4
- package/screenshots.json +1 -0
package/client.js
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: '@isdou/dsh-journal',
|
|
3
|
+
factory(require) {
|
|
4
|
+
const React = require('react');
|
|
5
|
+
const { useState, useEffect, useRef } = React;
|
|
6
|
+
const h = React.createElement;
|
|
7
|
+
const NS = 'dshJournal';
|
|
8
|
+
const PANEL_ID = 'dsh-journal';
|
|
9
|
+
const dictionaries = {
|
|
10
|
+
zh: {
|
|
11
|
+
panel: 'DSH 日记', subtitle: '从对话与改动中,整理这段时间的工作。',
|
|
12
|
+
day: '日报', week: '周报', month: '月报', custom: '自定范围',
|
|
13
|
+
start: '开始日期', end: '结束日期', timeZone: '时区',
|
|
14
|
+
timeZoneHint: '按所选时区计算日期,包含开始和结束当天。',
|
|
15
|
+
scan: '扫描记录', scanning: '正在扫描…', generate: '生成报告', generating: '正在生成…',
|
|
16
|
+
generatingHint: '正在整理这段时间的工作。记录较多时,会先归纳再汇总。',
|
|
17
|
+
cancel: '取消', cancelled: '已取消请求。', loading: '正在加载…', retry: '重试',
|
|
18
|
+
mode: '整理方式', ai: 'AI 工作报告', local: '本地记录整理',
|
|
19
|
+
aiHint: '点击生成后,将此范围的记录发送给简报模型:{model}。',
|
|
20
|
+
aiUnavailable: '简报模型暂不可用。可先生成本地记录整理,或检查 DSH 模型设置。',
|
|
21
|
+
localHint: '直接在本机按会话整理原始记录与改动,不调用模型。',
|
|
22
|
+
sessions: '会话', messages: '消息', tools: '工具调用', changes: '文件操作', failures: '失败调用',
|
|
23
|
+
coverage: '记录范围说明', coverageIncomplete: '部分记录未能读取,这份报告可能不完整。', sourceSessions: '来源会话', noSessions: '这段时间没有找到可整理的记录。',
|
|
24
|
+
sourceHint: '只包含所选日期内记录的活动;会话标题和工作目录用于核对来源。',
|
|
25
|
+
untitled: '未命名会话', noWorkspace: '未记录工作目录', sessionId: '会话 ID',
|
|
26
|
+
report: '工作报告', read: '阅读', edit: '编辑 Markdown', save: '保存修改', saving: '正在保存…',
|
|
27
|
+
unsaved: '有未保存的修改', saved: '修改已保存。', markdown: '报告 Markdown',
|
|
28
|
+
copy: '复制', copied: '已复制。', copyFailed: '无法访问剪贴板,请在编辑模式选中文本复制,或下载 Markdown。',
|
|
29
|
+
download: '下载 Markdown', history: '历史报告', historyEmpty: '生成的报告会保存在这里。',
|
|
30
|
+
emptyTitle: '选择时间范围,生成一份工作报告',
|
|
31
|
+
emptyDescription: '可以先扫描记录核对来源,再选择 AI 总结或本地整理。',
|
|
32
|
+
initialError: '无法加载日记数据。', requestError: '请求未完成,请重试。',
|
|
33
|
+
invalidDate: '请选择有效的开始和结束日期。', invalidOrder: '结束日期不能早于开始日期。',
|
|
34
|
+
invalidTimeZone: '请输入有效的 IANA 时区,例如 Asia/Shanghai。',
|
|
35
|
+
closeReport: '收起报告', generatedAt: '生成于 {time}', elapsedSeconds: '用时 {seconds} 秒', elapsedMinutes: '用时 {minutes} 分钟', openReport: '打开报告:{title}',
|
|
36
|
+
localBadge: '本地整理', aiBadge: 'AI 报告', reportHint: '报告可继续编辑,也能复制或下载 Markdown。',
|
|
37
|
+
},
|
|
38
|
+
en: {
|
|
39
|
+
panel: 'DSH Journal', subtitle: 'Turn conversations and recorded changes into a work report.',
|
|
40
|
+
day: 'Daily', week: 'Weekly', month: 'Monthly', custom: 'Custom',
|
|
41
|
+
start: 'Start date', end: 'End date', timeZone: 'Time zone',
|
|
42
|
+
timeZoneHint: 'Dates use this time zone and include both the start and end days.',
|
|
43
|
+
scan: 'Scan records', scanning: 'Scanning…', generate: 'Generate report', generating: 'Generating…',
|
|
44
|
+
generatingHint: 'Organizing your work in this period. Longer records are summarized before the report is written.',
|
|
45
|
+
cancel: 'Cancel', cancelled: 'Request cancelled.', loading: 'Loading…', retry: 'Retry',
|
|
46
|
+
mode: 'Report format', ai: 'AI work report', local: 'Local record summary',
|
|
47
|
+
aiHint: 'Generating sends records in this range to the report model: {model}.',
|
|
48
|
+
aiUnavailable: 'The report model is unavailable. Generate a local record summary, or check DSH model settings.',
|
|
49
|
+
localHint: 'Organize records and changes by session on this computer, without a model call.',
|
|
50
|
+
sessions: 'Sessions', messages: 'Messages', tools: 'Tool calls', changes: 'File operations', failures: 'Failed calls',
|
|
51
|
+
coverage: 'Record coverage', coverageIncomplete: 'Some records could not be read, so this report may be incomplete.', sourceSessions: 'Source sessions', noSessions: 'No records were found in this date range.',
|
|
52
|
+
sourceHint: 'Includes only activity recorded within the selected dates. Titles and working directories identify the source.',
|
|
53
|
+
untitled: 'Untitled session', noWorkspace: 'No working directory recorded', sessionId: 'Session ID',
|
|
54
|
+
report: 'Work report', read: 'Read', edit: 'Edit Markdown', save: 'Save changes', saving: 'Saving…',
|
|
55
|
+
unsaved: 'Unsaved changes', saved: 'Changes saved.', markdown: 'Report Markdown',
|
|
56
|
+
copy: 'Copy', copied: 'Copied.', copyFailed: 'Clipboard access failed. Select and copy text in edit mode, or download Markdown.',
|
|
57
|
+
download: 'Download Markdown', history: 'Report history', historyEmpty: 'Generated reports will be saved here.',
|
|
58
|
+
emptyTitle: 'Choose a date range to create a work report',
|
|
59
|
+
emptyDescription: 'Scan the records to check sources, then choose an AI report or a local summary.',
|
|
60
|
+
initialError: 'Journal data could not be loaded.', requestError: 'The request did not finish. Please try again.',
|
|
61
|
+
invalidDate: 'Select valid start and end dates.', invalidOrder: 'The end date must not precede the start date.',
|
|
62
|
+
invalidTimeZone: 'Enter a valid IANA time zone, such as Asia/Singapore.',
|
|
63
|
+
closeReport: 'Close report', generatedAt: 'Generated {time}', elapsedSeconds: 'Took {seconds}s', elapsedMinutes: 'Took {minutes} min', openReport: 'Open report: {title}',
|
|
64
|
+
localBadge: 'Local summary', aiBadge: 'AI report', reportHint: 'You can edit this report, copy it, or download Markdown.',
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const css = `
|
|
69
|
+
.dsh-journal{height:100%;min-width:0;overflow:auto;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);font:inherit;font-size:14px;line-height:1.5;color-scheme:inherit}
|
|
70
|
+
.dsh-journal *{box-sizing:border-box}
|
|
71
|
+
.dsh-journal .dj-page{width:100%;max-width:1008px;margin:0 auto;padding:28px 24px 48px}
|
|
72
|
+
.dsh-journal .dj-header{padding-inline-start:max(0px,calc(var(--dsh-frame-leading-clearance,0px) - 24px));margin-bottom:24px}
|
|
73
|
+
.dsh-journal h1{font-size:20px;line-height:28px;font-weight:500;margin:0 0 5px}
|
|
74
|
+
.dsh-journal h2{font-size:15px;line-height:22px;font-weight:500;margin:0}
|
|
75
|
+
.dsh-journal p{margin:0}
|
|
76
|
+
.dsh-journal .dj-muted{color:var(--dsw-alias-label-secondary);font-size:13px}
|
|
77
|
+
.dsh-journal .dj-form{display:flex;flex-direction:column;gap:16px;padding-bottom:24px;border-bottom:1px solid var(--dsw-alias-border-l2)}
|
|
78
|
+
.dsh-journal button,.dsh-journal input,.dsh-journal select,.dsh-journal textarea{font:inherit;color:inherit}
|
|
79
|
+
.dsh-journal button,.dsh-journal select,.dsh-journal input{min-height:32px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:transparent}
|
|
80
|
+
.dsh-journal button{padding:5px 12px;cursor:pointer;white-space:nowrap;line-height:20px}
|
|
81
|
+
.dsh-journal button:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}
|
|
82
|
+
.dsh-journal button:disabled{opacity:.45;cursor:default}
|
|
83
|
+
.dsh-journal button:focus-visible,.dsh-journal input:focus-visible,.dsh-journal select:focus-visible,.dsh-journal textarea:focus-visible,.dsh-journal summary:focus-visible{outline:2px solid var(--dsw-alias-link,#4d6bfe);outline-offset:3px}
|
|
84
|
+
.dsh-journal .dj-primary{border-color:transparent;background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-inverted)}
|
|
85
|
+
.dsh-journal .dj-primary:hover:not(:disabled){background:var(--dsw-alias-button-primary-hover)}
|
|
86
|
+
.dsh-journal .dj-presets{display:flex;flex-wrap:wrap;gap:4px;align-self:flex-start;padding:3px;border-radius:10px;background:var(--dsw-alias-bg-layer-1)}
|
|
87
|
+
.dsh-journal .dj-presets button{border-color:transparent;min-width:68px}
|
|
88
|
+
.dsh-journal .dj-presets button[aria-pressed=true]{background:var(--dsw-alias-bg-base);border-color:var(--dsw-alias-border-l2);box-shadow:0 1px 2px #00000008}
|
|
89
|
+
.dsh-journal .dj-fields{display:grid;grid-template-columns:minmax(136px,1fr) minmax(136px,1fr) minmax(180px,1.3fr);gap:12px}
|
|
90
|
+
.dsh-journal label.dj-field{display:flex;flex-direction:column;gap:6px;min-width:0;font-size:13px}
|
|
91
|
+
.dsh-journal input,.dsh-journal select{width:100%;min-width:0;padding:5px 9px;background:var(--dsw-alias-bg-base)}
|
|
92
|
+
.dsh-journal select option{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary)}
|
|
93
|
+
.dsh-journal .dj-bottom-row{display:flex;gap:12px;align-items:flex-end;justify-content:space-between;flex-wrap:wrap}
|
|
94
|
+
.dsh-journal .dj-mode{width:200px}
|
|
95
|
+
.dsh-journal .dj-actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
|
|
96
|
+
.dsh-journal .dj-hint{font-size:12px;color:var(--dsw-alias-label-secondary);line-height:1.6}
|
|
97
|
+
.dsh-journal .dj-error,.dsh-journal .dj-notice{margin:16px 0;padding:10px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);font-size:13px;overflow-wrap:anywhere}
|
|
98
|
+
.dsh-journal .dj-error{color:var(--dsw-alias-state-error-primary)}
|
|
99
|
+
.dsh-journal .dj-stats{display:flex;gap:24px;flex-wrap:wrap;padding:18px 0}
|
|
100
|
+
.dsh-journal .dj-stat{display:flex;gap:6px;align-items:baseline}
|
|
101
|
+
.dsh-journal .dj-number{font-size:20px;font-weight:500;font-variant-numeric:tabular-nums}
|
|
102
|
+
.dsh-journal .dj-stat-label{font-size:12px;color:var(--dsw-alias-label-secondary)}
|
|
103
|
+
.dsh-journal .dj-warnings{padding:10px 12px;border-radius:8px;background:var(--dsw-alias-bg-layer-1);font-size:12px;color:var(--dsw-alias-label-secondary);margin-bottom:14px}
|
|
104
|
+
.dsh-journal .dj-warnings summary{padding:0;color:inherit}
|
|
105
|
+
.dsh-journal .dj-warnings ul{padding-left:18px;margin:5px 0 0}
|
|
106
|
+
.dsh-journal .dj-coverage-error{margin:0 0 8px;color:var(--dsw-alias-state-error-primary);font-size:13px}
|
|
107
|
+
.dsh-journal .dj-sources{margin:2px 0 20px;font-size:13px}
|
|
108
|
+
.dsh-journal summary{cursor:pointer;color:var(--dsw-alias-label-secondary);padding:5px 0;width:fit-content}
|
|
109
|
+
.dsh-journal .dj-source-list{list-style:none;padding:0;margin:8px 0 0;border-top:1px solid var(--dsw-alias-border-l2)}
|
|
110
|
+
.dsh-journal .dj-source{padding:10px 0;border-bottom:1px solid var(--dsw-alias-border-l2);display:flex;flex-direction:column;gap:3px}
|
|
111
|
+
.dsh-journal .dj-source-title{font-weight:500;overflow-wrap:anywhere}
|
|
112
|
+
.dsh-journal .dj-path{font-size:12px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
113
|
+
.dsh-journal .dj-source-meta{font-size:12px;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere}
|
|
114
|
+
.dsh-journal .dj-report{margin-top:24px}
|
|
115
|
+
.dsh-journal .dj-report-header{display:flex;flex-wrap:wrap;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:12px}
|
|
116
|
+
.dsh-journal .dj-report-name{font-size:17px;font-weight:500;line-height:1.5;overflow-wrap:anywhere;margin:0 0 3px}
|
|
117
|
+
.dsh-journal .dj-report-meta{display:flex;align-items:center;gap:8px;flex-wrap:wrap;color:var(--dsw-alias-label-secondary);font-size:12px}
|
|
118
|
+
.dsh-journal .dj-badge{padding:1px 6px;border-radius:5px;background:var(--dsw-alias-bg-layer-1)}
|
|
119
|
+
.dsh-journal .dj-tabs{display:flex;gap:4px;padding-bottom:10px;border-bottom:1px solid var(--dsw-alias-border-l2);margin-top:16px}
|
|
120
|
+
.dsh-journal .dj-tabs button{border-color:transparent;color:var(--dsw-alias-label-secondary)}
|
|
121
|
+
.dsh-journal .dj-tabs button[aria-pressed=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
|
|
122
|
+
.dsh-journal .dj-edit-toolbar{display:flex;gap:12px;align-items:center;justify-content:flex-end;margin:12px 0}
|
|
123
|
+
.dsh-journal .dj-editor{display:block;width:100%;min-height:460px;resize:vertical;padding:16px;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;background:var(--dsw-alias-bg-base);font:13px/1.7 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
124
|
+
.dsh-journal .dj-markdown{padding:18px 0 12px;overflow-wrap:anywhere;line-height:1.8}
|
|
125
|
+
.dsh-journal .dj-markdown h1,.dsh-journal .dj-markdown h2,.dsh-journal .dj-markdown h3,.dsh-journal .dj-markdown h4,.dsh-journal .dj-markdown h5,.dsh-journal .dj-markdown h6{margin:22px 0 9px;font-weight:500;line-height:1.5}
|
|
126
|
+
.dsh-journal .dj-markdown h1{font-size:22px}.dsh-journal .dj-markdown h2{font-size:18px}.dsh-journal .dj-markdown h3{font-size:16px}
|
|
127
|
+
.dsh-journal .dj-markdown>:first-child{margin-top:0}
|
|
128
|
+
.dsh-journal .dj-markdown p{margin:9px 0;white-space:pre-wrap}
|
|
129
|
+
.dsh-journal .dj-markdown ul,.dsh-journal .dj-markdown ol{padding-left:22px;margin:9px 0}
|
|
130
|
+
.dsh-journal .dj-markdown li{margin:3px 0;white-space:pre-wrap}
|
|
131
|
+
.dsh-journal .dj-markdown blockquote{margin:12px 0;padding:4px 14px;border-left:3px solid var(--dsw-alias-border-l3);color:var(--dsw-alias-label-secondary)}
|
|
132
|
+
.dsh-journal .dj-markdown code{padding:2px 5px;border-radius:4px;background:var(--dsw-alias-markdown-inline-code);font:12px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
|
|
133
|
+
.dsh-journal .dj-markdown pre{padding:14px;border-radius:8px;background:var(--dsw-alias-markdown-code-block);overflow:auto}
|
|
134
|
+
.dsh-journal .dj-markdown pre code{padding:0;background:transparent;white-space:pre;overflow-wrap:normal}
|
|
135
|
+
.dsh-journal .dj-markdown a{color:var(--dsw-alias-link);text-decoration:underline;text-underline-offset:3px}
|
|
136
|
+
.dsh-journal .dj-markdown hr{border:0;border-top:1px solid var(--dsw-alias-border-l2);margin:20px 0}
|
|
137
|
+
.dsh-journal .dj-table-wrap{overflow:auto}.dsh-journal .dj-markdown table{border-collapse:collapse;width:100%;font-size:13px;margin:10px 0}
|
|
138
|
+
.dsh-journal .dj-markdown th,.dsh-journal .dj-markdown td{text-align:left;border:1px solid var(--dsw-alias-border-l2);padding:7px 10px;min-width:80px}
|
|
139
|
+
.dsh-journal .dj-markdown th{background:var(--dsw-alias-bg-layer-1);font-weight:500}
|
|
140
|
+
.dsh-journal .dj-empty{padding:44px 8px;text-align:center;color:var(--dsw-alias-label-secondary)}
|
|
141
|
+
.dsh-journal .dj-empty-title{font-size:15px;font-weight:500;color:var(--dsw-alias-label-primary);margin:0 0 8px}
|
|
142
|
+
.dsh-journal .dj-history{margin-top:28px;padding-top:20px;border-top:1px solid var(--dsw-alias-border-l2)}
|
|
143
|
+
.dsh-journal .dj-history-list{list-style:none;padding:0;margin:10px 0 0}
|
|
144
|
+
.dsh-journal .dj-history-list li{border-bottom:1px solid var(--dsw-alias-border-l2)}
|
|
145
|
+
.dsh-journal .dj-history-entry{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;border:0;border-radius:6px;padding:10px 8px}
|
|
146
|
+
.dsh-journal .dj-history-entry[aria-current=true]{background:var(--dsw-alias-interactive-bg-hover)}
|
|
147
|
+
.dsh-journal .dj-history-title{display:block;white-space:normal;font-weight:500;overflow-wrap:anywhere}
|
|
148
|
+
.dsh-journal .dj-history-date{display:block;margin-top:3px;font-size:12px;color:var(--dsw-alias-label-secondary)}
|
|
149
|
+
@media(max-width:620px){.dsh-journal .dj-page{padding:24px 16px 36px}.dsh-journal .dj-fields{grid-template-columns:1fr 1fr}.dsh-journal .dj-zone{grid-column:1/-1}.dsh-journal .dj-stats{gap:14px}.dsh-journal .dj-history-entry{align-items:flex-start}.dsh-journal .dj-badge{white-space:nowrap}.dsh-journal .dj-report-header .dj-actions{width:100%}.dsh-journal .dj-header{padding-inline-start:max(0px,calc(var(--dsh-frame-leading-clearance,0px) - 16px))}}
|
|
150
|
+
`;
|
|
151
|
+
|
|
152
|
+
function dateInZone(zone) {
|
|
153
|
+
return new Intl.DateTimeFormat('en-CA', {
|
|
154
|
+
timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit',
|
|
155
|
+
}).format(new Date());
|
|
156
|
+
}
|
|
157
|
+
function presetDates(preset, zone) {
|
|
158
|
+
let end;
|
|
159
|
+
try { end = dateInZone(zone); } catch { end = dateInZone('UTC'); }
|
|
160
|
+
let start = end;
|
|
161
|
+
if (preset === 'week') {
|
|
162
|
+
const date = new Date(`${end}T12:00:00Z`);
|
|
163
|
+
date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 6) % 7);
|
|
164
|
+
start = date.toISOString().slice(0, 10);
|
|
165
|
+
} else if (preset === 'month') start = `${end.slice(0, 7)}-01`;
|
|
166
|
+
return { start, end };
|
|
167
|
+
}
|
|
168
|
+
function validDate(value) {
|
|
169
|
+
return /^\d{4}-\d{2}-\d{2}$/.test(value)
|
|
170
|
+
&& !Number.isNaN(Date.parse(`${value}T00:00:00Z`))
|
|
171
|
+
&& new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value;
|
|
172
|
+
}
|
|
173
|
+
function rangeError(form, t) {
|
|
174
|
+
if (!validDate(form.start) || !validDate(form.end)) return t('invalidDate');
|
|
175
|
+
if (form.end < form.start) return t('invalidOrder');
|
|
176
|
+
try { new Intl.DateTimeFormat('en', { timeZone: form.timeZone }).format(); }
|
|
177
|
+
catch { return t('invalidTimeZone'); }
|
|
178
|
+
return '';
|
|
179
|
+
}
|
|
180
|
+
function showTime(value, zone) {
|
|
181
|
+
if (!value) return '';
|
|
182
|
+
const date = new Date(value);
|
|
183
|
+
if (Number.isNaN(date.getTime())) return String(value);
|
|
184
|
+
try { return date.toLocaleString(undefined, { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); }
|
|
185
|
+
catch { return date.toLocaleString(); }
|
|
186
|
+
}
|
|
187
|
+
function warningText(warning) {
|
|
188
|
+
if (typeof warning === 'string') return warning;
|
|
189
|
+
return warning?.message || warning?.description || String(warning?.code || '');
|
|
190
|
+
}
|
|
191
|
+
function inline(text, prefix = '') {
|
|
192
|
+
const parts = String(text).split(/(`[^`\n]+`|\*\*[^*\n]+\*\*|\[[^\]\n]+\]\(https?:\/\/[^\s)]+\))/g);
|
|
193
|
+
return parts.filter(Boolean).map((part, i) => {
|
|
194
|
+
const key = `${prefix}${i}`;
|
|
195
|
+
if (part.startsWith('`') && part.endsWith('`')) return h('code', { key }, part.slice(1, -1));
|
|
196
|
+
if (part.startsWith('**') && part.endsWith('**')) return h('strong', { key }, part.slice(2, -2));
|
|
197
|
+
const match = /^\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)$/.exec(part);
|
|
198
|
+
if (match) return h('a', { key, href: match[2], target: '_blank', rel: 'noopener noreferrer' }, match[1]);
|
|
199
|
+
return part;
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
function Markdown({ text, title }) {
|
|
203
|
+
const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
|
|
204
|
+
const nodes = [];
|
|
205
|
+
let i = 0;
|
|
206
|
+
const isSpecial = line => /^\s*$|^\s*```|^#{1,6}\s|^\s*[-*+]\s|^\s*\d+[.)]\s|^>\s?|^\s*([-*_])(?:\s*\1){2,}\s*$/.test(line);
|
|
207
|
+
const cells = line => line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(cell => cell.trim());
|
|
208
|
+
while (i < lines.length) {
|
|
209
|
+
const line = lines[i];
|
|
210
|
+
const key = i;
|
|
211
|
+
if (!line.trim()) { i++; continue; }
|
|
212
|
+
if (/^\s*```/.test(line)) {
|
|
213
|
+
const code = [];
|
|
214
|
+
i++;
|
|
215
|
+
while (i < lines.length && !/^\s*```/.test(lines[i])) code.push(lines[i++]);
|
|
216
|
+
if (i < lines.length) i++;
|
|
217
|
+
nodes.push(h('pre', { key }, h('code', null, code.join('\n'))));
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
const heading = /^(#{1,6})\s+(.+)$/.exec(line);
|
|
221
|
+
if (heading) {
|
|
222
|
+
if (!(i === 0 && heading[1] === '#' && heading[2] === title)) nodes.push(h(`h${heading[1].length}`, { key }, inline(heading[2])));
|
|
223
|
+
i++; continue;
|
|
224
|
+
}
|
|
225
|
+
if (/^\s*([-*_])(?:\s*\1){2,}\s*$/.test(line)) { nodes.push(h('hr', { key })); i++; continue; }
|
|
226
|
+
if (line.includes('|') && i + 1 < lines.length && /^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(lines[i + 1])) {
|
|
227
|
+
const headings = cells(line);
|
|
228
|
+
const rows = [];
|
|
229
|
+
i += 2;
|
|
230
|
+
while (i < lines.length && lines[i].trim() && lines[i].includes('|')) rows.push(cells(lines[i++]));
|
|
231
|
+
nodes.push(h('div', { key, className: 'dj-table-wrap' }, h('table', null,
|
|
232
|
+
h('thead', null, h('tr', null, ...headings.map((cell, j) => h('th', { key: j }, inline(cell))))),
|
|
233
|
+
h('tbody', null, ...rows.map((row, j) => h('tr', { key: j }, ...headings.map((_, col) => h('td', { key: col }, inline(row[col] || '')))))))));
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
const list = /^\s*(?:([-*+])|(\d+)[.)])\s+(.+)$/.exec(line);
|
|
237
|
+
if (list) {
|
|
238
|
+
const ordered = !!list[2];
|
|
239
|
+
const items = [];
|
|
240
|
+
const start = ordered ? Number(list[2]) : undefined;
|
|
241
|
+
while (i < lines.length) {
|
|
242
|
+
const item = /^\s*(?:([-*+])|(\d+)[.)])\s+(.+)$/.exec(lines[i]);
|
|
243
|
+
if (!item || !!item[2] !== ordered) break;
|
|
244
|
+
items.push(h('li', { key: i }, inline(item[3])));
|
|
245
|
+
i++;
|
|
246
|
+
}
|
|
247
|
+
nodes.push(h(ordered ? 'ol' : 'ul', { key, ...(ordered ? { start } : {}) }, ...items));
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
if (/^>\s?/.test(line)) {
|
|
251
|
+
const quote = [];
|
|
252
|
+
while (i < lines.length && /^>\s?/.test(lines[i])) quote.push(lines[i++].replace(/^>\s?/, ''));
|
|
253
|
+
nodes.push(h('blockquote', { key }, h('p', null, inline(quote.join('\n')))));
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
const paragraph = [line];
|
|
257
|
+
i++;
|
|
258
|
+
while (i < lines.length && !isSpecial(lines[i]) && !(lines[i].includes('|') && i + 1 < lines.length && /\|?\s*:?-{3,}/.test(lines[i + 1]))) paragraph.push(lines[i++]);
|
|
259
|
+
nodes.push(h('p', { key }, inline(paragraph.join('\n'))));
|
|
260
|
+
}
|
|
261
|
+
return h('div', { className: 'dj-markdown' }, ...nodes);
|
|
262
|
+
}
|
|
263
|
+
function Warnings({ warnings = [], t }) {
|
|
264
|
+
const items = warnings.map(warningText).filter(Boolean);
|
|
265
|
+
const incomplete = warnings.some(warning => {
|
|
266
|
+
const code = typeof warning === 'object' && warning ? String(warning.code || '') : '';
|
|
267
|
+
return /READ_(?:FAILED|ERROR)|INVALID_EVENTS|MISSING_SESSION_ID/i.test(code)
|
|
268
|
+
|| /读取失败|无法读取|报告覆盖不完整|事件格式无效|could not be read|failed to read|read(?:ing)? failed|coverage.{0,20}incomplete/i.test(warningText(warning));
|
|
269
|
+
});
|
|
270
|
+
return items.length ? h('div', null,
|
|
271
|
+
incomplete ? h('p', { className: 'dj-coverage-error', role: 'alert' }, t('coverageIncomplete')) : null,
|
|
272
|
+
h('details', { className: 'dj-warnings' }, h('summary', null, t('coverage')),
|
|
273
|
+
h('ul', null, ...items.map((item, index) => h('li', { key: index }, item))))) : null;
|
|
274
|
+
}
|
|
275
|
+
function elapsedTime(milliseconds, t) {
|
|
276
|
+
if (typeof milliseconds !== 'number' || !Number.isFinite(milliseconds) || milliseconds < 0) return null;
|
|
277
|
+
return milliseconds < 60000
|
|
278
|
+
? t('elapsedSeconds', { seconds: Math.round(milliseconds / 1000) })
|
|
279
|
+
: t('elapsedMinutes', { minutes: Math.round(milliseconds / 6000) / 10 });
|
|
280
|
+
}
|
|
281
|
+
function Stats({ stats = {}, t }) {
|
|
282
|
+
return h('div', { className: 'dj-stats', 'aria-label': t('report') },
|
|
283
|
+
...[['sessionCount', 'sessions'], ['messageCount', 'messages'], ['toolCount', 'tools'], ['changeCount', 'changes'], ['failedToolCount', 'failures']].map(([key, label]) =>
|
|
284
|
+
h('div', { className: 'dj-stat', key }, h('span', { className: 'dj-number' }, stats[key] ?? 0), h('span', { className: 'dj-stat-label' }, t(label)))));
|
|
285
|
+
}
|
|
286
|
+
function Sources({ sessions = [], t, zone }) {
|
|
287
|
+
if (!sessions.length) return null;
|
|
288
|
+
return h('details', { className: 'dj-sources' },
|
|
289
|
+
h('summary', null, `${t('sourceSessions')} · ${sessions.length}`),
|
|
290
|
+
h('p', { className: 'dj-hint' }, t('sourceHint')),
|
|
291
|
+
h('ul', { className: 'dj-source-list' }, ...sessions.map(session => h('li', { className: 'dj-source', key: session.id },
|
|
292
|
+
h('span', { className: 'dj-source-title' }, session.title || t('untitled')),
|
|
293
|
+
h('span', { className: 'dj-path' }, session.cwd || t('noWorkspace')),
|
|
294
|
+
h('span', { className: 'dj-source-meta' }, `${session.messageCount ?? 0} ${t('messages')} · ${session.changeCount ?? 0} ${t('changes')}${session.startTime ? ` · ${showTime(session.startTime, zone)}` : ''}`),
|
|
295
|
+
h('span', { className: 'dj-source-meta' }, `${t('sessionId')}: ${session.id}`)))));
|
|
296
|
+
}
|
|
297
|
+
function JournalIcon({ size = 18 }) {
|
|
298
|
+
return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
|
|
299
|
+
h('rect', { x: 4, y: 3, width: 16, height: 18, rx: 2.5 }),
|
|
300
|
+
h('path', { d: 'M8 3v18M11 8h5M11 12h5M11 16h3' }));
|
|
301
|
+
}
|
|
302
|
+
async function api(path, options = {}, signal) {
|
|
303
|
+
const transport = window.__DSH_TRANSPORT__;
|
|
304
|
+
const send = transport?.fetch ? transport.fetch.bind(transport) : window.fetch.bind(window);
|
|
305
|
+
const response = await send(`api/dsh-journal${path}`, {
|
|
306
|
+
...options, ...(signal ? { signal } : {}),
|
|
307
|
+
headers: { 'content-type': 'application/json', ...options.headers },
|
|
308
|
+
});
|
|
309
|
+
let body;
|
|
310
|
+
try { body = await response.json(); } catch { throw new Error(`HTTP ${response.status}`); }
|
|
311
|
+
if (!response.ok) throw new Error(typeof body?.error === 'string' ? body.error : body?.error?.message || body?.message || `HTTP ${response.status}`);
|
|
312
|
+
return body;
|
|
313
|
+
}
|
|
314
|
+
function JournalPage({ t }) {
|
|
315
|
+
const initialZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
|
|
316
|
+
const [form, setForm] = useState(() => ({ ...presetDates('day', initialZone), timeZone: initialZone, preset: 'day' }));
|
|
317
|
+
const [model, setModel] = useState({ available: false });
|
|
318
|
+
const [mode, setMode] = useState('ai');
|
|
319
|
+
const [history, setHistory] = useState([]);
|
|
320
|
+
const [initialLoading, setInitialLoading] = useState(true);
|
|
321
|
+
const [initialError, setInitialError] = useState('');
|
|
322
|
+
const [preview, setPreview] = useState(null);
|
|
323
|
+
const [report, setReport] = useState(null);
|
|
324
|
+
const [editing, setEditing] = useState(false);
|
|
325
|
+
const [drafts, setDrafts] = useState({});
|
|
326
|
+
const [busy, setBusy] = useState('');
|
|
327
|
+
const [error, setError] = useState('');
|
|
328
|
+
const [notice, setNotice] = useState('');
|
|
329
|
+
const requests = useRef(new Set());
|
|
330
|
+
const currentRequest = useRef(null);
|
|
331
|
+
const mounted = useRef(false);
|
|
332
|
+
const draft = report ? drafts[report.id] ?? report.markdown : '';
|
|
333
|
+
const dirty = !!report && draft !== report.markdown;
|
|
334
|
+
const validation = rangeError(form, t);
|
|
335
|
+
const activeEvidence = report || preview;
|
|
336
|
+
const blocked = !!busy || initialLoading;
|
|
337
|
+
const begin = () => { const controller = new AbortController(); requests.current.add(controller); return controller; };
|
|
338
|
+
const end = controller => { requests.current.delete(controller); if (currentRequest.current === controller) currentRequest.current = null; };
|
|
339
|
+
async function loadState() {
|
|
340
|
+
const controller = begin();
|
|
341
|
+
setInitialLoading(true); setInitialError('');
|
|
342
|
+
try {
|
|
343
|
+
const state = await api('/state', {}, controller.signal);
|
|
344
|
+
if (!mounted.current) return;
|
|
345
|
+
setHistory(state.reports || []);
|
|
346
|
+
setModel(state.model || { available: false });
|
|
347
|
+
setMode(previous => state.model?.available ? previous : 'local');
|
|
348
|
+
} catch (failure) {
|
|
349
|
+
if (mounted.current && !controller.signal.aborted) {
|
|
350
|
+
setInitialError(failure.message || t('initialError'));
|
|
351
|
+
setModel({ available: false });
|
|
352
|
+
setMode('local');
|
|
353
|
+
}
|
|
354
|
+
} finally {
|
|
355
|
+
end(controller);
|
|
356
|
+
if (mounted.current) setInitialLoading(false);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
useEffect(() => {
|
|
360
|
+
mounted.current = true;
|
|
361
|
+
void loadState();
|
|
362
|
+
return () => {
|
|
363
|
+
mounted.current = false;
|
|
364
|
+
for (const controller of requests.current) controller.abort();
|
|
365
|
+
requests.current.clear();
|
|
366
|
+
};
|
|
367
|
+
}, []);
|
|
368
|
+
function changeForm(patch) {
|
|
369
|
+
setForm(previous => ({ ...previous, ...patch }));
|
|
370
|
+
setPreview(null); setError(''); setNotice('');
|
|
371
|
+
}
|
|
372
|
+
function selectPreset(preset) {
|
|
373
|
+
changeForm({ preset, ...(preset === 'custom' ? {} : presetDates(preset, form.timeZone)) });
|
|
374
|
+
}
|
|
375
|
+
function changeZone(timeZone) {
|
|
376
|
+
let dates = {};
|
|
377
|
+
if (form.preset !== 'custom') {
|
|
378
|
+
try {
|
|
379
|
+
new Intl.DateTimeFormat('en', { timeZone }).format();
|
|
380
|
+
dates = presetDates(form.preset, timeZone);
|
|
381
|
+
} catch { /* Keep the date fields while a time zone is being typed. */ }
|
|
382
|
+
}
|
|
383
|
+
changeForm({ timeZone, ...dates });
|
|
384
|
+
}
|
|
385
|
+
async function run(kind, action) {
|
|
386
|
+
if (currentRequest.current) return;
|
|
387
|
+
const controller = begin();
|
|
388
|
+
currentRequest.current = controller;
|
|
389
|
+
setBusy(kind); setError(''); setNotice('');
|
|
390
|
+
try { await action(controller.signal); }
|
|
391
|
+
catch (failure) {
|
|
392
|
+
if (mounted.current) {
|
|
393
|
+
if (controller.signal.aborted) setNotice(t('cancelled'));
|
|
394
|
+
else setError(failure.message || t('requestError'));
|
|
395
|
+
}
|
|
396
|
+
} finally {
|
|
397
|
+
end(controller);
|
|
398
|
+
if (mounted.current) setBusy('');
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
function scan() {
|
|
402
|
+
if (validation) { setError(validation); return; }
|
|
403
|
+
void run('scan', async signal => {
|
|
404
|
+
const result = await api('/preview', { method: 'POST', body: JSON.stringify(form) }, signal);
|
|
405
|
+
if (!mounted.current) return;
|
|
406
|
+
setPreview(result); setReport(null); setEditing(false);
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
function generate() {
|
|
410
|
+
if (validation) { setError(validation); return; }
|
|
411
|
+
void run('generate', async signal => {
|
|
412
|
+
const result = await api('/generate', { method: 'POST', body: JSON.stringify({ ...form, mode }) }, signal);
|
|
413
|
+
if (!mounted.current) return;
|
|
414
|
+
setReport(result); setEditing(false);
|
|
415
|
+
setHistory(previous => [result, ...previous.filter(item => item.id !== result.id)]);
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
function openReport(id) {
|
|
419
|
+
void run('open', async signal => {
|
|
420
|
+
const result = await api(`/report?id=${encodeURIComponent(id)}`, {}, signal);
|
|
421
|
+
if (!mounted.current) return;
|
|
422
|
+
setReport(result); setEditing(false);
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
function save() {
|
|
426
|
+
if (!report || !dirty) return;
|
|
427
|
+
void run('save', async signal => {
|
|
428
|
+
const result = await api('/report', { method: 'PUT', body: JSON.stringify({ id: report.id, markdown: draft }) }, signal);
|
|
429
|
+
if (!mounted.current) return;
|
|
430
|
+
setReport(result);
|
|
431
|
+
setDrafts(previous => { const next = { ...previous }; delete next[result.id]; return next; });
|
|
432
|
+
setHistory(previous => previous.map(item => item.id === result.id ? result : item));
|
|
433
|
+
setNotice(t('saved'));
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
async function copy() {
|
|
437
|
+
try {
|
|
438
|
+
await navigator.clipboard.writeText(draft);
|
|
439
|
+
if (mounted.current) { setNotice(t('copied')); setError(''); }
|
|
440
|
+
} catch { if (mounted.current) setError(t('copyFailed')); }
|
|
441
|
+
}
|
|
442
|
+
function download() {
|
|
443
|
+
if (!report) return;
|
|
444
|
+
const url = URL.createObjectURL(new Blob([draft], { type: 'text/markdown;charset=utf-8' }));
|
|
445
|
+
const anchor = document.createElement('a');
|
|
446
|
+
anchor.href = url;
|
|
447
|
+
anchor.download = `${String(report.title || 'DSH Journal').replace(/[\\/:*?"<>|\u0000-\u001f]/g, '-').slice(0, 120)}.md`;
|
|
448
|
+
anchor.click();
|
|
449
|
+
URL.revokeObjectURL(url);
|
|
450
|
+
}
|
|
451
|
+
const field = (key, label) => h('label', { className: 'dj-field', key },
|
|
452
|
+
h('span', null, t(label)),
|
|
453
|
+
h('input', { type: 'date', value: form[key], disabled: blocked, required: true,
|
|
454
|
+
...(key === 'end' ? { min: form.start } : { max: form.end }),
|
|
455
|
+
onChange: event => changeForm({ [key]: event.target.value, preset: 'custom' }) }));
|
|
456
|
+
return h('section', { className: 'dsh-journal', 'aria-label': t('panel') },
|
|
457
|
+
h('style', null, css),
|
|
458
|
+
h('div', { className: 'dj-page' },
|
|
459
|
+
h('header', { className: 'dj-header' }, h('h1', null, t('panel')), h('p', { className: 'dj-muted' }, t('subtitle'))),
|
|
460
|
+
h('form', { className: 'dj-form', onSubmit: event => { event.preventDefault(); generate(); } },
|
|
461
|
+
h('div', { className: 'dj-presets', role: 'group', 'aria-label': t('custom') },
|
|
462
|
+
...['day', 'week', 'month', 'custom'].map(preset => h('button', { key: preset, type: 'button', disabled: blocked, 'aria-pressed': form.preset === preset, onClick: () => selectPreset(preset) }, t(preset)))),
|
|
463
|
+
h('div', { className: 'dj-fields' }, field('start', 'start'), field('end', 'end'),
|
|
464
|
+
h('label', { className: 'dj-field dj-zone' }, h('span', null, t('timeZone')),
|
|
465
|
+
h('input', { type: 'text', value: form.timeZone, list: 'dsh-journal-timezones', disabled: blocked, required: true, spellCheck: false, 'aria-describedby': 'dsh-journal-zone-hint',
|
|
466
|
+
onChange: event => changeZone(event.target.value) }),
|
|
467
|
+
h('datalist', { id: 'dsh-journal-timezones' }, ...[...new Set([initialZone, 'Asia/Shanghai', 'Asia/Singapore', 'Asia/Tokyo', 'UTC', 'Europe/London', 'America/New_York', 'America/Los_Angeles'])].map(zone => h('option', { value: zone, key: zone }))))),
|
|
468
|
+
h('p', { className: 'dj-hint', id: 'dsh-journal-zone-hint' }, t('timeZoneHint')),
|
|
469
|
+
h('div', { className: 'dj-bottom-row' },
|
|
470
|
+
h('label', { className: 'dj-field dj-mode' }, h('span', null, t('mode')),
|
|
471
|
+
h('select', { value: mode, disabled: blocked, onChange: event => setMode(event.target.value) },
|
|
472
|
+
h('option', { value: 'ai', disabled: !model.available }, t('ai')), h('option', { value: 'local' }, t('local')))),
|
|
473
|
+
h('div', { className: 'dj-actions' },
|
|
474
|
+
busy ? h('button', { type: 'button', onClick: () => currentRequest.current?.abort() }, t('cancel')) : null,
|
|
475
|
+
h('button', { type: 'button', onClick: scan, disabled: blocked || !!validation }, busy === 'scan' ? t('scanning') : t('scan')),
|
|
476
|
+
h('button', { type: 'submit', className: 'dj-primary', disabled: blocked || !!validation || (mode === 'ai' && !model.available) }, busy === 'generate' ? t('generating') : t('generate')))),
|
|
477
|
+
h('p', { className: 'dj-hint' }, mode === 'local' ? t('localHint') : model.available ? t('aiHint', { model: [model.provider, model.model].filter(Boolean).join(' / ') }) : t('aiUnavailable')),
|
|
478
|
+
!model.available && mode === 'local' && !initialLoading ? h('p', { className: 'dj-hint' }, t('aiUnavailable')) : null,
|
|
479
|
+
validation ? h('p', { className: 'dj-hint' }, validation) : null),
|
|
480
|
+
initialLoading ? h('p', { className: 'dj-notice', role: 'status' }, t('loading')) : null,
|
|
481
|
+
initialError ? h('div', { className: 'dj-error', role: 'alert' }, initialError, ' ', h('button', { type: 'button', onClick: () => void loadState(), disabled: initialLoading }, t('retry'))) : null,
|
|
482
|
+
error ? h('div', { className: 'dj-error', role: 'alert' }, error) : null,
|
|
483
|
+
notice ? h('div', { className: 'dj-notice', role: 'status', 'aria-live': 'polite' }, notice) : null,
|
|
484
|
+
busy === 'generate' ? h('p', { className: 'dj-notice', role: 'status' }, t('generatingHint')) : busy === 'scan' ? h('p', { className: 'dj-notice', role: 'status' }, t('scanning')) : null,
|
|
485
|
+
busy === 'open' ? h('p', { className: 'dj-notice', role: 'status' }, t('loading')) : null,
|
|
486
|
+
activeEvidence ? h(React.Fragment, null,
|
|
487
|
+
h(Stats, { stats: activeEvidence.stats, t }),
|
|
488
|
+
h(Warnings, { warnings: activeEvidence.warnings, t }),
|
|
489
|
+
h(Sources, { sessions: activeEvidence.sources || activeEvidence.sessions, t, zone: activeEvidence.range?.timeZone || form.timeZone }),
|
|
490
|
+
!report && activeEvidence.stats?.sessionCount === 0 ? h('p', { className: 'dj-muted' }, t('noSessions')) : null) : null,
|
|
491
|
+
report ? h('article', { className: 'dj-report', 'aria-label': report.title || t('report'), 'aria-busy': busy === 'save' },
|
|
492
|
+
h('div', { className: 'dj-report-header' },
|
|
493
|
+
h('div', null, h('h2', { className: 'dj-report-name' }, report.title || t('report')),
|
|
494
|
+
h('div', { className: 'dj-report-meta' }, h('span', { className: 'dj-badge' }, t(report.mode === 'local' ? 'localBadge' : 'aiBadge')),
|
|
495
|
+
h('span', null, t('generatedAt', { time: showTime(report.createdAt, report.range?.timeZone || form.timeZone) })),
|
|
496
|
+
elapsedTime(report.generation?.elapsedMs, t) ? h('span', null, elapsedTime(report.generation.elapsedMs, t)) : null),
|
|
497
|
+
report.range?.start ? h('p', { className: 'dj-hint', style: { marginTop: 5 } }, `${report.range.start}${report.range.start === report.range.end ? '' : ` — ${report.range.end}`} · ${report.range.timeZone || form.timeZone}`) : null),
|
|
498
|
+
h('div', { className: 'dj-actions' },
|
|
499
|
+
h('button', { type: 'button', onClick: () => void copy() }, t('copy')),
|
|
500
|
+
h('button', { type: 'button', onClick: download }, t('download')),
|
|
501
|
+
h('button', { type: 'button', disabled: blocked, onClick: () => { setReport(null); setEditing(false); } }, t('closeReport')))),
|
|
502
|
+
h('p', { className: 'dj-hint' }, t('reportHint')),
|
|
503
|
+
h('div', { className: 'dj-tabs', role: 'group', 'aria-label': t('report') },
|
|
504
|
+
h('button', { type: 'button', 'aria-pressed': !editing, onClick: () => setEditing(false) }, t('read')),
|
|
505
|
+
h('button', { type: 'button', 'aria-pressed': editing, onClick: () => setEditing(true) }, t('edit'))),
|
|
506
|
+
editing ? h(React.Fragment, null,
|
|
507
|
+
h('div', { className: 'dj-edit-toolbar' }, dirty ? h('span', { className: 'dj-hint' }, t('unsaved')) : null,
|
|
508
|
+
h('button', { type: 'button', className: 'dj-primary', disabled: blocked || !dirty, onClick: save }, busy === 'save' ? t('saving') : t('save'))),
|
|
509
|
+
h('textarea', { className: 'dj-editor', 'aria-label': t('markdown'), value: draft, disabled: busy === 'save', spellCheck: false,
|
|
510
|
+
onChange: event => setDrafts(previous => ({ ...previous, [report.id]: event.target.value })) })) : h(Markdown, { text: draft, title: report.title })) : !activeEvidence && !initialLoading ?
|
|
511
|
+
h('div', { className: 'dj-empty' }, h('p', { className: 'dj-empty-title' }, t('emptyTitle')), h('p', { className: 'dj-muted' }, t('emptyDescription'))) : null,
|
|
512
|
+
h('section', { className: 'dj-history', 'aria-label': t('history') }, h('h2', null, t('history')),
|
|
513
|
+
history.length ? h('ul', { className: 'dj-history-list' }, ...history.map(item => h('li', { key: item.id },
|
|
514
|
+
h('button', { type: 'button', className: 'dj-history-entry', disabled: blocked, 'aria-current': report?.id === item.id, 'aria-label': t('openReport', { title: item.title || t('report') }), onClick: () => openReport(item.id) },
|
|
515
|
+
h('span', null, h('span', { className: 'dj-history-title' }, item.title || t('report')), h('span', { className: 'dj-history-date' }, showTime(item.createdAt, item.range?.timeZone || form.timeZone))),
|
|
516
|
+
h('span', { className: 'dj-badge' }, t(item.mode === 'local' ? 'localBadge' : 'aiBadge')))))) : h('p', { className: 'dj-muted', style: { marginTop: 10 } }, t('historyEmpty')))));
|
|
517
|
+
}
|
|
518
|
+
return {
|
|
519
|
+
inject: ['slots', 'locale', 'connection'],
|
|
520
|
+
apply(ctx) {
|
|
521
|
+
ctx.effect(() => ctx.locale.register(NS, dictionaries), 'dsh-journal: locale');
|
|
522
|
+
const t = ctx.locale.bind(NS);
|
|
523
|
+
ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID, locale: NS }, JournalPage));
|
|
524
|
+
ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 10, label: () => t('panel'), locale: NS }, JournalIcon));
|
|
525
|
+
},
|
|
526
|
+
};
|
|
527
|
+
},
|
|
528
|
+
});
|
package/cordis.patch.yml
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128" fill="none">
|
|
2
|
+
<rect x="12" y="8" width="104" height="112" rx="24" fill="#EAF0FF"/>
|
|
3
|
+
<path d="M40 29h48a8 8 0 0 1 8 8v58a8 8 0 0 1-8 8H40a8 8 0 0 1-8-8V37a8 8 0 0 1 8-8Z" stroke="#4269D0" stroke-width="5"/>
|
|
4
|
+
<path d="M46 29v74M59 49h23M59 64h23M59 79h15" stroke="#4269D0" stroke-width="5" stroke-linecap="round"/>
|
|
5
|
+
<path d="m76 91 6 6 13-15" stroke="#4269D0" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
6
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { collectActivity } from './lib/collector.js';
|
|
3
|
+
import { normalizeRange } from './lib/range.js';
|
|
4
|
+
import { createReport, modelState } from './lib/report.js';
|
|
5
|
+
import { ReportStore } from './lib/report-store.js';
|
|
6
|
+
import { loadReportModel } from './lib/preferences.js';
|
|
7
|
+
import { prepareReportStorage, resolveReportRoot } from './lib/storage-location.js';
|
|
8
|
+
|
|
9
|
+
export const inject = ['connection', 'sessionQuery'];
|
|
10
|
+
|
|
11
|
+
const LEGACY_DATA = fileURLToPath(new URL('./data/reports/', import.meta.url));
|
|
12
|
+
|
|
13
|
+
function json(value, status = 200) {
|
|
14
|
+
return Response.json(value, { status, headers: { 'cache-control': 'no-store' } });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function input(request) {
|
|
18
|
+
try {
|
|
19
|
+
const value = await request.json();
|
|
20
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error();
|
|
21
|
+
return value;
|
|
22
|
+
} catch {
|
|
23
|
+
throw Object.assign(new Error('请求内容须为 JSON 对象。'), { status: 400, code: 'INVALID_JSON' });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function registerJournal(ctx, { store = new ReportStore(resolveReportRoot()), reportModel } = {}) {
|
|
28
|
+
const lifecycle = new AbortController();
|
|
29
|
+
let generating = false;
|
|
30
|
+
ctx.effect(() => () => lifecycle.abort());
|
|
31
|
+
function route(path, methods, handler) {
|
|
32
|
+
ctx.connection.fetch.register({
|
|
33
|
+
path: `/api/dsh-journal/${path}`, methods,
|
|
34
|
+
requestBody: 'buffered',
|
|
35
|
+
fetch: async request => {
|
|
36
|
+
try {
|
|
37
|
+
const signal = AbortSignal.any([request.signal, lifecycle.signal]);
|
|
38
|
+
signal.throwIfAborted();
|
|
39
|
+
return json(await handler(request, signal));
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (request.signal.aborted || lifecycle.signal.aborted || error.name === 'AbortError') {
|
|
42
|
+
return json({ error: '操作已取消。', code: 'ABORTED' }, 499);
|
|
43
|
+
}
|
|
44
|
+
return json({ error: error.message || '日记操作失败,请重试。', code: error.code || 'JOURNAL_ERROR' }, error.status || 500);
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
route('state', ['GET'], async () => ({ reports: await store.list(), model: modelState(ctx, reportModel) }));
|
|
50
|
+
route('preview', ['POST'], async (request, signal) => {
|
|
51
|
+
const range = normalizeRange(await input(request));
|
|
52
|
+
const { evidence: _evidence, ...preview } = await collectActivity(ctx, range, { signal });
|
|
53
|
+
return preview;
|
|
54
|
+
});
|
|
55
|
+
route('generate', ['POST'], async (request, signal) => {
|
|
56
|
+
const args = await input(request);
|
|
57
|
+
const range = normalizeRange(args);
|
|
58
|
+
if (args.mode !== 'local' && args.mode !== 'ai') {
|
|
59
|
+
throw Object.assign(new Error('请选择 AI 总结或本地整理。'), { status: 400, code: 'INVALID_MODE' });
|
|
60
|
+
}
|
|
61
|
+
if (generating) throw Object.assign(new Error('已有一份报告正在生成,请稍后重试。'), { status: 409, code: 'GENERATING' });
|
|
62
|
+
generating = true;
|
|
63
|
+
try {
|
|
64
|
+
const activity = await collectActivity(ctx, range, { signal });
|
|
65
|
+
const report = await createReport(ctx, activity, args.mode, { signal, reportModel });
|
|
66
|
+
signal.throwIfAborted();
|
|
67
|
+
return await store.save(report);
|
|
68
|
+
} finally {
|
|
69
|
+
generating = false;
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
route('report', ['GET', 'PUT'], async request => {
|
|
73
|
+
if (request.method === 'GET') return store.get(new URL(request.url).searchParams.get('id'));
|
|
74
|
+
const args = await input(request);
|
|
75
|
+
return store.update(args.id, { markdown: args.markdown });
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function apply(ctx) {
|
|
80
|
+
const { root } = await prepareReportStorage({ legacyRoot: LEGACY_DATA });
|
|
81
|
+
const store = new ReportStore(root);
|
|
82
|
+
const reportModel = await loadReportModel(store.root);
|
|
83
|
+
registerJournal(ctx, { store, reportModel });
|
|
84
|
+
}
|