sycommon-python-lib 0.2.12a3__py3-none-any.whl → 0.2.12a5__py3-none-any.whl

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.
@@ -0,0 +1,556 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>DevChat 开发协作</title>
7
+ <style>
8
+ :root {
9
+ --navy: #0f0966; --blue: #185fa5; --blue-bg: #e6f1fb;
10
+ --teal: #0f6e56; --teal-bg: #e1f5ee; --orange: #e68615; --orange-bg: #faeeda;
11
+ --red: #a32d2d; --red-bg: #fcebeb;
12
+ --ink: #1f2329; --ink-2: #4b5563; --ink-3: #8a919c;
13
+ --line: #e5e7eb; --bg: #f6f7f9; --card: #fff; --r: 10px;
14
+ }
15
+ * { box-sizing: border-box; margin: 0; padding: 0; }
16
+ html, body { height: 100%; font-family: 'PingFang SC','Microsoft YaHei','Segoe UI',sans-serif; color: var(--ink); font-size: 14px; background: var(--bg); }
17
+ body.standalone { display: flex; flex-direction: column; }
18
+ body.embedded { background: transparent; overflow: hidden; }
19
+
20
+ /* 悬浮球(嵌入模式) */
21
+ .dc-fab {
22
+ position: fixed; right: 22px; bottom: 22px; width: 52px; height: 52px;
23
+ border-radius: 50%; background: var(--navy); color: #fff; border: none; cursor: pointer;
24
+ font-size: 22px; display: none; align-items: center; justify-content: center;
25
+ box-shadow: 0 6px 18px rgba(15,9,102,.35); z-index: 2147483000; transition: transform .15s;
26
+ }
27
+ .dc-fab:hover { transform: scale(1.06); }
28
+ .dc-fab .dc-fab-badge {
29
+ position: absolute; top: -3px; right: -3px; min-width: 18px; height: 18px; padding: 0 4px;
30
+ border-radius: 9px; background: var(--red); color: #fff; font-size: 11px; line-height: 18px; text-align: center;
31
+ display: none;
32
+ }
33
+ .dc-fab .dc-fab-badge.show { display: block; }
34
+ body.embedded .dc-fab { display: flex; }
35
+
36
+ /* 面板 */
37
+ .dc-panel {
38
+ display: none; flex-direction: column;
39
+ width: 380px; height: 520px; max-height: calc(100vh - 44px);
40
+ background: var(--card); border: 1px solid var(--line); border-radius: 14px;
41
+ box-shadow: 0 12px 40px rgba(31,35,41,.22); overflow: hidden; z-index: 2147483001;
42
+ }
43
+ body.standalone .dc-panel { display: flex; width: 100%; height: 100%; max-height: none; border: none; border-radius: 0; }
44
+ body.embedded .dc-panel.open { display: flex; position: fixed; right: 22px; bottom: 86px; }
45
+
46
+ .dc-head {
47
+ display: flex; align-items: center; gap: 8px; padding: 12px 14px;
48
+ background: var(--navy); color: #fff; flex-shrink: 0;
49
+ }
50
+ .dc-head .dc-title { font-weight: 700; font-size: 14px; flex: 1; }
51
+ .dc-head .dc-sub { font-size: 11px; opacity: .75; }
52
+ .dc-head button {
53
+ background: rgba(255,255,255,.15); border: none; color: #fff; border-radius: 6px;
54
+ padding: 3px 9px; cursor: pointer; font-size: 12px;
55
+ }
56
+ .dc-head button:hover { background: rgba(255,255,255,.28); }
57
+
58
+ .dc-statusbar {
59
+ display: flex; align-items: center; gap: 6px; padding: 6px 14px;
60
+ background: var(--blue-bg); color: var(--blue); font-size: 12px; flex-shrink: 0;
61
+ }
62
+ .dc-statusbar.busy { background: var(--orange-bg); color: var(--orange); }
63
+ .dc-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
64
+ .dc-dot.pulse { animation: dcPulse 1.2s infinite; }
65
+ @keyframes dcPulse { 50% { opacity: .3; } }
66
+
67
+ .dc-messages { flex: 1; overflow-y: auto; padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
68
+ .dc-msg { max-width: 86%; }
69
+ .dc-msg.user { align-self: flex-end; }
70
+ .dc-msg-name { font-size: 11px; color: var(--ink-3); margin-bottom: 3px; }
71
+ .dc-msg.user .dc-msg-name { text-align: right; }
72
+ .dc-msg-bubble {
73
+ padding: 8px 11px; border-radius: 10px; background: var(--bg);
74
+ white-space: pre-wrap; word-break: break-word; line-height: 1.55; font-size: 13px;
75
+ }
76
+ .dc-msg.user .dc-msg-bubble { background: var(--navy); color: #fff; }
77
+ .dc-msg.claude .dc-msg-bubble { background: var(--teal-bg); border: 1px solid #cbe9de; }
78
+ .dc-msg.system .dc-msg-bubble { background: var(--orange-bg); color: #8a5508; font-size: 12px; }
79
+
80
+ .dc-tool {
81
+ align-self: flex-start; font-size: 11px; color: var(--ink-3);
82
+ background: var(--bg); border: 1px dashed var(--line); border-radius: 6px; padding: 2px 8px;
83
+ max-width: 86%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
84
+ }
85
+ .dc-typing {
86
+ align-self: flex-start; font-size: 12px; color: var(--teal); padding: 0 2px;
87
+ display: flex; gap: 4px; align-items: center;
88
+ }
89
+ .dc-typing .dc-caret { display: inline-block; width: 7px; background: var(--teal); animation: dcBlink .8s infinite; height: 13px; }
90
+ @keyframes dcBlink { 50% { opacity: 0; } }
91
+
92
+ .dc-compose { display: flex; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--line); flex-shrink: 0; background: #fff; }
93
+ .dc-compose textarea {
94
+ flex: 1; resize: none; border: 1px solid var(--line); border-radius: 8px;
95
+ padding: 7px 10px; font: inherit; height: 58px; outline: none;
96
+ }
97
+ .dc-compose textarea:focus { border-color: var(--blue); }
98
+ .dc-send-col { display: flex; flex-direction: column; gap: 6px; justify-content: flex-end; }
99
+ .dc-btn {
100
+ border: none; border-radius: 8px; padding: 7px 14px; cursor: pointer;
101
+ font: inherit; font-size: 13px; background: var(--navy); color: #fff;
102
+ }
103
+ .dc-btn:disabled { opacity: .5; cursor: not-allowed; }
104
+ .dc-btn.ghost { background: var(--orange-bg); color: #8a5508; font-size: 12px; padding: 5px 10px; }
105
+ .dc-btn.ghost:disabled { background: var(--line); color: var(--ink-3); }
106
+ .dc-hint { font-size: 11px; color: var(--ink-3); padding: 0 14px 8px; flex-shrink: 0; }
107
+
108
+ /* ===== 需求队列(左栏任务卡) ===== */
109
+ .dc-tabs { display: flex; border-bottom: 1px solid var(--line); flex-shrink: 0; }
110
+ .dc-tab {
111
+ flex: 1; padding: 8px 0; text-align: center; font-size: 12px; color: var(--ink-2);
112
+ background: none; border: none; cursor: pointer; border-bottom: 2px solid transparent;
113
+ font-family: inherit;
114
+ }
115
+ .dc-tab.active { color: var(--navy); border-bottom-color: var(--navy); font-weight: 600; }
116
+ .dc-tab .dc-tab-count {
117
+ display: inline-block; min-width: 16px; padding: 0 4px; margin-left: 3px;
118
+ border-radius: 8px; background: var(--bg); font-size: 10px; color: var(--ink-2);
119
+ }
120
+ .dc-tasks { flex: 1; overflow-y: auto; padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; }
121
+ .dc-task {
122
+ border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px;
123
+ background: #fff; display: flex; flex-direction: column; gap: 5px;
124
+ }
125
+ .dc-task.s-queued { border-left: 3px solid var(--ink-3); }
126
+ .dc-task.s-running { border-left: 3px solid var(--blue); background: var(--blue-bg); }
127
+ .dc-task.s-done { border-left: 3px solid var(--teal); }
128
+ .dc-task.s-error,
129
+ .dc-task.s-cancelled { border-left: 3px solid var(--red); background: var(--red-bg); }
130
+ .dc-task-top { display: flex; align-items: center; gap: 6px; }
131
+ .dc-task-title {
132
+ flex: 1; font-size: 12px; color: var(--ink); overflow: hidden;
133
+ text-overflow: ellipsis; white-space: nowrap;
134
+ }
135
+ .dc-pill {
136
+ font-size: 10px; padding: 1px 8px; border-radius: 8px; white-space: nowrap;
137
+ display: inline-flex; align-items: center; gap: 4px;
138
+ }
139
+ .dc-pill.p-queued { background: var(--bg); color: var(--ink-2); }
140
+ .dc-pill.p-running { background: #d9e8f7; color: var(--blue); }
141
+ .dc-pill.p-running .dc-mini-spin { animation: dcPulse 1s infinite; }
142
+ .dc-pill.p-done { background: var(--teal-bg); color: var(--teal); }
143
+ .dc-pill.p-error, .dc-pill.p-cancelled { background: var(--red-bg); color: var(--red); }
144
+ .dc-task-meta { font-size: 10px; color: var(--ink-3); display: flex; gap: 8px; }
145
+ .dc-task-err { font-size: 10px; color: var(--red); word-break: break-all; }
146
+ .dc-task .dc-task-cancel {
147
+ border: none; background: none; color: var(--ink-3); cursor: pointer; font-size: 12px;
148
+ padding: 0 2px;
149
+ }
150
+ .dc-task .dc-task-cancel:hover { color: var(--red); }
151
+ </style>
152
+ </head>
153
+ <body class="standalone">
154
+ <button class="dc-fab" id="dcFab" aria-label="打开 DevChat 开发协作">
155
+ <span aria-hidden="true">💬</span>
156
+ <span class="dc-fab-badge" id="dcBadge">1</span>
157
+ </button>
158
+
159
+ <div class="dc-panel" id="dcPanel" role="dialog" aria-label="DevChat 开发协作面板">
160
+ <div class="dc-head">
161
+ <div style="flex:1">
162
+ <div class="dc-title">DevChat 开发协作</div>
163
+ <div class="dc-sub" id="dcSub">群聊 · claude code 在编队里</div>
164
+ </div>
165
+ <button id="dcRestartBtn" title="重建并重启服务(仅管理员)" style="display:none">⟳ 重启服务</button>
166
+ <button id="dcCloseBtn" title="收起" style="display:none">—</button>
167
+ </div>
168
+ <div class="dc-statusbar" id="dcStatus"><span class="dc-dot"></span><span id="dcStatusText">连接中…</span></div>
169
+ <div class="dc-tabs">
170
+ <button class="dc-tab active" id="dcTabChat" data-tab="chat">群聊</button>
171
+ <button class="dc-tab" id="dcTabTasks" data-tab="tasks">需求队列 <span class="dc-tab-count" id="dcTaskCount">0</span></button>
172
+ </div>
173
+ <div class="dc-messages" id="dcMessages" aria-live="polite"></div>
174
+ <div class="dc-tasks" id="dcTasks" style="display:none" aria-label="需求队列"></div>
175
+ <div class="dc-hint" id="dcHint">claude 在本机项目目录执行开发任务;所有打开本页的人共享此群聊。</div>
176
+ <div class="dc-compose">
177
+ <div id="dcAttachRow" style="display:none;flex-wrap:wrap;gap:4px"></div>
178
+ <textarea id="dcInput" placeholder="给 claude 派个开发任务…(Enter 发送 / Shift+Enter 换行,📎 附件)"></textarea>
179
+ <div class="dc-send-col">
180
+ <input type="file" id="dcFileInput" multiple style="display:none"
181
+ accept="image/*,.txt,.md,.json,.yaml,.yml,.csv,.log,.xml,.html,.js,.ts,.py,.go,.java,.sql,.pdf,.doc,.docx,.xls,.xlsx,.zip,.tar,.gz">
182
+ <button class="dc-btn ghost" id="dcAttachBtn" title="选择文件/图片附件">📎</button>
183
+ <button class="dc-btn ghost" id="dcStopBtn" style="display:none">停止</button>
184
+ <button class="dc-btn" id="dcSendBtn">发送</button>
185
+ </div>
186
+ </div>
187
+ </div>
188
+
189
+ <script>
190
+ (function () {
191
+ 'use strict';
192
+
193
+ // ── 嵌入模式判定 ──
194
+ var params = new URLSearchParams(location.search);
195
+ var embedded = params.get('embed') === '1' || window.self !== window.top;
196
+ if (embedded) {
197
+ document.body.classList.remove('standalone');
198
+ document.body.classList.add('embedded');
199
+ document.getElementById('dcCloseBtn').style.display = '';
200
+ }
201
+
202
+ var BASE = (params.get('base') || '').replace(/\/+$/, '');
203
+ function url(p) { return BASE + p; }
204
+
205
+ var $ = function (id) { return document.getElementById(id); };
206
+ var fab = $('dcFab'), panel = $('dcPanel'), badge = $('dcBadge');
207
+ var msgs = $('dcMessages'), input = $('dcInput'), sendBtn = $('dcSendBtn');
208
+ var stopBtn = $('dcStopBtn'), restartBtn = $('dcRestartBtn'), closeBtn = $('dcCloseBtn');
209
+ var statusBar = $('dcStatus'), statusText = $('dcStatusText'), sub = $('dcSub');
210
+
211
+ var state = {
212
+ open: !embedded, running: false, isAdmin: false, unread: 0, seenTs: 0,
213
+ typingEl: null, es: null, bootedAt: Date.now(),
214
+ tasks: [], activeTab: 'chat'
215
+ };
216
+
217
+ // ── 任务队列(需求状态卡:排队/进行中/完成) ──
218
+ var STATUS_LABEL = { queued: '排队等待', running: '进行中', done: '完成', error: '失败', cancelled: '已取消' };
219
+ function fmtDuration(ms) {
220
+ if (!ms || ms <= 0) return '';
221
+ var s = Math.round(ms / 1000);
222
+ if (s < 60) return s + 's';
223
+ return Math.floor(s / 60) + 'm' + (s % 60) + 's';
224
+ }
225
+ function fmtTaskTime(iso) {
226
+ try {
227
+ var d = toDate(iso);
228
+ if (Number.isNaN(d.getTime())) return '';
229
+ return d.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
230
+ } catch (e) { return ''; }
231
+ }
232
+ function renderTasks() {
233
+ var box = $('dcTasks');
234
+ var counts = { queued: 0, running: 0, done: 0, error: 0, cancelled: 0 };
235
+ state.tasks.forEach(function (t) { counts[t.status] = (counts[t.status] || 0) + 1; });
236
+ $('dcTaskCount').textContent = String(counts.queued + counts.running);
237
+ box.innerHTML = '';
238
+ if (!state.tasks.length) {
239
+ var empty = document.createElement('div');
240
+ empty.className = 'dc-task-meta';
241
+ empty.textContent = '还没有需求。在「群聊」里给 claude 发一条任务,这里会出现它的状态卡。';
242
+ box.appendChild(empty);
243
+ return;
244
+ }
245
+ state.tasks.forEach(function (t) {
246
+ var card = document.createElement('div');
247
+ card.className = 'dc-task s-' + t.status;
248
+ var top = document.createElement('div');
249
+ top.className = 'dc-task-top';
250
+ var title = document.createElement('div');
251
+ title.className = 'dc-task-title';
252
+ title.textContent = (t.prompt || '').slice(0, 60) || '(空需求)';
253
+ title.title = t.prompt || '';
254
+ var pill = document.createElement('span');
255
+ pill.className = 'dc-pill p-' + t.status;
256
+ pill.textContent = (t.status === 'running' ? '⏳ ' : '') + (STATUS_LABEL[t.status] || t.status);
257
+ top.appendChild(title); top.appendChild(pill);
258
+ if (t.status === 'queued') {
259
+ // 排队任务:走任务删除(只影响这一条),绝不能调全局 /stop —
260
+ // 那会取消【正在跑的】任务,与本卡意图正好相反。
261
+ var del = document.createElement('button');
262
+ del.className = 'dc-task-cancel';
263
+ del.textContent = '✕';
264
+ del.title = '删除这条排队需求';
265
+ del.addEventListener('click', function () {
266
+ post('/devchat/tasks/delete', { id: t.id }).then(function () { loadTasks(); });
267
+ });
268
+ top.appendChild(del);
269
+ } else if (t.status === 'running') {
270
+ var stop = document.createElement('button');
271
+ stop.className = 'dc-task-cancel';
272
+ stop.textContent = '✕';
273
+ stop.title = '停止正在执行的这条需求';
274
+ stop.addEventListener('click', function () {
275
+ post('/devchat/stop', {}).then(function () { loadTasks(); refreshStatus(); });
276
+ });
277
+ top.appendChild(stop);
278
+ }
279
+ card.appendChild(top);
280
+ var meta = document.createElement('div');
281
+ meta.className = 'dc-task-meta';
282
+ var dur = t.duration_ms ? fmtDuration(t.duration_ms) : (t.status === 'running' ? '进行中' : '');
283
+ meta.textContent = '#' + String(t.seq).slice(-6) + ' · ' + (t.requester || '?') + ' · ' + fmtTaskTime(t.created_at) + (dur ? ' · ' + dur : '');
284
+ card.appendChild(meta);
285
+ if (t.error) {
286
+ var err = document.createElement('div');
287
+ err.className = 'dc-task-err';
288
+ err.textContent = t.error;
289
+ card.appendChild(err);
290
+ }
291
+ box.appendChild(card);
292
+ });
293
+ }
294
+ function loadTasks() {
295
+ return fetch(url('/devchat/tasks?limit=100'), { credentials: 'include' })
296
+ .then(function (r) { return r.json(); })
297
+ .then(function (d) { state.tasks = d.tasks || []; renderTasks(); })
298
+ .catch(function () {});
299
+ }
300
+ // ── tab 切换(切到任务列表也滚到底:最新执行历史在底部) ──
301
+ function switchTab(name) {
302
+ state.activeTab = name;
303
+ $('dcTabChat').classList.toggle('active', name === 'chat');
304
+ $('dcTabTasks').classList.toggle('active', name === 'tasks');
305
+ msgs.style.display = name === 'chat' ? '' : 'none';
306
+ $('dcTasks').style.display = name === 'tasks' ? '' : 'none';
307
+ $('dcHint').style.display = name === 'chat' ? '' : 'none';
308
+ requestAnimationFrame(function () { requestAnimationFrame(function () {
309
+ var box = name === 'tasks' ? $('dcTasks') : msgs;
310
+ if (box) box.scrollTop = box.scrollHeight;
311
+ }); });
312
+ }
313
+ $('dcTabChat').addEventListener('click', function () { switchTab('chat'); });
314
+ $('dcTabTasks').addEventListener('click', function () { switchTab('tasks'); loadTasks(); });
315
+
316
+ // ── 面板开合 ──
317
+ function renderOpen() {
318
+ if (embedded) panel.classList.toggle('open', state.open);
319
+ if (state.open) { state.unread = 0; renderBadge(); scrollBottom(); }
320
+ }
321
+ function renderBadge() {
322
+ if (!embedded) return;
323
+ badge.textContent = state.unread > 9 ? '9+' : String(state.unread);
324
+ badge.classList.toggle('show', !state.open && state.unread > 0);
325
+ }
326
+ fab.addEventListener('click', function () { state.open = !state.open; renderOpen(); });
327
+ closeBtn.addEventListener('click', function () { state.open = false; renderOpen(); });
328
+
329
+ // ── 状态 ──
330
+ function setRunning(r) {
331
+ state.running = r;
332
+ statusBar.classList.toggle('busy', r);
333
+ statusText.textContent = r ? 'claude 执行中…(实时进度见下方)' : 'claude 空闲 · 可派任务';
334
+ var dot = statusBar.querySelector('.dc-dot');
335
+ if (dot) dot.classList.toggle('pulse', r);
336
+ stopBtn.style.display = r ? '' : 'none';
337
+ sendBtn.disabled = false;
338
+ sub.textContent = r ? '群聊 · claude code 工作中' : '群聊 · claude code 在编队里';
339
+ }
340
+
341
+ // ── 消息渲染 ──
342
+ function scrollBottom() { msgs.scrollTop = msgs.scrollHeight; }
343
+ // 后端 created_at 是 epoch 秒(SSE 本地构造的是 ISO 串):数字且
344
+ // < 1e12 视为秒 → 乘 1000;其余(Date 可直接解析的串)原样。
345
+ function toDate(v) {
346
+ var n = typeof v === 'number' ? v : Number(v);
347
+ if (!Number.isNaN(n) && v !== null && v !== '' && !/[^0-9.]/.test(String(v))) {
348
+ return new Date(n < 1e12 ? n * 1000 : n);
349
+ }
350
+ return new Date(v);
351
+ }
352
+ function fmtTime(iso) {
353
+ try { var d = toDate(iso); if (Number.isNaN(d.getTime())) return ''; return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; }
354
+ }
355
+ function appendMessage(m) {
356
+ var wrap = document.createElement('div');
357
+ wrap.className = 'dc-msg ' + (m.sender_role || 'system');
358
+ var name = document.createElement('div');
359
+ name.className = 'dc-msg-name';
360
+ name.textContent = (m.sender_name || m.sender_role || '?') + ' · ' + fmtTime(m.created_at);
361
+ var bubble = document.createElement('div');
362
+ bubble.className = 'dc-msg-bubble';
363
+ bubble.textContent = m.content || '';
364
+ wrap.appendChild(name); wrap.appendChild(bubble);
365
+ clearTyping();
366
+ msgs.appendChild(wrap);
367
+ if (wrap.offsetTop < msgs.scrollTop || wrap.offsetTop > msgs.scrollTop + msgs.clientHeight - 80 || state.open) scrollBottom();
368
+ if (m.created_at && toDate(m.created_at).getTime() > state.seenTs) {
369
+ state.seenTs = toDate(m.created_at).getTime();
370
+ }
371
+ if (!state.open && embedded) { state.unread++; renderBadge(); }
372
+ }
373
+ function appendToolLine(tool, phase) {
374
+ var el = document.createElement('div');
375
+ el.className = 'dc-tool';
376
+ el.textContent = (phase === 'call' ? '🔧 ' : '✓ ') + (tool || 'tool');
377
+ msgs.appendChild(el);
378
+ if (state.open) scrollBottom();
379
+ }
380
+ function showTyping(chunk) {
381
+ if (!state.typingEl) {
382
+ state.typingEl = document.createElement('div');
383
+ state.typingEl.className = 'dc-typing';
384
+ state.typingEl.innerHTML = '<span class="dc-typing-text"></span><span class="dc-caret"></span>';
385
+ msgs.appendChild(state.typingEl);
386
+ }
387
+ var t = state.typingEl.querySelector('.dc-typing-text');
388
+ t.textContent = (t.textContent || '') + chunk;
389
+ if (t.textContent.length > 400) t.textContent = t.textContent.slice(-400);
390
+ if (state.open) scrollBottom();
391
+ }
392
+ function clearTyping() {
393
+ if (state.typingEl && state.typingEl.parentNode) state.typingEl.parentNode.removeChild(state.typingEl);
394
+ state.typingEl = null;
395
+ }
396
+
397
+ // ── API ──
398
+ function post(p, body) {
399
+ return fetch(url(p), {
400
+ method: 'POST', credentials: 'include',
401
+ headers: { 'Content-Type': 'application/json' },
402
+ body: JSON.stringify(body || {})
403
+ }).then(function (r) { return r.json().catch(function () { return {}; }); });
404
+ }
405
+ function loadHistory() {
406
+ return fetch(url('/devchat/messages?limit=200'), { credentials: 'include' })
407
+ .then(function (r) { return r.json(); })
408
+ .then(function (d) {
409
+ (d.messages || []).forEach(function (m) {
410
+ // 过滤掉本页 boot 前很久的系统重复提示可选;全量展示(群聊语义)
411
+ appendMessage(m);
412
+ });
413
+ setRunning(!!d.running);
414
+ if (d.session_id) state.sessionId = d.session_id;
415
+ }).catch(function () { statusText.textContent = '历史加载失败'; });
416
+ }
417
+ function refreshStatus() {
418
+ fetch(url('/devchat/status'), { credentials: 'include' })
419
+ .then(function (r) { return r.json(); })
420
+ .then(function (d) {
421
+ state.isAdmin = !!d.is_admin;
422
+ restartBtn.style.display = state.isAdmin ? '' : 'none';
423
+ setRunning(!!d.running);
424
+ sub.textContent = (d.viewers || 1) + ' 人在线 · ' + (d.running ? 'claude 工作中' : 'claude 空闲');
425
+ }).catch(function () {});
426
+ }
427
+
428
+ // ── SSE ──
429
+ function connect() {
430
+ if (state.es) { state.es.close(); state.es = null; }
431
+ var es = new EventSource(url('/devchat/stream'));
432
+ state.es = es;
433
+ es.onopen = function () { statusText.textContent = state.running ? 'claude 执行中…' : '已连接 · claude 空闲'; };
434
+ es.onerror = function () {
435
+ statusText.textContent = '连接断开,重连中…';
436
+ es.close(); if (state.es === es) state.es = null;
437
+ setTimeout(connect, 3000);
438
+ };
439
+ es.onmessage = function (e) {
440
+ var d; try { d = JSON.parse(e.data); } catch (err) { return; }
441
+ switch (d.type) {
442
+ case 'hello':
443
+ setRunning(!!d.running);
444
+ if (d.session_id) state.sessionId = d.session_id;
445
+ break;
446
+ case 'message': appendMessage(d.message || {}); break;
447
+ case 'typing': showTyping(d.content || ''); break;
448
+ case 'tool': appendToolLine(d.tool, d.phase); break;
449
+ case 'status': setRunning(d.state === 'running'); break;
450
+ case 'done':
451
+ setRunning(false);
452
+ if (d.state === 'success') restartBtn.style.display = state.isAdmin ? '' : 'none';
453
+ break;
454
+ case 'error':
455
+ clearTyping();
456
+ appendMessage({ sender_role: 'system', sender_name: 'devchat', content: '⚠ ' + (d.message || '未知错误'), created_at: new Date().toISOString() });
457
+ break;
458
+ case 'restarting':
459
+ clearTyping();
460
+ appendMessage({ sender_role: 'system', sender_name: 'devchat', content: '♻ ' + (d.message || '服务重启中…'), created_at: new Date().toISOString() });
461
+ statusText.textContent = '服务重启中,稍后自动重连…';
462
+ setTimeout(function () { location.reload(); }, 6000);
463
+ break;
464
+ case 'tasks':
465
+ state.tasks = d.tasks || [];
466
+ renderTasks();
467
+ break;
468
+ }
469
+ };
470
+ }
471
+
472
+ // ── 发送 ──
473
+ // ── 附件(文件/图片):选择 → 上传 → 路径清单拼进消息文本 ──
474
+ var attachRow = $('dcAttachRow'), fileInput = $('dcFileInput');
475
+ var attachments = []; // {name}
476
+ $('dcAttachBtn').addEventListener('click', function () { fileInput.click(); });
477
+ fileInput.addEventListener('change', function () {
478
+ Array.prototype.slice.call(fileInput.files || []).forEach(function (f) {
479
+ if (attachments.length < 5) attachments.push(f);
480
+ });
481
+ fileInput.value = '';
482
+ renderAttachments();
483
+ });
484
+ function renderAttachments() {
485
+ attachRow.style.display = attachments.length ? 'flex' : 'none';
486
+ attachRow.innerHTML = '';
487
+ attachments.forEach(function (f, i) {
488
+ var tag = document.createElement('span');
489
+ tag.style.cssText = 'font-size:11px;color:#4b5563;background:#f6f7f9;border:1px solid #e5e7eb;border-radius:6px;padding:1px 6px;cursor:pointer';
490
+ tag.textContent = (f.type && f.type.indexOf('image/') === 0 ? '🖼 ' : '📄 ') + f.name + ' ✕';
491
+ tag.title = '点击移除';
492
+ tag.addEventListener('click', function () {
493
+ attachments.splice(i, 1); renderAttachments();
494
+ });
495
+ attachRow.appendChild(tag);
496
+ });
497
+ }
498
+ function uploadAttachment(f) {
499
+ var form = new FormData();
500
+ form.append('file', f);
501
+ return fetch(url('/devchat/upload'), { method: 'POST', credentials: 'include', body: form })
502
+ .then(function (r) { return r.json(); })
503
+ .then(function (d) {
504
+ if (d.path) return d.path;
505
+ appendMessage({ sender_role: 'system', sender_name: 'devchat', content: '⚠ 上传失败:' + f.name, created_at: new Date().toISOString() });
506
+ return null;
507
+ })
508
+ .catch(function () { return null; });
509
+ }
510
+ function send() {
511
+ var text = input.value.trim();
512
+ if (!text) return;
513
+ sendBtn.disabled = true;
514
+ var pre = attachments.length
515
+ ? Promise.all(attachments.map(uploadAttachment))
516
+ : Promise.resolve([]);
517
+ pre.then(function (paths) {
518
+ attachments = []; renderAttachments();
519
+ paths = paths.filter(Boolean);
520
+ if (paths.length) {
521
+ text += '\n\n[附件](可用 Read 工具直接查看):\n' + paths.map(function (p) { return '- ' + p; }).join('\n');
522
+ }
523
+ return post('/devchat/send', { content: text }).then(function (d) {
524
+ if (d.started) { setRunning(true); input.value = ''; }
525
+ else if (d.detail) {
526
+ appendMessage({ sender_role: 'system', sender_name: 'devchat', content: d.detail, created_at: new Date().toISOString() });
527
+ }
528
+ sendBtn.disabled = false;
529
+ });
530
+ }).catch(function () { sendBtn.disabled = false; });
531
+ }
532
+ sendBtn.addEventListener('click', send);
533
+ input.addEventListener('keydown', function (e) {
534
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
535
+ });
536
+ stopBtn.addEventListener('click', function () {
537
+ post('/devchat/stop', {}).then(function () { refreshStatus(); });
538
+ });
539
+ restartBtn.addEventListener('click', function () {
540
+ if (!confirm('重建并重启当前服务?(构建失败不会重启)')) return;
541
+ restartBtn.disabled = true;
542
+ post('/devchat/restart', {}).then(function (d) {
543
+ if (!d.detail || d.detail.indexOf('已安排') < 0) { restartBtn.disabled = false; alert(d.detail || '重启失败'); }
544
+ }).catch(function () { restartBtn.disabled = false; });
545
+ });
546
+
547
+ // ── 启动 ──
548
+ renderOpen();
549
+ loadTasks();
550
+ loadHistory().then(refreshStatus).then(connect);
551
+ setInterval(refreshStatus, 15000);
552
+ setInterval(function () { if (state.activeTab === 'tasks') loadTasks(); }, 10000);
553
+ })();
554
+ </script>
555
+ </body>
556
+ </html>
@@ -33,6 +33,7 @@ import shutil
33
33
  import signal
34
34
  import subprocess
35
35
  import sys
36
+ import threading
36
37
  import time
37
38
  import uuid
38
39
  from dataclasses import dataclass, field
@@ -139,7 +140,7 @@ class Message:
139
140
 
140
141
 
141
142
  class _MemStore:
142
- """进程内环形缓冲(Redis 不可用降级;重启即失)。"""
143
+ """进程内环形缓冲(SQLite 不可用降级;重启即失)。"""
143
144
 
144
145
  def __init__(self, limit: int = 500):
145
146
  self._ring: List[Message] = []
@@ -189,13 +190,59 @@ class DevchatState:
189
190
  self.events = _open_event_store(cfg)
190
191
  # 历史会话列表口(「以后可恢复」);None = 端点回空。
191
192
  self.session_archive = _open_session_archive(cfg)
193
+ # 宿主地址(审批 MCP 回调用):面板请求探测值 > app.yaml 兜底。
194
+ self._host_lock = threading.Lock()
195
+ self._captured_host = ""
196
+ self._fallback_host = ""
197
+ self._fallback_port = 0
198
+
199
+ # ---- 宿主地址(与 Go 版 Devchat.serviceBase 同语义) ----
200
+
201
+ def set_fallback_addr(self, host: str, port: int) -> None:
202
+ """服务自身地址(app.yaml Host/Port,setup 时注入)。"""
203
+ with self._host_lock:
204
+ self._fallback_host = host or ""
205
+ self._fallback_port = int(port or 0)
206
+
207
+ def capture_host(self, host: str) -> None:
208
+ """面板请求真实 Host:port(仅首次记录,浏览器怎么连就怎么回调)。"""
209
+ if not host:
210
+ return
211
+ with self._host_lock:
212
+ if not self._captured_host:
213
+ self._captured_host = host
214
+
215
+ @staticmethod
216
+ def _normalize(host_port: str) -> str:
217
+ """监听形态(0.0.0.0/::/空)归一回环;具体 IP 原样。"""
218
+ host, _, port = host_port.rpartition(":")
219
+ if not host or host in ("0.0.0.0", "::"):
220
+ host = "127.0.0.1"
221
+ return f"{host}:{port}"
222
+
223
+ def service_base(self) -> str:
224
+ with self._host_lock:
225
+ captured = self._captured_host
226
+ fb_host = self._fallback_host
227
+ fb_port = self._fallback_port
228
+ if captured:
229
+ return "http://" + self._normalize(captured)
230
+ if fb_port > 0:
231
+ return "http://" + self._normalize(f"{fb_host or '127.0.0.1'}:{fb_port}")
232
+ port = os.environ.get("PORT", "")
233
+ if port:
234
+ return f"http://127.0.0.1:{port}"
235
+ return "http://127.0.0.1:8080"
192
236
 
193
237
  def _open_message_store(self) -> None:
194
- from .store import open_message_store
238
+ from .store import SqliteMessageStore
195
239
  root = self.cfg.projectRoot or os.getcwd()
196
- path = os.path.join(root, ".devchat", "devchat.db")
197
- if (ms := open_message_store(path, self.cfg.channel, self.cfg.maxHistory)) is not None:
198
- self.store = ms
240
+ conn = _open_shared_conn(os.path.join(root, ".devchat", "devchat.db"))
241
+ if conn is not None:
242
+ try:
243
+ self.store = SqliteMessageStore(conn, self.cfg.channel, self.cfg.maxHistory)
244
+ except Exception: # noqa: BLE001 — 退 _MemStore
245
+ pass
199
246
 
200
247
  def broadcast_tasks(self) -> None:
201
248
  """任务列表快照广播(SSE type=tasks;store 空时跳过)。"""
@@ -238,37 +285,77 @@ class DevchatState:
238
285
  self.last_status = status
239
286
 
240
287
 
288
+ # _shared_conns 同一 devchat.db 路径 → 唯一连接(任务/消息/事件/会话
289
+ # 四存储共用 — 多连接各持锁写同库会 SQLITE_BUSY,广播路径的 suppress
290
+ # 把它吞成静默丢数据)。按路径缓存:不同 projectRoot 不同库。WAL 模式:
291
+ # 读写不互斥,崩溃安全。
292
+ _shared_conns: Dict[str, "sqlite3.Connection"] = {}
293
+ _shared_conns_mu = threading.Lock()
294
+
295
+
296
+ def _open_shared_conn(path: str):
297
+ """打开(或复用)该 devchat.db 路径的共享连接;失败 None(退内存)。"""
298
+ key = os.path.abspath(path)
299
+ with _shared_conns_mu:
300
+ if key in _shared_conns:
301
+ return _shared_conns[key]
302
+ try:
303
+ import sqlite3 as _sqlite3
304
+ from pathlib import Path as _Path
305
+ _Path(path).parent.mkdir(parents=True, exist_ok=True)
306
+ conn = _sqlite3.connect(path, check_same_thread=False)
307
+ conn.execute("PRAGMA journal_mode=WAL")
308
+ conn.execute("PRAGMA busy_timeout=5000")
309
+ except Exception as exc: # noqa: BLE001 — 降级可用优先
310
+ SYLogger.warning(f"[Devchat] sqlite 不可用,退内存: {exc}")
311
+ return None
312
+ with _shared_conns_mu:
313
+ # 竞态双开:后开者让位(先开的赢,多余连接关掉)。
314
+ if key in _shared_conns:
315
+ conn.close()
316
+ return _shared_conns[key]
317
+ _shared_conns[key] = conn
318
+ return conn
319
+
320
+
241
321
  def _open_task_store(cfg: DevchatConfig):
242
322
  """SQLite 任务库({projectRoot}/.devchat/devchat.db);失败退内存。"""
243
323
  from .tasks import MemTaskStore, SqliteTaskStore
244
324
  root = cfg.projectRoot or os.getcwd()
245
325
  path = os.path.join(root, ".devchat", "devchat.db")
326
+ conn = _open_shared_conn(path)
327
+ if conn is None:
328
+ return MemTaskStore(200)
246
329
  try:
247
- return SqliteTaskStore(path)
330
+ return SqliteTaskStore(None, conn=conn)
248
331
  except Exception as exc: # noqa: BLE001 — 降级可用优先
249
332
  SYLogger.warning(f"[Devchat] task sqlite 不可用,退内存: {exc}")
250
333
  return MemTaskStore(200)
251
334
 
252
335
 
253
336
  def _open_event_store(cfg: DevchatConfig):
254
- """事件归档库(devchat_events,同 devchat.db);失败 None(跳过归档)。"""
337
+ """事件归档库(devchat_events,同 devchat.db 共享连接);失败 None。"""
255
338
  from .tasks import SqliteEventStore
256
339
  root = cfg.projectRoot or os.getcwd()
257
- path = os.path.join(root, ".devchat", "devchat.db")
340
+ conn = _open_shared_conn(os.path.join(root, ".devchat", "devchat.db"))
341
+ if conn is None:
342
+ return None
258
343
  try:
259
- return SqliteEventStore(path)
344
+ return SqliteEventStore(conn=conn)
260
345
  except Exception as exc: # noqa: BLE001 — 归档是增强,缺席不阻断
261
346
  SYLogger.warning(f"[Devchat] event sqlite 不可用,事件不归档: {exc}")
262
347
  return None
263
348
 
264
349
 
265
350
  def _open_session_archive(cfg: DevchatConfig):
266
- """历史会话档案(devchat_sessions,同 devchat.db);失败 None。"""
351
+ """历史会话档案(devchat_sessions,同 devchat.db 共享连接);失败 None。"""
267
352
  from .tasks import SqliteSessionArchive
268
353
  root = cfg.projectRoot or os.getcwd()
269
- path = os.path.join(root, ".devchat", "devchat.db")
354
+ conn = _open_shared_conn(os.path.join(root, ".devchat", "devchat.db"))
355
+ if conn is None:
356
+ return None
270
357
  try:
271
- return SqliteSessionArchive(path)
358
+ return SqliteSessionArchive(conn=conn)
272
359
  except Exception as exc: # noqa: BLE001 — 列表是增强,缺席不阻断
273
360
  SYLogger.warning(f"[Devchat] session archive sqlite 不可用: {exc}")
274
361
  return None
@@ -299,10 +386,16 @@ async def _drive_claude(st: DevchatState, prompt: str, seq: int, task_id: str) -
299
386
  reply_parts: List[str] = []
300
387
  got_session_id = ""
301
388
  final_status = "success"
389
+ # 宿主地址(探测 > app.yaml 兜底)注入子环境(审批链路预留,与 Go 版
390
+ # 同语义;当前 py 版仍 skip-permissions,环境变量仅占位不生效)。
391
+ env = dict(os.environ)
392
+ env["DEVCHAT_BASE_URL"] = st.service_base() + st.cfg.basePath
393
+ env["DEVCHAT_TASK_ID"] = task_id
394
+ env["DEVCHAT_SESSION_ID"] = resume_sid
302
395
 
303
396
  try:
304
397
  proc = await asyncio.create_subprocess_exec(
305
- *args, cwd=cwd,
398
+ *args, cwd=cwd, env=env,
306
399
  stdout=asyncio.subprocess.PIPE,
307
400
  stderr=asyncio.subprocess.DEVNULL,
308
401
  stdin=asyncio.subprocess.DEVNULL,
@@ -315,7 +408,11 @@ async def _drive_claude(st: DevchatState, prompt: str, seq: int, task_id: str) -
315
408
  continue
316
409
  with contextlib.suppress(json.JSONDecodeError):
317
410
  ev = json.loads(line)
318
- got_session_id = _translate(st, ev, reply_parts, task_id) or got_session_id
411
+ got = _translate(st, ev, reply_parts, task_id)
412
+ if got == "__error__":
413
+ final_status = "error"
414
+ elif got:
415
+ got_session_id = got
319
416
 
320
417
  rc = await proc.wait()
321
418
  if rc != 0:
@@ -419,6 +516,10 @@ def _translate(st: DevchatState, ev: dict, reply_parts: List[str],
419
516
  if ev.get("is_error"):
420
517
  st.broadcast({"type": "error", "message": ev.get("result", "")})
421
518
  _archive(st, task_id, "error", {"message": ev.get("result", "")})
519
+ # 哨兵:claude 报告本轮失败 → 任务终态必须是 error(否则状态卡
520
+ # 误标 done 且成功提示/重启指引误发)。与 Go 版 result.IsError
521
+ # → finalStatus="error" 同语义。
522
+ sid = "__error__"
422
523
  return sid
423
524
 
424
525
 
@@ -456,7 +557,16 @@ def _default_restart_self() -> str:
456
557
  ts = int(time.time() * 1000)
457
558
  log_path = os.path.join(os.path.sep + "tmp" if sys.platform != "win32" else os.environ.get("TEMP", "."),
458
559
  f"devchat-restart-{ts}.log")
459
- argv = [sys.executable] + sys.argv[1:]
560
+ # 完整重建原命令行(修复:旧版丢 argv[0] — uvicorn 入口/脚本名
561
+ # 被吞,重启后命令不完整直接退出 = 永久停机):
562
+ # argv[0] 以 .py 结尾 → [python, 脚本, *rest];
563
+ # 否则(uvicorn 等 console-script)→ 原样 [argv0, *rest],
564
+ # 入口不可执行时加解释器前缀。
565
+ argv0, rest = sys.argv[0], sys.argv[1:]
566
+ if argv0.endswith(".py") or not os.access(argv0, os.X_OK):
567
+ argv = [sys.executable, argv0, *rest]
568
+ else:
569
+ argv = [argv0, *rest]
460
570
  script = (
461
571
  f"while kill -0 {old_pid} 2>/dev/null; do sleep 0.3; done\n"
462
572
  f"cd {os.getcwd()} && exec {' '.join(argv)} >>{log_path} 2>&1\n"
@@ -470,7 +580,6 @@ def _default_restart_self() -> str:
470
580
  with contextlib.suppress(Exception):
471
581
  os.kill(old_pid, signal.SIGTERM)
472
582
 
473
- import threading
474
583
  threading.Thread(target=_self_terminate, daemon=True).start()
475
584
  return f"重启已安排(新日志: {log_path})"
476
585
 
@@ -514,8 +623,38 @@ def setup_devchat_handler(app: FastAPI, config: Optional[dict] = None) -> FastAP
514
623
  cfg.projectRoot = os.getcwd()
515
624
  st = DevchatState(cfg)
516
625
 
626
+ # 启动恢复:上次崩溃/重启留下的 running 残影归为 error(没有活着的
627
+ # 协程在跑它们,不清理则状态卡永远「进行中」且排队任务不被接力)。
628
+ if st.tasks is not None:
629
+ with contextlib.suppress(Exception):
630
+ n = st.tasks.recover_stale()
631
+ if n:
632
+ SYLogger.info(f"[Devchat] 启动恢复:{n} 条中断任务归为 error")
633
+
634
+ # 服务自身地址(app.yaml 的 Host/Port):审批 MCP 回调的兜底 —
635
+ # 面板请求未探测到真实 Host 前按它回环调用(与 Go 版同语义)。
636
+ # 配置源:宿主 Services 已加载时读其 _config dict(app.yaml 顶层键);
637
+ # 兜底 Config 单例的 config dict。两处都是 dict 取值(非属性),
638
+ # 与 services.py 的读取方式一致。
639
+ with contextlib.suppress(Exception):
640
+ host, port = "", 0
641
+ try:
642
+ from sycommon.services import Services
643
+ host = str(Services._config.get("Host", "") or "")
644
+ port = int(Services._config.get("Port", 0) or 0)
645
+ except Exception: # noqa: BLE001 — Services 未装配时走 Config 单例
646
+ from sycommon.config.Config import Config
647
+ conf = Config().config
648
+ host = str(conf.get("Host", "") or "")
649
+ port = int(conf.get("Port", 0) or 0)
650
+ st.set_fallback_addr(host, port)
651
+
517
652
  router = APIRouter(prefix=cfg.basePath, tags=["Devchat"])
518
653
 
654
+ def _capture_host(request: Request) -> None:
655
+ """浏览器实际连接的 host:port = 宿主对外地址(仅首次记录)。"""
656
+ st.capture_host(request.headers.get("host", ""))
657
+
519
658
  # ---- 身份 ----
520
659
  async def _identity(request: Request):
521
660
  if cfg.identityFunc is not None:
@@ -547,6 +686,7 @@ def setup_devchat_handler(app: FastAPI, config: Optional[dict] = None) -> FastAP
547
686
  ident = await _identity(request)
548
687
  if ident is None:
549
688
  return JSONResponse({"detail": "未登录或无权访问 DevChat"}, status_code=401)
689
+ _capture_host(request)
550
690
  msgs = await st.store.recent(limit)
551
691
  return {
552
692
  "messages": [m.to_dict() for m in msgs],
@@ -698,6 +838,7 @@ def setup_devchat_handler(app: FastAPI, config: Optional[dict] = None) -> FastAP
698
838
  ident = await _identity(request)
699
839
  if ident is None:
700
840
  return JSONResponse({"detail": "未登录或无权访问 DevChat"}, status_code=401)
841
+ _capture_host(request)
701
842
  uid, _ = ident
702
843
  return {
703
844
  "running": st.running,
sycommon/devchat/store.py CHANGED
@@ -36,9 +36,10 @@ CREATE INDEX IF NOT EXISTS idx_devchat_messages_chan
36
36
 
37
37
 
38
38
  class SqliteMessageStore:
39
- """消息表存储(devchat_messages);复用任务库连接(同库同生命周期)。"""
39
+ """消息表存储(devchat_messages);共享连接(同库四存储共用,handler 注入)。"""
40
40
 
41
41
  def __init__(self, conn: sqlite3.Connection, channel: str, limit: int = 500):
42
+ # conn:共享连接(同库四存储共用;见 handler._open_shared_conn)。
42
43
  self._conn = conn
43
44
  self._channel = channel
44
45
  self._limit = limit if limit > 0 else 500
sycommon/devchat/tasks.py CHANGED
@@ -94,9 +94,14 @@ CREATE INDEX IF NOT EXISTS idx_devchat_sessions_active
94
94
  class SqliteTaskStore:
95
95
  """本地 SQLite 任务库。标准库驱动,单连接 + 锁(本地工具无高并发)。"""
96
96
 
97
- def __init__(self, path: str):
98
- Path(path).parent.mkdir(parents=True, exist_ok=True)
99
- self._conn = sqlite3.connect(path, check_same_thread=False)
97
+ def __init__(self, path: Optional[str] = None, conn: Optional[sqlite3.Connection] = None):
98
+ # conn=共享连接(推荐,同库四存储共用);path=独立开库(兼容旧签名)。
99
+ if conn is None:
100
+ if not path:
101
+ raise ValueError("path or conn required")
102
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
103
+ conn = sqlite3.connect(path, check_same_thread=False)
104
+ self._conn = conn
100
105
  self._conn.row_factory = sqlite3.Row
101
106
  self._mu = threading.Lock()
102
107
  with self._mu, self._conn:
@@ -152,6 +157,16 @@ class SqliteTaskStore:
152
157
  created_at=r["created_at"]))
153
158
  return out
154
159
 
160
+ def recover_stale(self) -> int:
161
+ """启动恢复:进程重启后,库里的 running 行是上次崩溃的残影(没有
162
+ 活着的协程在跑它)— 归为 error;随后排队任务可被正常接力。
163
+ 返回归为 error 的行数。幂等:无 running 行 = no-op。"""
164
+ with self._mu, self._conn:
165
+ cur = self._conn.execute(
166
+ "UPDATE devchat_tasks SET status=?, error=? WHERE status=?",
167
+ (TASK_ERROR, "服务重启,任务中断(启动恢复)", TASK_RUNNING))
168
+ return cur.rowcount or 0
169
+
155
170
  def oldest_queued(self) -> Optional[Task]:
156
171
  """seq 最小的 queued 任务(先来先做)。"""
157
172
  with self._mu:
@@ -182,6 +197,9 @@ class MemTaskStore:
182
197
  if len(self._items) > self._limit:
183
198
  self._items = self._items[-self._limit:]
184
199
 
200
+ def recover_stale(self) -> int:
201
+ return 0 # 内存态重启即失,无残影
202
+
185
203
  def update_status(self, task_id: str, status: str, error: str = "",
186
204
  started: Optional[float] = None,
187
205
  finished: Optional[float] = None) -> None:
@@ -227,9 +245,13 @@ def _task_from_json(raw: str) -> Optional[Task]:
227
245
  class SqliteEventStore:
228
246
  """任务事件归档:每次 claude 输出/工具调用/状态迁移一行,面板回放用。"""
229
247
 
230
- def __init__(self, path: str):
231
- Path(path).parent.mkdir(parents=True, exist_ok=True)
232
- self._conn = sqlite3.connect(path, check_same_thread=False)
248
+ def __init__(self, path: Optional[str] = None, conn: Optional[sqlite3.Connection] = None):
249
+ if conn is None:
250
+ if not path:
251
+ raise ValueError("path or conn required")
252
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
253
+ conn = sqlite3.connect(path, check_same_thread=False)
254
+ self._conn = conn
233
255
  self._conn.row_factory = sqlite3.Row
234
256
  self._mu = threading.Lock()
235
257
  with self._mu, self._conn:
@@ -260,9 +282,13 @@ class SqliteEventStore:
260
282
  class SqliteSessionArchive:
261
283
  """历史 claude 会话列表:每行一个 session_id,最近活跃在前。"""
262
284
 
263
- def __init__(self, path: str):
264
- Path(path).parent.mkdir(parents=True, exist_ok=True)
265
- self._conn = sqlite3.connect(path, check_same_thread=False)
285
+ def __init__(self, path: Optional[str] = None, conn: Optional[sqlite3.Connection] = None):
286
+ if conn is None:
287
+ if not path:
288
+ raise ValueError("path or conn required")
289
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
290
+ conn = sqlite3.connect(path, check_same_thread=False)
291
+ self._conn = conn
266
292
  self._conn.row_factory = sqlite3.Row
267
293
  self._mu = threading.Lock()
268
294
  with self._mu, self._conn:
@@ -293,4 +319,4 @@ class SqliteSessionArchive:
293
319
  " VALUES (?,?,?,?,1)"
294
320
  " ON CONFLICT(session_id) DO UPDATE SET"
295
321
  " last_active_at=excluded.last_active_at, task_count=task_count+1",
296
- (session_id, channel, now, now))
322
+ (session_id, channel, now, now))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sycommon-python-lib
3
- Version: 0.2.12a3
3
+ Version: 0.2.12a5
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -215,10 +215,11 @@ sycommon/database/resilient_pg_saver.py,sha256=S5hOoF7gGTa0b4-P3dM_iLy1GFesG_jEn
215
215
  sycommon/database/token_usage_db_service.py,sha256=iYK51ZtGNpBA4nj2IhflltbftE5Fsc3C0UksSJr-phY,10152
216
216
  sycommon/database/txnref.py,sha256=sOFp85PlanCA0oryVpHu53JbM0aSHAVkELWgEJKalLI,7755
217
217
  sycommon/devchat/__init__.py,sha256=Z2BgzDKrp_mR165d3a1kftP8lf1-WKz_5xuZMFXR-iw,2288
218
+ sycommon/devchat/_page.html,sha256=ArLQMgymJhj9J3z00Y9fwHOhlc5jukhbifBuLh6cDeU,26007
218
219
  sycommon/devchat/_page.py,sha256=JzTX7Wv_4-nJky7wg5E44yftSQYvC9L9_YsQzNnaWhI,406
219
- sycommon/devchat/handler.py,sha256=ix_nU_8vllmt2wHhEMMFRwwrwraWSAGZ6f3gK7NHiBg,31957
220
- sycommon/devchat/store.py,sha256=leNJunuCjS8t4dTrCxYooBO8EQl69dtAyV-2HHlJ_uM,3957
221
- sycommon/devchat/tasks.py,sha256=hh4Gv04bkI_-MP-OCfKG09NEZXuURz-i2iAARTeEdZI,11688
220
+ sycommon/devchat/handler.py,sha256=nlyBO-pVm5g_snxGZT_vAq0zAnGg1c6pzz94zHFmewY,38214
221
+ sycommon/devchat/store.py,sha256=iAxCJs5jrNbRDCVL4i0QnbEAUGLXtJumf8YsBGwfBe0,4047
222
+ sycommon/devchat/tasks.py,sha256=r4v-ZWibJzr4y3uQzGvVtDQ87R3Zfc-togCveLxa5l8,13030
222
223
  sycommon/health/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
223
224
  sycommon/health/health_check.py,sha256=EhfbhspRpQiKJaxdtE-PzpKQO_ucaFKtQxIm16F5Mpk,391
224
225
  sycommon/health/metrics.py,sha256=fHqO73JuhoZkNPR-xIlxieXiTCvttq-kG-tvxag1s1s,268
@@ -401,8 +402,8 @@ sycommon/tools/usercache.py,sha256=Zu2oiXISUOojleEYCAS9t06ZzgWSNHCIhCjv4yTtkRw,4
401
402
  sycommon/xxljob/__init__.py,sha256=7eoBlQxv-B39IfRSCY2bkqdGYs1QRe1umAWd88VMEEM,86
402
403
  sycommon/xxljob/sharding.py,sha256=LJ0tle7qSUS32S5ntjzri1aOcPzwL5CFde3W4Rf1AUE,2560
403
404
  sycommon/xxljob/xxljob_service.py,sha256=1yifwIBNGsCIxLnQjHKiBlbsigc_zvPH-dMTZcNxe-Q,7649
404
- sycommon_python_lib-0.2.12a3.dist-info/METADATA,sha256=rYJx3foOincQsDexTV4e2miEJ9dYwGVo7AwTLqs2ayA,8028
405
- sycommon_python_lib-0.2.12a3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
406
- sycommon_python_lib-0.2.12a3.dist-info/entry_points.txt,sha256=gsR4SssKxDWjRU8ggidzNcdMXDPRSKRS7UaGyNP84Qg,92
407
- sycommon_python_lib-0.2.12a3.dist-info/top_level.txt,sha256=RgphKrg7nJyZ7irJqbxFr-5H2LUYTvI7ivoWZH2hcD0,29
408
- sycommon_python_lib-0.2.12a3.dist-info/RECORD,,
405
+ sycommon_python_lib-0.2.12a5.dist-info/METADATA,sha256=r1u8Gyr23LnD18adv8eiXG4mHH5ODrCIbJ7-50CXcuQ,8028
406
+ sycommon_python_lib-0.2.12a5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
407
+ sycommon_python_lib-0.2.12a5.dist-info/entry_points.txt,sha256=gsR4SssKxDWjRU8ggidzNcdMXDPRSKRS7UaGyNP84Qg,92
408
+ sycommon_python_lib-0.2.12a5.dist-info/top_level.txt,sha256=RgphKrg7nJyZ7irJqbxFr-5H2LUYTvI7ivoWZH2hcD0,29
409
+ sycommon_python_lib-0.2.12a5.dist-info/RECORD,,