zcode-pro 1.8.2 → 1.10.0
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/README.en.md +1 -1
- package/README.md +1 -1
- package/dist/inject.js +3485 -144
- package/package.json +2 -2
- package/src/host/helper.mjs +762 -65
- package/src/host/taskIndex.mjs +123 -4
- package/src/inject/core.js +153 -21
- package/src/inject/features/auto-continue.js +574 -0
- package/src/inject/features/auto-rename.js +3 -3
- package/src/inject/features/idle-reclaim.js +31 -5
- package/src/inject/features/newtab-panels.js +10 -4
- package/src/inject/features/session-switch.js +170 -11
- package/src/inject/features/settings-dialog.js +123 -37
- package/src/inject/features/status-bar.js +25 -20
- package/src/inject/features/subagent-icon.js +114 -18
- package/src/inject/features/title-gen.js +3 -3
- package/src/inject/features/title-lock.js +2 -2
- package/src/inject/features/turn-usage.js +49 -15
- package/src/inject/index.js +2 -0
- package/src/inject/locales/ja.js +772 -0
- package/src/inject/locales/ko.js +772 -0
- package/src/inject/locales/ru.js +772 -0
|
@@ -0,0 +1,574 @@
|
|
|
1
|
+
// 回合失败自动继续:回合因请求故障直接死亡(turn.failed)时,ZCode 会话流末尾渲染
|
|
2
|
+
// chat-error-banner 错误横幅("An error occurred ... Please try again." /
|
|
3
|
+
// "Turn execution failed")。这条失败路径不触发钩子(Stop 只在正常回合结束时跑),
|
|
4
|
+
// 由本特性补上:发现会话流收尾处的失败横幅就往输入框写入继续指令并发送,让任务
|
|
5
|
+
// 接着跑——正在跑的失败当场接上,重开会话(含重启 ZCode 后)留着尾巴的任务也接上;
|
|
6
|
+
// 认证、余额、模型不存在等永久性错误和用户手动停止(cancelled)不打扰。截断的回复
|
|
7
|
+
// 也会接着写。开关与文案走 ~/.zcode/auto-continue.json。
|
|
8
|
+
import { rpc, uiLocale, t, errText } from '../core.js';
|
|
9
|
+
|
|
10
|
+
const SCAN_MS = 2000;
|
|
11
|
+
const BANNER_SEL = '[data-testid="chat-error-banner"]';
|
|
12
|
+
const STOP_SEL = '[data-testid="v4-stop"]';
|
|
13
|
+
const INPUT_SEL = '[data-testid="v4-composer-input"]';
|
|
14
|
+
const SEND_SEL = '[data-testid="v4-composer-send"]';
|
|
15
|
+
|
|
16
|
+
// 默认提示词按 ZCode 的界面语言取值(官方支持 zh-CN / en-US / ja-JP / ko-KR / ru-RU),
|
|
17
|
+
// 与设置页显示的默认值一致;界面文案同样跟随这五种语言
|
|
18
|
+
const CONTINUE_TEXT_BY_LOCALE = {
|
|
19
|
+
'zh-CN': '继续',
|
|
20
|
+
'en-US': 'continue',
|
|
21
|
+
'ja-JP': '続けて',
|
|
22
|
+
'ko-KR': '계속',
|
|
23
|
+
'ru-RU': 'Продолжай',
|
|
24
|
+
};
|
|
25
|
+
export function defaultContinueText() {
|
|
26
|
+
return CONTINUE_TEXT_BY_LOCALE[uiLocale()] || CONTINUE_TEXT_BY_LOCALE['en-US'];
|
|
27
|
+
}
|
|
28
|
+
const TRUNCATION_CONTINUE_TEXT_BY_LOCALE = {
|
|
29
|
+
'zh-CN': '上一条回复疑似在输出中途被截断。请接着已生成的内容继续输出,从中断处往下写,不要重复任何已经生成的内容。',
|
|
30
|
+
'en-US': 'The previous reply appears to have been cut off. Continue from where it stopped, without repeating anything already generated.',
|
|
31
|
+
'ja-JP': '前回の回答は出力の途中で途切れた可能性があります。生成済みの内容の続きから、中断した箇所を書き進めてください。すでに出力した内容は繰り返さないでください。',
|
|
32
|
+
'ko-KR': '이전 답변이 출력 도중에 잘린 것 같습니다. 이미 생성된 내용에 이어서 중단된 지점부터 계속 작성해 주세요. 이미 생성된 내용은 반복하지 마세요.',
|
|
33
|
+
'ru-RU': 'Похоже, предыдущий ответ был обрезан на середине. Продолжите с того места, где он остановился, не повторяя уже сгенерированный текст.',
|
|
34
|
+
};
|
|
35
|
+
function defaultTruncationText() {
|
|
36
|
+
return TRUNCATION_CONTINUE_TEXT_BY_LOCALE[uiLocale()] || TRUNCATION_CONTINUE_TEXT_BY_LOCALE['en-US'];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// 没有保存过提示词时才用当前语言的默认值;已保存的值(包括旧语言的内置默认)保持不变。
|
|
40
|
+
// 用户想换成当前语言的默认值,去设置页点“使用默认提示词”重新取。
|
|
41
|
+
const truncationTextFor = (value) => {
|
|
42
|
+
const text = String(value || '').trim();
|
|
43
|
+
return text || defaultTruncationText();
|
|
44
|
+
};
|
|
45
|
+
const continueTextFor = (value) => {
|
|
46
|
+
const text = String(value || '').trim();
|
|
47
|
+
return text || defaultContinueText();
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const DEFAULTS = {
|
|
51
|
+
enabled: true,
|
|
52
|
+
continueText: '',
|
|
53
|
+
maxRetries: 8,
|
|
54
|
+
cooldownBaseSec: 10,
|
|
55
|
+
cooldownFactor: 2,
|
|
56
|
+
cooldownMaxSec: 60,
|
|
57
|
+
stuckAfterMin: 30,
|
|
58
|
+
failedAfterMin: 3,
|
|
59
|
+
truncationContinueText: '',
|
|
60
|
+
// 永久性错误关键词(正则,命中不自动继续),与插件引擎同一份配置可覆盖
|
|
61
|
+
permanentPatterns: [
|
|
62
|
+
'\\b40[123]\\b',
|
|
63
|
+
'unauthorized', 'forbidden', 'authentication', 'invalid[_ -]?api[_ -]?key', 'api[_ -]?key',
|
|
64
|
+
'credential', '鉴权', '认证失败', '凭证', '无效的密钥',
|
|
65
|
+
'insufficient (balance|funds|quota)', '余额不足', '欠费',
|
|
66
|
+
'billing', 'payment required', 'quota exceeded', '配额(不足|已用|用尽)', '免费额度',
|
|
67
|
+
'使用上限', '每周.{0,4}上限', '每月.{0,4}上限', 'usage limit', 'rate limit reached',
|
|
68
|
+
'model not found', 'unknown model', 'no such model', 'no model available', 'current model is unavailable',
|
|
69
|
+
'模型不存在', '无可用模型', '当前模型不可用',
|
|
70
|
+
'access denied', 'permission denied',
|
|
71
|
+
'context[_ -]length', 'prompt (is )?too long', '上下文(超|过|长度)', '输入过长', 'token limit',
|
|
72
|
+
'exceeded the provider context window',
|
|
73
|
+
'param incorrect', 'invalid[_ -]?request', 'invalid[_ -]?parameter', '参数(错误|不正确|无效)',
|
|
74
|
+
// 官方会把已知错误本地化后再显示;补上日/韩/俄的同类措辞,避免一直续接永久失败
|
|
75
|
+
'認証(に失敗|エラー|が必要)', 'ログイン.*(期限|失効|必要)', 'サインイン.*(期限|失効|必要)',
|
|
76
|
+
'クォータ.*(使い切|超過|不足|上限)', '残高.*不足',
|
|
77
|
+
'モデル.*(見つかりません|利用できません|利用できなく|ありません|含まれていません)', 'コンテキスト.*(長|超過|上限)',
|
|
78
|
+
'인증.*(실패|오류|필요)', '로그인.*(만료|필요)',
|
|
79
|
+
'할당량.*(초과|부족|모두 사용|한도)', '잔액.*부족',
|
|
80
|
+
'모델.*(찾을 수 없|사용할 수 없|없습니다|포함되어 있지 않)', '컨텍스트.*(길|초과|한도)',
|
|
81
|
+
'аутентификац.*(ошиб|неудач|требуется)', 'сеанс.*(истёк|истек)', 'войд.*снова',
|
|
82
|
+
'квот.*(израсходован|превышен|недостаточно)', 'баланс.*недостаточно',
|
|
83
|
+
'модель.*(не найдена|недоступна|не входит)', 'нет доступной модели', 'контекст.*(длин|превыш)',
|
|
84
|
+
],
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
let cachedCfg = null;
|
|
88
|
+
let cachedAt = 0;
|
|
89
|
+
|
|
90
|
+
async function getConfig() {
|
|
91
|
+
const now = Date.now();
|
|
92
|
+
if (cachedCfg && now - cachedAt < 30000) return cachedCfg;
|
|
93
|
+
const res = await rpc('/auto-continue');
|
|
94
|
+
const raw = res.ok && res.config && typeof res.config === 'object' ? res.config : {};
|
|
95
|
+
cachedCfg = { ...DEFAULTS, ...raw };
|
|
96
|
+
cachedAt = now;
|
|
97
|
+
return cachedCfg;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function compile(patterns) {
|
|
101
|
+
return (Array.isArray(patterns) ? patterns : [])
|
|
102
|
+
.map((src) => { try { return new RegExp(src, 'i'); } catch { return null; } })
|
|
103
|
+
.filter(Boolean);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function isPermanent(text, cfg) {
|
|
107
|
+
return compile(cfg.permanentPatterns).some((re) => re.test(text));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// 用户手动停止 / 系统取消的失败横幅(如 “Model request was cancelled.”)不自动继续
|
|
111
|
+
function isCancelled(text) {
|
|
112
|
+
return /\bcancel+ed?\b|已取消|已停止|手动停止|キャンセル|中止|취소|중지|отмен|остановлен/i.test(text);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 官方横幅带 data-error-code(如 providerBusiness.1005);这些码是重试也不会好的
|
|
116
|
+
const PERMANENT_CODES = [
|
|
117
|
+
'model_config_missing',
|
|
118
|
+
'ZCODE_RUNTIME_MODEL_UNAVAILABLE',
|
|
119
|
+
'ZCODE_BIGMODEL_TEAM_PLAN_MEMBER_REQUIRED',
|
|
120
|
+
];
|
|
121
|
+
function isPermanentCode(code) {
|
|
122
|
+
const s = String(code || '').trim();
|
|
123
|
+
if (PERMANENT_CODES.some((n) => s === n || s.endsWith('.' + n) || s.endsWith(':' + n))) return true;
|
|
124
|
+
return /(?:^|[.\-_/:])(?:401|402|403|429|1005|1006|3001|3006)$/.test(s);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 会话流收尾处的失败横幅:横幅所在的行是最后一行(任务死在收尾上)才算数;
|
|
128
|
+
// 排在中间的历史横幅(用户已在后面说过话)不动
|
|
129
|
+
function trailingBanner() {
|
|
130
|
+
const banners = [...document.querySelectorAll(`${BANNER_SEL}:not([data-zcodepro-ac])`)];
|
|
131
|
+
if (!banners.length) return null;
|
|
132
|
+
const rows = [...document.querySelectorAll('[data-testid^="v4-row-"]')];
|
|
133
|
+
const lastRow = rows.length ? rows[rows.length - 1] : null;
|
|
134
|
+
for (const b of banners) {
|
|
135
|
+
const row = b.closest('[data-testid^="v4-row-"]');
|
|
136
|
+
if (!row || !lastRow || row === lastRow) return b;
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// 自动继续时间戳(页面存活期内):30 分钟窗口计总数(防故障反复时无限继续),
|
|
142
|
+
// 2 分钟窗口计密集程度(只对密集失败退避,单次失败不等待)
|
|
143
|
+
let continueTimes = [];
|
|
144
|
+
function pruneTimes() {
|
|
145
|
+
const cutoff = Date.now() - 30 * 60 * 1000;
|
|
146
|
+
continueTimes = continueTimes.filter((t) => t >= cutoff);
|
|
147
|
+
}
|
|
148
|
+
function recentWithin(ms) {
|
|
149
|
+
const cutoff = Date.now() - ms;
|
|
150
|
+
return continueTimes.filter((t) => t >= cutoff).length;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function sleep(ms) {
|
|
154
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// 往 Lexical 输入框写入文本:execCommand 走原生输入路径,Lexical 会把文本纳入
|
|
158
|
+
// 自己的模型。注意 Windows 的 Chromium 上 execCommand 返回 true 但提交是异步的
|
|
159
|
+
//(实测立即读长度为 0,约 300ms 后才出现)——判定必须轮询等待,同步读会误判
|
|
160
|
+
// “没写进去”而追加事件派发,造成双份文本。写入前先全选清空,保证内容恰好一份;
|
|
161
|
+
// 事件派发只作为 execCommand 确认无产出后的兜底。
|
|
162
|
+
async function fillComposer(text) {
|
|
163
|
+
const input = document.querySelector(INPUT_SEL);
|
|
164
|
+
if (!input) return false;
|
|
165
|
+
input.focus();
|
|
166
|
+
// 全选清空(选区套在输入框上,Lexical 顺着删除事件走自己的模型)
|
|
167
|
+
const range = document.createRange();
|
|
168
|
+
range.selectNodeContents(input);
|
|
169
|
+
const sel = getSelection();
|
|
170
|
+
sel.removeAllRanges();
|
|
171
|
+
sel.addRange(range);
|
|
172
|
+
try { document.execCommand('delete'); } catch { /* 下一步全选插入会整体替换 */ }
|
|
173
|
+
for (let i = 0; i < 10 && (input.textContent || '').length > 0; i += 1) await sleep(50);
|
|
174
|
+
try { document.execCommand('insertText', false, text); } catch { /* 走兜底 */ }
|
|
175
|
+
// 等异步提交(Windows 上约 300ms)
|
|
176
|
+
for (let i = 0; i < 12; i += 1) {
|
|
177
|
+
const cur = input.textContent || '';
|
|
178
|
+
if (cur.includes(text)) return true; // 恰好一份(清空后插入,不会更多)
|
|
179
|
+
await sleep(50);
|
|
180
|
+
}
|
|
181
|
+
// 兜底:派发 beforeinput/input(Lexical 处理 beforeinput)
|
|
182
|
+
input.dispatchEvent(new InputEvent('beforeinput', { bubbles: true, cancelable: true, inputType: 'insertText', data: text }));
|
|
183
|
+
input.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: text }));
|
|
184
|
+
for (let i = 0; i < 10; i += 1) {
|
|
185
|
+
if ((input.textContent || '').includes(text)) return true;
|
|
186
|
+
await sleep(50);
|
|
187
|
+
}
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// 发送按钮的可用状态由界面在文本写入后异步渲染(写完立刻查会读到旧的禁用状态),
|
|
192
|
+
// 轮询等它启用再点;每轮重新查按钮(元素可能被重建);慢机器上按钮渲染可达数秒,等足 6 秒
|
|
193
|
+
async function clickSend() {
|
|
194
|
+
for (let i = 0; i < 15; i += 1) {
|
|
195
|
+
const send = document.querySelector(SEND_SEL);
|
|
196
|
+
if (send && !send.disabled) {
|
|
197
|
+
send.click();
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
await sleep(400);
|
|
201
|
+
}
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// 单次失败不等待(任务等着接上,只留 3 秒界面稳定时间);2 分钟内已继续过
|
|
206
|
+
// 则视为密集失败,按 2 倍递增退避
|
|
207
|
+
function delayFor(dense, cfg) {
|
|
208
|
+
if (dense <= 1) return 3000;
|
|
209
|
+
const secs = Math.min(cfg.cooldownBaseSec * Math.pow(cfg.cooldownFactor || 2, dense - 2), cfg.cooldownMaxSec);
|
|
210
|
+
return Math.round(secs * 1000);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// 回合正常结束但收尾内容坏了(原插件 Stop 钩子角色的 DOM 版):最后一行是长回复且
|
|
214
|
+
// 代码围栏未闭合或以省略号收尾,多半是输出中途被掐断。只看可见会话最后一行,
|
|
215
|
+
// 阈值沿用插件引擎(长度 300、围栏奇偶);空回复不在 DOM 判(伪空行太多,误报高)。
|
|
216
|
+
function brokenTail() {
|
|
217
|
+
const rows = [...document.querySelectorAll('[data-testid^="v4-row-"]')];
|
|
218
|
+
if (!rows.length) return null;
|
|
219
|
+
const last = rows[rows.length - 1];
|
|
220
|
+
if (!last.className.includes('assistant') || last.dataset.zcodeproAc) return null;
|
|
221
|
+
const text = (last.innerText || '').trim();
|
|
222
|
+
if (text.length < 300) return null;
|
|
223
|
+
const fences = (text.match(/```/g) || []).length;
|
|
224
|
+
if (fences % 2 === 1) return { el: last, kind: 'truncation' };
|
|
225
|
+
if (/(\.\.\.|…)\s*$/.test(text)) return { el: last, kind: 'truncation' };
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
let inflight = false;
|
|
230
|
+
|
|
231
|
+
async function tick() {
|
|
232
|
+
if (inflight || document.querySelector(STOP_SEL) || Date.now() < rescueUntil) return;
|
|
233
|
+
const banner = trailingBanner();
|
|
234
|
+
const target = banner ? { el: banner, kind: 'banner' } : brokenTail();
|
|
235
|
+
if (!target) return;
|
|
236
|
+
const el = target.el;
|
|
237
|
+
inflight = true;
|
|
238
|
+
try {
|
|
239
|
+
const cfg = await getConfig();
|
|
240
|
+
if (cfg.enabled === false) return;
|
|
241
|
+
|
|
242
|
+
if (target.kind === 'banner') {
|
|
243
|
+
const text = (banner.innerText || '');
|
|
244
|
+
const code = banner.getAttribute('data-error-code') || '';
|
|
245
|
+
if (isPermanent(text, cfg) || isPermanentCode(code) || isCancelled(text)) {
|
|
246
|
+
el.dataset.zcodeproAc = 'skip';
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
// 有人重新发起回合、或用户已在输入框起草:不打扰
|
|
251
|
+
if (document.querySelector(STOP_SEL)) return;
|
|
252
|
+
const input = document.querySelector(INPUT_SEL);
|
|
253
|
+
if (!input || (input.textContent || '').trim()) return;
|
|
254
|
+
|
|
255
|
+
pruneTimes();
|
|
256
|
+
if (continueTimes.length >= (cfg.maxRetries || DEFAULTS.maxRetries)) {
|
|
257
|
+
el.dataset.zcodeproAc = 'cap';
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
el.dataset.zcodeproAc = 'pending';
|
|
261
|
+
await sleep(delayFor(recentWithin(2 * 60 * 1000), cfg));
|
|
262
|
+
// 等待期间状态可能变化(用户手动继续、切走会话、目标行消失),重新校验后再发
|
|
263
|
+
if (!el.isConnected || document.querySelector(STOP_SEL)) {
|
|
264
|
+
el.dataset.zcodeproAc = 'skip';
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const input2 = document.querySelector(INPUT_SEL);
|
|
268
|
+
const want = target.kind === 'truncation'
|
|
269
|
+
? truncationTextFor(cfg.truncationContinueText)
|
|
270
|
+
: (continueTextFor(cfg.continueText));
|
|
271
|
+
const current = ((input2 && input2.textContent) || '').trim();
|
|
272
|
+
// 输入框有内容:是上次没发出去的继续提示词就只重试发送(不重复插入,
|
|
273
|
+
// 同一目标重渲染再次触发也走到这里);是用户起草的内容就不打扰
|
|
274
|
+
if (current && !current.includes(want.slice(0, 10))) {
|
|
275
|
+
el.dataset.zcodeproAc = 'skip';
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (!current && !(await fillComposer(want))) {
|
|
279
|
+
el.dataset.zcodeproAc = 'fail';
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (!(await clickSend())) {
|
|
283
|
+
el.dataset.zcodeproAc = 'fail';
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
el.dataset.zcodeproAc = '1';
|
|
287
|
+
continueTimes.push(Date.now());
|
|
288
|
+
} finally {
|
|
289
|
+
inflight = false;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// —— 卡死看门狗 ——
|
|
294
|
+
// 回合卡死(工具执行器悬死)没有任何失败横幅,上面的横幅路径覆盖不到。这类卡死在
|
|
295
|
+
// ZCode 运行日志里的形态:background_task.tracking.started 之后永远等不到
|
|
296
|
+
// background_task.tracking.terminal(实测案例:TaskOutput 等一个早已死掉的后台
|
|
297
|
+
// 构建任务,悬了 1 小时)。定期向宿主要悬空任务清单,超阈值入队提示,一张卡
|
|
298
|
+
// 处理完再弹下一张。只提示不动自动手:长时间后台构建(如打包)与卡死同形态。
|
|
299
|
+
const STUCK_POLL_MS = 60 * 1000;
|
|
300
|
+
const stuckShown = new Set();
|
|
301
|
+
const failedShown = new Set();
|
|
302
|
+
const rescueTimes = new Map(); // sessionId -> 无头救援时间戳(30 分钟窗口内限 3 次)
|
|
303
|
+
const stuckQueue = [];
|
|
304
|
+
let stuckCardEl = null;
|
|
305
|
+
// 救援进行中Until:期间横幅规则暂停,避免它和救援动作同时往输入框写“继续”
|
|
306
|
+
let rescueUntil = 0;
|
|
307
|
+
|
|
308
|
+
// 把卡死的任务续上(无头):能切到目标会话就先停掉它悬着的回合,再走宿主的
|
|
309
|
+
// 无头续接(--resume -p)——全程不碰输入框,不会和别的续接动作叠“继续”。
|
|
310
|
+
async function rescueStuck(task) {
|
|
311
|
+
rescueUntil = Date.now() + 30000;
|
|
312
|
+
const switched = switchToTask(task.sessionId);
|
|
313
|
+
if (switched) {
|
|
314
|
+
await sleep(800);
|
|
315
|
+
const stop = document.querySelector(STOP_SEL);
|
|
316
|
+
if (stop) {
|
|
317
|
+
stop.click();
|
|
318
|
+
await sleep(3000);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const cfg = await getConfig();
|
|
322
|
+
const r = await rpc('/ac-continue', { method: 'POST', body: { sessionId: task.sessionId, text: continueTextFor(cfg.continueText) } });
|
|
323
|
+
if (!r.ok) rescueUntil = 0;
|
|
324
|
+
return r.ok;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// 切到任务所在的会话:侧栏行直接点;虚拟列表没渲染出该行时返回 false(留在当前视图)
|
|
328
|
+
function switchToTask(sessionId) {
|
|
329
|
+
const row = document.querySelector(`[data-testid="task-item-${sessionId}"]`);
|
|
330
|
+
if (!row) return false;
|
|
331
|
+
row.click();
|
|
332
|
+
return true;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// 任务的人类可读名字:侧栏行文本(标题 + 相对时间);行没渲染时退回会话号
|
|
336
|
+
function taskTitle(sessionId) {
|
|
337
|
+
const row = document.querySelector(`[data-testid="task-item-${sessionId}"]`);
|
|
338
|
+
const text = row ? (row.textContent || '').trim() : '';
|
|
339
|
+
return text ? text.split('\n')[0].slice(0, 30) : String(sessionId).slice(0, 20) + '…';
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function dequeueStuck(task) {
|
|
343
|
+
const i = stuckQueue.indexOf(task);
|
|
344
|
+
if (i >= 0) stuckQueue.splice(i, 1);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// 队列条目按会话合并;任务数据变了就更新,全部任务都已终结(或会话恢复活跃)
|
|
348
|
+
// 的条目直接丢弃。返回是否丢掉了正在显示的那一条。
|
|
349
|
+
function pruneStuckQueue(scan, threshold) {
|
|
350
|
+
const alive = new Map(); // sessionId -> 仍满足阈值的任务
|
|
351
|
+
for (const t of (Array.isArray(scan?.tasks) ? scan.tasks : [])) {
|
|
352
|
+
if (t.ageSec < threshold || (t.silenceSec ?? 0) < threshold) continue;
|
|
353
|
+
const arr = alive.get(t.sessionId) || [];
|
|
354
|
+
arr.push(t);
|
|
355
|
+
alive.set(t.sessionId, arr);
|
|
356
|
+
}
|
|
357
|
+
const failedAlive = new Set((Array.isArray(scan?.failed) ? scan.failed : []).map((f) => `${f.sessionId}:${f.failedAt}`));
|
|
358
|
+
let removedCurrent = false;
|
|
359
|
+
for (let i = stuckQueue.length - 1; i >= 0; i -= 1) {
|
|
360
|
+
const q = stuckQueue[i];
|
|
361
|
+
let keep = false;
|
|
362
|
+
if (q.failedMsg) {
|
|
363
|
+
keep = failedAlive.has(`${q.sessionId}:${q.failedAt}`);
|
|
364
|
+
} else {
|
|
365
|
+
const remain = (alive.get(q.sessionId) || []).filter((t) => q.taskIds.includes(t.taskId));
|
|
366
|
+
if (remain.length) {
|
|
367
|
+
q.tasks = remain;
|
|
368
|
+
q.kinds = [...new Set(remain.map((t) => t.kind || 'terminal'))];
|
|
369
|
+
q.ageSec = Math.max(...remain.map((t) => t.ageSec));
|
|
370
|
+
keep = true;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (!keep) {
|
|
374
|
+
if (i === 0 && stuckCardEl) removedCurrent = true;
|
|
375
|
+
stuckQueue.splice(i, 1);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return removedCurrent;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function closeStuckCard() {
|
|
382
|
+
if (stuckCardEl) { stuckCardEl.remove(); stuckCardEl = null; }
|
|
383
|
+
if (!stuckQueue.length) return;
|
|
384
|
+
// 队列是扫描快照:弹下一张前重新拉一次,任务已经结束的卡不再弹出来
|
|
385
|
+
setTimeout(() => {
|
|
386
|
+
void (async () => {
|
|
387
|
+
try {
|
|
388
|
+
const res = await rpc('/ac-stuck');
|
|
389
|
+
const cfg = await getConfig();
|
|
390
|
+
if (res.ok) pruneStuckQueue(res, (cfg.stuckAfterMin || DEFAULTS.stuckAfterMin) * 60);
|
|
391
|
+
} catch { /* 复核失败就按现有队列继续弹 */ }
|
|
392
|
+
showNextStuckCard();
|
|
393
|
+
})();
|
|
394
|
+
}, 500);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function kindLabel(kind) {
|
|
398
|
+
const L = t();
|
|
399
|
+
if (kind === 'subagent') return L.acCardKindSubagent;
|
|
400
|
+
if (kind === 'turn') return L.acCardKindTurn;
|
|
401
|
+
return L.acCardKindTerminal;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function stuckDesc(task, mins) {
|
|
405
|
+
const L = t();
|
|
406
|
+
const title = taskTitle(task.sessionId);
|
|
407
|
+
const count = task.tasks ? task.tasks.length : 1;
|
|
408
|
+
const parts = [];
|
|
409
|
+
if (task.kinds.includes('terminal')) {
|
|
410
|
+
parts.push(L.acCardTerminalSilent.replaceAll('{count}', String(count)).replaceAll('{mins}', String(mins)));
|
|
411
|
+
}
|
|
412
|
+
if (task.kinds.includes('subagent')) {
|
|
413
|
+
parts.push(L.acCardSubagentSilent.replaceAll('{count}', String(count)).replaceAll('{mins}', String(mins)));
|
|
414
|
+
}
|
|
415
|
+
if (task.kinds.includes('turn')) {
|
|
416
|
+
parts.push(L.acCardTurnStalled.replaceAll('{mins}', String(mins)));
|
|
417
|
+
}
|
|
418
|
+
return L.acCardStuckDesc.replaceAll('{title}', title).replaceAll('{parts}', parts.join(L.acCardPartSep));
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function showNextStuckCard() {
|
|
422
|
+
// 卡片可能被界面整体重建时从 DOM 移走而引用还在(实测会卡死队列):引用失效就当作没卡
|
|
423
|
+
if (stuckCardEl) {
|
|
424
|
+
if (stuckCardEl.isConnected) return;
|
|
425
|
+
stuckCardEl = null;
|
|
426
|
+
}
|
|
427
|
+
if (!stuckQueue.length) return;
|
|
428
|
+
const task = stuckQueue[0];
|
|
429
|
+
const L = t();
|
|
430
|
+
const mins = Math.round(task.ageSec / 60);
|
|
431
|
+
const kinds = task.kinds && task.kinds.length ? task.kinds : ['terminal'];
|
|
432
|
+
const more = stuckQueue.length > 1;
|
|
433
|
+
const card = document.createElement('div');
|
|
434
|
+
card.style.cssText = 'position:fixed;right:16px;bottom:16px;z-index:2147483000;max-width:360px;padding:12px;border-radius:12px;border:1px solid var(--color-border, #666);background:var(--color-surface, #222);color:var(--color-foreground, #eee);font-size:13px;line-height:1.5;box-shadow:0 4px 24px rgba(0,0,0,.4)';
|
|
435
|
+
const title = document.createElement('div');
|
|
436
|
+
title.style.cssText = 'font-weight:600;margin-bottom:4px';
|
|
437
|
+
title.textContent = (task.failedMsg
|
|
438
|
+
? L.acCardFailedTitle
|
|
439
|
+
: kinds.map((k) => kindLabel(k)).join(L.acCardKindSep))
|
|
440
|
+
+ (more ? L.acCardMore.replaceAll('{n}', String(stuckQueue.length - 1)) : '');
|
|
441
|
+
const desc = document.createElement('div');
|
|
442
|
+
desc.style.cssText = 'opacity:.85';
|
|
443
|
+
desc.textContent = task.failedMsg
|
|
444
|
+
? L.acCardFailedDesc
|
|
445
|
+
.replaceAll('{title}', taskTitle(task.sessionId))
|
|
446
|
+
.replaceAll('{mins}', String(mins))
|
|
447
|
+
.replaceAll('{msg}', String(task.failedMsg).slice(0, 60))
|
|
448
|
+
: stuckDesc(task, mins);
|
|
449
|
+
const row = document.createElement('div');
|
|
450
|
+
row.style.cssText = 'display:flex;gap:8px;margin-top:10px';
|
|
451
|
+
const mkBtn = (label, primary) => {
|
|
452
|
+
const b = document.createElement('button');
|
|
453
|
+
b.type = 'button';
|
|
454
|
+
b.textContent = label;
|
|
455
|
+
b.style.cssText = primary
|
|
456
|
+
? 'cursor:pointer;border:none;border-radius:8px;padding:5px 12px;background:var(--color-brand, #4a7cf7);color:#fff;font-size:12px'
|
|
457
|
+
: 'cursor:pointer;border-radius:8px;padding:5px 12px;background:transparent;border:1px solid var(--color-border, #666);color:inherit;font-size:12px';
|
|
458
|
+
return b;
|
|
459
|
+
};
|
|
460
|
+
const jump = mkBtn(L.acCardJump, false);
|
|
461
|
+
jump.addEventListener('click', () => {
|
|
462
|
+
switchToTask(task.sessionId);
|
|
463
|
+
// 卡片留着:看完任务再决定“继续”还是“知道了”
|
|
464
|
+
});
|
|
465
|
+
const fix = mkBtn(L.acCardContinue, true);
|
|
466
|
+
fix.addEventListener('click', () => {
|
|
467
|
+
fix.disabled = true;
|
|
468
|
+
if (task.failedMsg) {
|
|
469
|
+
// 失败会话:走无头续接,不切界面
|
|
470
|
+
void (async () => {
|
|
471
|
+
const cfg = await getConfig();
|
|
472
|
+
const r = await rpc('/ac-continue', { method: 'POST', body: { sessionId: task.sessionId, text: continueTextFor(cfg.continueText) } });
|
|
473
|
+
if (r.ok) {
|
|
474
|
+
dequeueStuck(task);
|
|
475
|
+
closeStuckCard();
|
|
476
|
+
} else {
|
|
477
|
+
fix.disabled = false;
|
|
478
|
+
desc.textContent = L.acCardContinueStartFailed + (errText(r) || 'unknown');
|
|
479
|
+
}
|
|
480
|
+
})();
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
void (async () => {
|
|
484
|
+
const ok = await rescueStuck(task);
|
|
485
|
+
if (ok) {
|
|
486
|
+
dequeueStuck(task);
|
|
487
|
+
closeStuckCard();
|
|
488
|
+
} else {
|
|
489
|
+
fix.disabled = false;
|
|
490
|
+
desc.textContent = L.acCardHeadlessFailed;
|
|
491
|
+
}
|
|
492
|
+
})();
|
|
493
|
+
});
|
|
494
|
+
const dismiss = mkBtn(L.acCardDismiss, false);
|
|
495
|
+
dismiss.addEventListener('click', () => {
|
|
496
|
+
dequeueStuck(task);
|
|
497
|
+
closeStuckCard();
|
|
498
|
+
});
|
|
499
|
+
row.append(jump, fix, dismiss);
|
|
500
|
+
card.append(title, desc, row);
|
|
501
|
+
(document.body || document.documentElement).append(card);
|
|
502
|
+
stuckCardEl = card;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
async function stuckTick() {
|
|
506
|
+
const res = await rpc('/ac-stuck');
|
|
507
|
+
// 调试钩子(临时):记录每轮扫描的决策,排查无头续接不触发的问题
|
|
508
|
+
const dbg = (m) => { const a = (window.__acDebug ||= []); a.push(`${new Date().toISOString().slice(11, 19)} ${m}`); if (a.length > 50) a.splice(0, a.length - 50); };
|
|
509
|
+
dbg(`scan ok=${res.ok} tasks=${Array.isArray(res.tasks) ? res.tasks.length : 'x'} failed=${Array.isArray(res.failed) ? res.failed.length : 'x'}`);
|
|
510
|
+
if (!res.ok || !Array.isArray(res.tasks)) return;
|
|
511
|
+
const cfg = await getConfig();
|
|
512
|
+
if (cfg.enabled === false) return;
|
|
513
|
+
const threshold = (cfg.stuckAfterMin || DEFAULTS.stuckAfterMin) * 60;
|
|
514
|
+
for (const task of res.tasks) {
|
|
515
|
+
// 任务悬空够久、且会话也确实没动静才算卡死(会话在动 = 已救活/在跑,过滤诈尸)
|
|
516
|
+
dbg(`task tid=${String(task.taskId).slice(0, 16)} kind=${task.kind} age=${task.ageSec} sil=${task.silenceSec} thr=${threshold} shown=${stuckShown.has(task.taskId)}`);
|
|
517
|
+
if (task.ageSec < threshold || (task.silenceSec ?? 0) < threshold || stuckShown.has(task.taskId)) continue;
|
|
518
|
+
stuckShown.add(task.taskId);
|
|
519
|
+
const kind = task.kind || 'terminal';
|
|
520
|
+
// 同一会话的任务合并进一张卡:一个会话只需要用户做一个决定
|
|
521
|
+
let entry = stuckQueue.find((q) => !q.failedMsg && q.sessionId === task.sessionId);
|
|
522
|
+
if (!entry) {
|
|
523
|
+
entry = { sessionId: task.sessionId, taskIds: [], tasks: [], kinds: [], ageSec: 0 };
|
|
524
|
+
stuckQueue.push(entry);
|
|
525
|
+
}
|
|
526
|
+
entry.taskIds.push(task.taskId);
|
|
527
|
+
entry.tasks.push(task);
|
|
528
|
+
if (!entry.kinds.includes(kind)) entry.kinds.push(kind);
|
|
529
|
+
entry.ageSec = Math.max(entry.ageSec, task.ageSec);
|
|
530
|
+
}
|
|
531
|
+
// 失败会话:失败后没人续、静默超过阈值就接手——走宿主的无头续接(--resume -p),
|
|
532
|
+
// 不碰桌面界面,手机端/后台等视图外会话同样适用。子代理会话由父会话自己善后,不碰。
|
|
533
|
+
// 单会话救援限额:永久失败的会话每次失败都会产生新时间戳、绕开“同一次失败只救一次”,
|
|
534
|
+
// 不限额会每轮扫描拉起一次、无限循环;超过限额改为弹卡交还用户。
|
|
535
|
+
const failedThreshold = ((cfg.failedAfterMin ?? DEFAULTS.failedAfterMin)) * 60;
|
|
536
|
+
for (const f of (Array.isArray(res.failed) ? res.failed : [])) {
|
|
537
|
+
const key = `${f.sessionId}:${f.failedAt}`;
|
|
538
|
+
dbg(`entry sid=${String(f.sessionId).slice(0, 20)} age=${f.ageSec} thr=${failedThreshold} shown=${failedShown.has(key)} perm=${isPermanent(f.message || '', cfg)} canc=${isCancelled(f.message || '')}`);
|
|
539
|
+
if (f.ageSec < failedThreshold || failedShown.has(key)) continue;
|
|
540
|
+
if (isPermanent(f.message || '', cfg) || isCancelled(f.message || '')) continue;
|
|
541
|
+
if (String(f.sessionId).includes('subagent')) continue;
|
|
542
|
+
failedShown.add(key);
|
|
543
|
+
const times = (rescueTimes.get(f.sessionId) || []).filter((t) => t >= Date.now() - 30 * 60 * 1000);
|
|
544
|
+
dbg(`pass sid=${String(f.sessionId).slice(0, 20)} times=${times.length} autoFix=${cfg.failedAutoFix}`);
|
|
545
|
+
if (cfg.failedAutoFix !== false && times.length < 3) {
|
|
546
|
+
let r;
|
|
547
|
+
try {
|
|
548
|
+
r = await rpc('/ac-continue', { method: 'POST', body: { sessionId: f.sessionId, text: continueTextFor(cfg.continueText) } });
|
|
549
|
+
} catch (e) {
|
|
550
|
+
dbg(`rpc threw ${String(e).slice(0, 80)}`);
|
|
551
|
+
r = null;
|
|
552
|
+
}
|
|
553
|
+
dbg(`rpc done ok=${r ? r.ok : 'null'} err=${r && r.error ? String(r.error).slice(0, 60) : '-'}`);
|
|
554
|
+
if (r && r.ok) { times.push(Date.now()); rescueTimes.set(f.sessionId, times); continue; } // 无头续接已启动;成败由下一轮扫描的活跃度验证
|
|
555
|
+
}
|
|
556
|
+
stuckQueue.push({ ...f, taskId: key, failedMsg: f.message || '' });
|
|
557
|
+
}
|
|
558
|
+
stuckQueue.sort((a, b) => b.ageSec - a.ageSec); // 悬得最久的先处理
|
|
559
|
+
// 每轮复核:任务已终结(比如刚被手动停掉)或会话恢复活跃的条目丢掉;
|
|
560
|
+
// 正在显示的那张卡如果已过期,先关掉再弹下一张
|
|
561
|
+
const removedCurrent = pruneStuckQueue(res, threshold);
|
|
562
|
+
if (removedCurrent && stuckCardEl) {
|
|
563
|
+
stuckCardEl.remove();
|
|
564
|
+
stuckCardEl = null;
|
|
565
|
+
}
|
|
566
|
+
showNextStuckCard();
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
export function startAutoContinue() {
|
|
570
|
+
if (typeof document === 'undefined') return;
|
|
571
|
+
window.addEventListener('zcodepro:config-changed', () => { cachedAt = 0; });
|
|
572
|
+
setInterval(() => { tick().catch(() => { /* 单次巡检失败不影响后续 */ }); }, SCAN_MS);
|
|
573
|
+
setInterval(() => { stuckTick().catch((e) => { (window.__acDebug ||= []).push(`stuckTick threw ${String(e).slice(0, 100)}`); }); }, STUCK_POLL_MS);
|
|
574
|
+
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// 先记下会话键,菜单出现后克隆官方菜单项样式插入。
|
|
7
7
|
// 生成成功即更新侧栏行并刷新标题锁定表(同 title-gen.js);手动动作失败弹提示
|
|
8
8
|
//(不再静默)。入口各有开关、素材轮数可调,都在“自动重命名”tab 下。
|
|
9
|
-
import { rpc, getConfig, itemsOf, itemText, closeRadixMenu, t, errText } from '../core.js';
|
|
9
|
+
import { rpc, getConfig, itemsOf, itemText, closeRadixMenu, t, errText, uiLocale, isRenameLabel } from '../core.js';
|
|
10
10
|
import { showToast } from '../ui.js';
|
|
11
11
|
import { setRowTitle, refreshPinnedTitles } from './title-lock.js';
|
|
12
12
|
|
|
@@ -32,7 +32,7 @@ async function runAutoRename(key) {
|
|
|
32
32
|
runningKeys.add(key);
|
|
33
33
|
showToast(L.autoRenameWorking, 'info');
|
|
34
34
|
try {
|
|
35
|
-
const res = await rpc('/title-gen/rename', { method: 'POST', body: { sessId } }).catch(() => null);
|
|
35
|
+
const res = await rpc('/title-gen/rename', { method: 'POST', body: { sessId, locale: uiLocale() } }).catch(() => null);
|
|
36
36
|
if (res && res.ok && res.title) {
|
|
37
37
|
setRowTitle(key, res.title);
|
|
38
38
|
void refreshPinnedTitles();
|
|
@@ -109,7 +109,7 @@ async function injectHoverButtons() {
|
|
|
109
109
|
export function handleTaskRowMenu(content) {
|
|
110
110
|
if (!ctxKey || Date.now() - ctxAt > RENAME_CTX_VALID_MS) return;
|
|
111
111
|
if (content.querySelector('[data-zcodepro-item="auto-rename"]')) return;
|
|
112
|
-
const anchor = itemsOf(content).find((el) =>
|
|
112
|
+
const anchor = itemsOf(content).find((el) => isRenameLabel(itemText(el)));
|
|
113
113
|
if (!anchor) return;
|
|
114
114
|
const key = ctxKey;
|
|
115
115
|
void getConfig().then((cfg) => {
|
|
@@ -8,12 +8,16 @@
|
|
|
8
8
|
// 2) 有运行中会话的项目(含子智能体/工作流,它们都在会话回合内运行)——先用
|
|
9
9
|
// 折叠项目运行检测(ws-running)的现场记录,回收前再无感展开复核一次兜底;
|
|
10
10
|
// 3) 有仍在运行的后台命令的项目——helper 扫描会话进程的子进程(/idle-busy,
|
|
11
|
-
// Linux/macOS/Windows 各走系统自带工具),插件/MCP
|
|
12
|
-
//
|
|
11
|
+
// Linux/macOS/Windows 各走系统自带工具),插件/MCP 基础设施与会话自己拉起
|
|
12
|
+
// 的空闲 worker 除外,剩余视为用户命令;扫描不可用时整个功能停用,不做盲回收。
|
|
13
|
+
// 4) 最近仍有子代理活动的项目——后台子代理可能在会话行不显示运行状态时继续跑,
|
|
14
|
+
// 等待模型返回时没有子进程、CPU 也低;用 helper 直查会话库的子代理活动时间
|
|
15
|
+
// 兜底(只读数据库,不会启动进程)。活动窗口跟 subagentFreshMinutes 共用,
|
|
16
|
+
// 查询失败按“仍有活动”处理。
|
|
13
17
|
// 定时/闲时任务由宿主进程调度、触发时自动重建会话进程,无需排除。
|
|
14
18
|
//
|
|
15
19
|
// 开关:features.idleReclaim(默认开)。
|
|
16
|
-
// 两个时长:idleReclaimMinutes 常规空闲判定(默认
|
|
20
|
+
// 两个时长:idleReclaimMinutes 常规空闲判定(默认 10,1–1440);
|
|
17
21
|
// idleReclaimStartupMinutes 启动一次性回收的延后分钟(默认 5,0–1440,0 = 启动后
|
|
18
22
|
// 尽快收一次,不受常规空闲时长限制——应用启动会为每个恢复的项目预热进程,这次
|
|
19
23
|
// 回收专治启动瞬间的内存高峰)。
|
|
@@ -54,6 +58,18 @@ async function sidebarWorkspaces() {
|
|
|
54
58
|
return out;
|
|
55
59
|
}
|
|
56
60
|
|
|
61
|
+
// 最近仍有子代理活动的项目不算空闲:后台子代理可能在会话行不显示运行状态时
|
|
62
|
+
// 继续跑,等待模型返回时既没有子进程、CPU 也很低,单靠进程扫描会误判。
|
|
63
|
+
// /workspace-subagent-activity 由 helper 按会话库 directory 直查(不受
|
|
64
|
+
// /workspace-sessions 的 30 条/7 天限制),不会启动进程;查询失败按“仍有活动”
|
|
65
|
+
// 处理——宁可漏回收也不掐正在跑的子代理
|
|
66
|
+
async function hasFreshSubagentActivity(ws, windowMs) {
|
|
67
|
+
const res = await rpc('/workspace-subagent-activity?path=' + encodeURIComponent(ws)).catch(() => null);
|
|
68
|
+
if (!res || res.ok !== true) return true; // 查询失败 = 未知,按忙处理
|
|
69
|
+
const at = Number(res.at) || 0;
|
|
70
|
+
return at > 0 && Date.now() - at <= windowMs;
|
|
71
|
+
}
|
|
72
|
+
|
|
57
73
|
async function reclaim(ws) {
|
|
58
74
|
const services = findServices();
|
|
59
75
|
if (!services) {
|
|
@@ -130,8 +146,13 @@ async function tick() {
|
|
|
130
146
|
idleSince.clear();
|
|
131
147
|
return;
|
|
132
148
|
}
|
|
133
|
-
const minutes = Math.min(MAX_MINUTES, Math.max(MIN_MINUTES, Number(cfg.idleReclaimMinutes) ||
|
|
149
|
+
const minutes = Math.min(MAX_MINUTES, Math.max(MIN_MINUTES, Number(cfg.idleReclaimMinutes) || 10));
|
|
134
150
|
const threshold = minutes * 60_000;
|
|
151
|
+
// 子代理保护窗口与空闲阈值解耦:单个长工具调用可静默 20 分钟上下,回收阈值
|
|
152
|
+
// 最小可到 1 分钟,用它当保护窗口等于没有保护。跟 subagent-icon 的“无活动多久
|
|
153
|
+
// 算结束”共用一个配置(subagentFreshMinutes,默认 60)
|
|
154
|
+
const freshMinutes = Number(cfg.subagentFreshMinutes);
|
|
155
|
+
const subagentGuardMs = (Number.isFinite(freshMinutes) && freshMinutes >= 1 ? Math.min(1440, Math.round(freshMinutes)) : 60) * 60_000;
|
|
135
156
|
let startupMinutes = Number(cfg.idleReclaimStartupMinutes);
|
|
136
157
|
if (!Number.isFinite(startupMinutes)) startupMinutes = 5;
|
|
137
158
|
startupMinutes = Math.min(MAX_MINUTES, Math.max(0, startupMinutes));
|
|
@@ -174,7 +195,7 @@ async function tick() {
|
|
|
174
195
|
}
|
|
175
196
|
// 启动扫不因失败反复重试:否则每个巡检周期(30 秒)都重新扫——扫描不可用
|
|
176
197
|
// 还每 30 秒拉一次 PowerShell 全进程枚举,正是要消除的常驻开销。下一次
|
|
177
|
-
//
|
|
198
|
+
// 尝试回到空闲阈值节奏(idleReclaimMinutes),扫描恢复后仍能自动接上
|
|
178
199
|
if (startupDue) startupSweepDone = true;
|
|
179
200
|
idleSince.clear();
|
|
180
201
|
return;
|
|
@@ -182,7 +203,12 @@ async function tick() {
|
|
|
182
203
|
if (startupDue) startupSweepDone = true;
|
|
183
204
|
const procBusy = new Set(res.busy || []);
|
|
184
205
|
for (const ws of due) {
|
|
206
|
+
// 有后台命令 = 项目仍在活动,空闲计时归零。单次 CPU 采样误判由 helper 侧的
|
|
207
|
+
// 阈值和窗口控制;这里保留“忙就重计”的语义,不把长命令计入空闲时长
|
|
185
208
|
if (procBusy.has(ws)) { idleSince.delete(ws); continue; }
|
|
209
|
+
// 后台子代理可能在等模型返回(没有子进程、CPU 也低),进程扫描看不到;
|
|
210
|
+
// 会话库里有最近活动就先不回收,避免把正在跑的代理掐掉
|
|
211
|
+
if (await hasFreshSubagentActivity(ws, subagentGuardMs)) { idleSince.delete(ws); continue; }
|
|
186
212
|
await tryReclaim(ws, threshold);
|
|
187
213
|
}
|
|
188
214
|
}
|