agent-bridge-qwenwork 1.0.37 → 1.0.41
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.md +8 -2
- package/dist/src-ts/plugins/agent-task-abilities.js +125 -0
- package/dist/src-ts/plugins/agent-task-ability.js +26 -10
- package/dist/src-ts/plugins/desktop-launch.js +98 -29
- package/dist/src-ts/plugins/desktop-runtime.js +29 -0
- package/dist/src-ts/plugins/qwenwork/cdp-client.js +348 -71
- package/dist/src-ts/plugins/qwenwork/index.js +175 -16
- package/dist/src-ts/plugins/qwenwork/openai-adapter.js +17 -6
- package/dist/src-ts/plugins/qwenwork/session-history.js +4 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
|
@@ -14,7 +14,44 @@ const cdp_draft_1 = require("../cdp-draft");
|
|
|
14
14
|
const agent_1 = require("../../agent");
|
|
15
15
|
const attachments_1 = require("../../attachments");
|
|
16
16
|
exports.assistantMessageSelector = '[data-message-id][data-part-type="text"]:not([data-conversation-user-text="true"])';
|
|
17
|
-
exports.inputSelector = '.chat-input-editor-text[contenteditable="true"]';
|
|
17
|
+
exports.inputSelector = '.chat-input-editor-text[contenteditable="true"],[data-voice-input-target="chat-input"][role="textbox"][contenteditable="true"]';
|
|
18
|
+
const visibleEditorExpression = `(() => {
|
|
19
|
+
const editors = [...document.querySelectorAll(${JSON.stringify(exports.inputSelector)})].filter(node => node.getClientRects().length > 0 && getComputedStyle(node).visibility !== 'hidden' && !node.closest('[inert]') && !node.closest('[hidden],[aria-hidden="true"]'));
|
|
20
|
+
if (editors.length !== 1) throw new Error('千问可见编辑器不唯一,不能确认任务身份');
|
|
21
|
+
return editors[0];
|
|
22
|
+
})()`;
|
|
23
|
+
// 新版千问的 URL 和输入框外观都不代表任务身份,只读取唯一可见编辑器的原生上下文。
|
|
24
|
+
const taskStateExpression = `(() => {
|
|
25
|
+
const visible = node => node.getClientRects().length > 0 && getComputedStyle(node).visibility !== 'hidden' && !node.closest('[inert]') && !node.closest('[hidden],[aria-hidden="true"]');
|
|
26
|
+
const editors = [...document.querySelectorAll(${JSON.stringify(exports.inputSelector)})].filter(visible);
|
|
27
|
+
if (editors.length !== 1) throw new Error('千问可见编辑器不唯一,不能确认任务身份');
|
|
28
|
+
const editor = editors[0];
|
|
29
|
+
const registry = globalThis.__agentBridgeQwenEditors ??= { editors: new WeakMap(), sequence: 0 };
|
|
30
|
+
if (!registry.editors.has(editor)) registry.editors.set(editor, ++registry.sequence);
|
|
31
|
+
const chats = new Set(), subs = new Set();
|
|
32
|
+
let homepage = false, newTask = false;
|
|
33
|
+
const key = Object.keys(editor).find(key => key.startsWith('__reactFiber'));
|
|
34
|
+
let fiber = key ? editor[key] : null;
|
|
35
|
+
// shortcut: 超过 256 层的 React 上下文拒绝使用,客户端结构更深时再提高上限。
|
|
36
|
+
for (let depth = 0; fiber && depth < 256; depth++, fiber = fiber.return) {
|
|
37
|
+
const props = fiber.memoizedProps ?? {};
|
|
38
|
+
homepage ||= props.homepage === true;
|
|
39
|
+
newTask ||= props.artifactNewTask === true;
|
|
40
|
+
for (const [name, values] of [['chatId', chats], ['subChatId', subs]]) {
|
|
41
|
+
const value = props[name];
|
|
42
|
+
if (value == null || value === '') continue;
|
|
43
|
+
if (typeof value !== 'string' || value.trim() !== value || value.length > 512 || /[\\u0000-\\u001f]/.test(value)) throw new Error('千问任务上下文标识无效');
|
|
44
|
+
values.add(value);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (fiber || chats.size > 1 || subs.size > 1 || Boolean(chats.size) !== Boolean(subs.size)) throw new Error('千问任务上下文存在歧义,不能确认任务身份');
|
|
48
|
+
const messages = document.querySelectorAll('[data-message-id]').length;
|
|
49
|
+
// 新首页预分配的 ID 尚未落库,必须同时确认原生首页属性、当前编辑器布局及无消息。
|
|
50
|
+
if (homepage && newTask && !messages && editor.closest('[data-slot="composer"][data-appearance="hero"]')) { chats.clear(); subs.clear(); }
|
|
51
|
+
return { url: location.href, editor: registry.editors.get(editor), chatId: [...chats][0] ?? null, subChatId: [...subs][0] ?? null,
|
|
52
|
+
messages, input: editor.innerText,
|
|
53
|
+
generating: Boolean(document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')) };
|
|
54
|
+
})()`;
|
|
18
55
|
function freshAssistantMessages(beforeIds, messages) {
|
|
19
56
|
return messages.filter((message) => Boolean(message.id) && !beforeIds.has(message.id) && Boolean(message.text?.trim()));
|
|
20
57
|
}
|
|
@@ -101,6 +138,8 @@ class QwenCdpClient {
|
|
|
101
138
|
socket;
|
|
102
139
|
sequence = 0;
|
|
103
140
|
pending = new Map();
|
|
141
|
+
historyIdentityScope;
|
|
142
|
+
historyIdentityMode;
|
|
104
143
|
options;
|
|
105
144
|
constructor(options = {}) {
|
|
106
145
|
this.options = {
|
|
@@ -118,7 +157,7 @@ class QwenCdpClient {
|
|
|
118
157
|
async healthCheck() {
|
|
119
158
|
if (!this.socket)
|
|
120
159
|
throw new Error("千问 CDP 尚未连接");
|
|
121
|
-
const result = await this.evaluate(`(() => Boolean(window.electronTRPC &&
|
|
160
|
+
const result = await this.evaluate(`(() => Boolean(window.electronTRPC && ${visibleEditorExpression}))()`);
|
|
122
161
|
if (result !== true)
|
|
123
162
|
throw new Error("千问主页面或输入框无响应");
|
|
124
163
|
}
|
|
@@ -128,41 +167,138 @@ class QwenCdpClient {
|
|
|
128
167
|
const reply = await this.direct(`这是后台健康检测。请只回复 ${token},不要添加任何其它文字。`, 45_000, undefined, token);
|
|
129
168
|
verifyQwenHeartbeatReply(token, reply);
|
|
130
169
|
}
|
|
170
|
+
taskGuard(state) {
|
|
171
|
+
return `(() => { const current = ${taskStateExpression}; return current.url === ${JSON.stringify(state.url)} && current.editor === ${state.editor} && current.chatId === ${JSON.stringify(state.chatId)} && current.subChatId === ${JSON.stringify(state.subChatId)}; })()`;
|
|
172
|
+
}
|
|
173
|
+
async readTaskState() {
|
|
174
|
+
const state = await this.evaluate(taskStateExpression);
|
|
175
|
+
if (!state.chatId) {
|
|
176
|
+
if (state.messages)
|
|
177
|
+
throw new Error("千问已有消息但原生任务上下文缺失,不能确认任务身份");
|
|
178
|
+
const scope = await this.taskIdentityScope();
|
|
179
|
+
await this.checkTaskIdentityScope(scope);
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
const chat = await this.queryHistory("chats.get", { id: state.chatId });
|
|
183
|
+
if (chat?.id !== state.chatId || !Array.isArray(chat.subChats)
|
|
184
|
+
|| chat.subChats.filter(sub => sub.id === state.subChatId && sub.chatId === state.chatId).length !== 1) {
|
|
185
|
+
throw new Error("千问编辑器与原生任务或子会话关联不符,不能确认任务身份");
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (await this.evaluate(this.taskGuard(state)) !== true)
|
|
189
|
+
throw new Error("千问原生任务查询期间编辑器或任务身份已切换");
|
|
190
|
+
return state;
|
|
191
|
+
}
|
|
192
|
+
async waitForAssignedTask(previous, reservationToken, submittedText) {
|
|
193
|
+
const deadline = Date.now() + Math.min(this.options.timeoutMs, 10_000);
|
|
194
|
+
while (Date.now() < deadline) {
|
|
195
|
+
const candidate = await this.evaluate(`(() => {
|
|
196
|
+
const state = ${taskStateExpression};
|
|
197
|
+
const reservation = globalThis.__agentBridgeQwenBlankTask;
|
|
198
|
+
const reservedEditor = reservation?.editor;
|
|
199
|
+
const editorReplaced = state.editor !== ${previous.editor};
|
|
200
|
+
const oldEditorVisible = reservedEditor?.getClientRects?.().length > 0 && getComputedStyle(reservedEditor).visibility !== 'hidden'
|
|
201
|
+
&& !reservedEditor.closest('[inert],[hidden],[aria-hidden="true"]');
|
|
202
|
+
const submittedMessage = [...document.querySelectorAll('[data-message-id][data-conversation-user-text="true"],[data-message-id] [data-role="user"] [data-slot="session-user-text"]')]
|
|
203
|
+
.some(message => message.innerText.trim() === ${JSON.stringify(submittedText.trim())});
|
|
204
|
+
// 新版首页提交后会卸载旧输入框;凭据未被用户操作撤销且新页面包含本次原文时才接受替换。
|
|
205
|
+
const replacementConfirmed = !oldEditorVisible && submittedMessage;
|
|
206
|
+
const currentEditor = [...document.querySelectorAll(${JSON.stringify(exports.inputSelector)})].find(editor => globalThis.__agentBridgeQwenEditors?.editors.get(editor) === state.editor);
|
|
207
|
+
if (state.url !== ${JSON.stringify(previous.url)}
|
|
208
|
+
|| reservation?.token !== ${JSON.stringify(reservationToken)}
|
|
209
|
+
|| (editorReplaced ? !replacementConfirmed : reservedEditor !== currentEditor)) {
|
|
210
|
+
throw new Error('千问首轮原生任务页面、编辑器或空白绑定已失效,任务可能已提交,请勿重复发送');
|
|
211
|
+
}
|
|
212
|
+
return state;
|
|
213
|
+
})()`);
|
|
214
|
+
if (candidate.chatId && candidate.subChatId) {
|
|
215
|
+
const verified = await this.readTaskState();
|
|
216
|
+
if (verified.chatId !== candidate.chatId || verified.subChatId !== candidate.subChatId)
|
|
217
|
+
throw new Error("千问首轮任务身份已切换,任务可能已提交,请勿重复发送");
|
|
218
|
+
return verified;
|
|
219
|
+
}
|
|
220
|
+
await wait(100);
|
|
221
|
+
}
|
|
222
|
+
throw new Error("千问首轮原生任务身份尚未确认,任务可能已提交,请勿重复发送");
|
|
223
|
+
}
|
|
131
224
|
async createSession(_name, forceNew = false, preserveDraft = false) {
|
|
132
225
|
await this.ensureVisible();
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
226
|
+
let before = await this.readTaskState();
|
|
227
|
+
if (!preserveDraft) {
|
|
228
|
+
await this.recoverDraft(undefined, this.taskGuard(before));
|
|
229
|
+
if (await this.evaluate(this.taskGuard(before)) !== true)
|
|
230
|
+
throw new Error("千问恢复草稿后任务身份已变化,不能新建会话");
|
|
231
|
+
before = await this.readTaskState();
|
|
232
|
+
}
|
|
233
|
+
if (before.input.trim())
|
|
138
234
|
throw new Error("千问输入框含有未发送内容,不能新建会话");
|
|
139
|
-
if (!forceNew && before.
|
|
140
|
-
return
|
|
141
|
-
const clicked = await this.evaluate(`(() => {
|
|
235
|
+
if (!forceNew && !before.chatId && before.messages === 0)
|
|
236
|
+
return undefined;
|
|
237
|
+
const clicked = await this.evaluate(`(() => {
|
|
238
|
+
if (!${this.taskGuard(before)}) throw new Error('千问任务已切换,不能新建会话');
|
|
239
|
+
const state = ${taskStateExpression};
|
|
240
|
+
if (state.input.trim() || state.generating) throw new Error('千问当前有未发送内容或正在生成回复,不能新建会话');
|
|
241
|
+
const button = document.querySelector('button[aria-label="新任务"]');
|
|
242
|
+
if (!button || button.disabled || button.getAttribute('aria-disabled') === 'true') return false;
|
|
243
|
+
button.click(); return true;
|
|
244
|
+
})()`);
|
|
142
245
|
if (clicked !== true)
|
|
143
246
|
throw new Error("千问新任务入口未找到或不可用");
|
|
144
|
-
|
|
145
|
-
await this.waitFor(`(() => { const state = ${snapshot}; return state.input !== null && state.input.trim() === '' && state.messages === 0 && state.blank; })()`, "千问新会话状态校验失败");
|
|
247
|
+
await this.waitFor(`(() => { const state = ${taskStateExpression}; return !state.chatId && !state.subChatId && !state.input.trim() && state.messages === 0 && !state.generating; })()`, "千问新会话状态校验失败");
|
|
146
248
|
return this.currentSessionId();
|
|
147
249
|
}
|
|
148
250
|
async currentSessionId() {
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
251
|
+
return (await this.readTaskState()).chatId ?? undefined;
|
|
252
|
+
}
|
|
253
|
+
async blankTaskToken() {
|
|
254
|
+
const token = (0, node_crypto_1.randomUUID)();
|
|
255
|
+
return await this.evaluate(`(() => {
|
|
256
|
+
const state = ${taskStateExpression};
|
|
257
|
+
const editor = globalThis.__agentBridgeQwenEditors && [...document.querySelectorAll(${JSON.stringify(exports.inputSelector)})].find(node => globalThis.__agentBridgeQwenEditors.editors.get(node) === state.editor);
|
|
258
|
+
const previous = globalThis.__agentBridgeQwenBlankTask;
|
|
259
|
+
if (!editor || state.input.trim() || state.chatId || state.subChatId || state.messages || state.generating) { previous?.clear(); return undefined; }
|
|
260
|
+
if (previous?.editor === editor && previous.url === location.href) return previous.token;
|
|
261
|
+
previous?.clear();
|
|
262
|
+
const reservation = { editor, url: location.href, token: ${JSON.stringify(token)}, submitting: false, invalidate: () => { if (!reservation.submitting) reservation.clear(); }, clear: () => {
|
|
263
|
+
if (globalThis.__agentBridgeQwenBlankTask === reservation) delete globalThis.__agentBridgeQwenBlankTask;
|
|
264
|
+
document.removeEventListener('click', reservation.invalidate, true);
|
|
265
|
+
document.removeEventListener('keydown', reservation.invalidate, true);
|
|
266
|
+
} };
|
|
267
|
+
globalThis.__agentBridgeQwenBlankTask = reservation;
|
|
268
|
+
document.addEventListener('click', reservation.invalidate, true);
|
|
269
|
+
document.addEventListener('keydown', reservation.invalidate, true);
|
|
270
|
+
return reservation.token;
|
|
271
|
+
})()`);
|
|
156
272
|
}
|
|
157
273
|
async activateSession(sessionId) {
|
|
158
274
|
if (!sessionId.trim() || sessionId.length > 512 || /[\u0000-\u001f]/.test(sessionId))
|
|
159
275
|
throw new Error("千问模型会话标识无效");
|
|
160
276
|
await this.ensureVisible();
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
277
|
+
const before = await this.readTaskState();
|
|
278
|
+
if (before.input.trim() || before.generating)
|
|
279
|
+
throw new Error("千问当前有未发送内容或正在生成回复,不能切换会话");
|
|
280
|
+
if (before.chatId === sessionId)
|
|
281
|
+
return;
|
|
282
|
+
const target = await this.queryHistory("chats.get", { id: sessionId });
|
|
283
|
+
if (target?.id !== sessionId)
|
|
284
|
+
throw new Error("千问切换目标与原生任务不符");
|
|
285
|
+
// 原生任务行的 list-action 调用自身导航,避免改写新版已不使用的 chat URL 参数。
|
|
286
|
+
const clicked = await this.evaluate(`(() => {
|
|
287
|
+
if (!${this.taskGuard(before)}) throw new Error('千问切换前任务身份已变化');
|
|
288
|
+
const state = ${taskStateExpression};
|
|
289
|
+
if (state.input.trim() || state.generating) throw new Error('千问当前有未发送内容或正在生成回复,不能切换会话');
|
|
290
|
+
const visible = node => node.getClientRects().length > 0 && getComputedStyle(node).visibility !== 'hidden' && !node.closest('[hidden],[aria-hidden="true"]');
|
|
291
|
+
const rows = [...document.querySelectorAll('[data-chat-id]')].filter(row => row.getAttribute('data-chat-id') === ${JSON.stringify(sessionId)} && visible(row));
|
|
292
|
+
if (rows.length !== 1) return false;
|
|
293
|
+
const buttons = [...rows[0].querySelectorAll('button[data-slot="list-action"]')].filter(visible);
|
|
294
|
+
if (buttons.length !== 1 || buttons[0].disabled || buttons[0].getAttribute('aria-disabled') === 'true') return false;
|
|
295
|
+
buttons[0].click(); return true;
|
|
296
|
+
})()`);
|
|
297
|
+
if (clicked !== true)
|
|
298
|
+
throw new Error("千问精确任务切换入口未找到或不唯一,未切换会话");
|
|
299
|
+
await this.waitFor(`(() => { const state = ${taskStateExpression}; return state.chatId === ${JSON.stringify(sessionId)}; })()`, "千问原生任务切换状态校验失败");
|
|
300
|
+
if (await this.currentSessionId() !== sessionId)
|
|
301
|
+
throw new Error("千问原生任务切换身份校验失败");
|
|
166
302
|
}
|
|
167
303
|
async connect() {
|
|
168
304
|
if (this.connected())
|
|
@@ -211,6 +347,8 @@ class QwenCdpClient {
|
|
|
211
347
|
close() {
|
|
212
348
|
const socket = this.socket;
|
|
213
349
|
this.socket = undefined;
|
|
350
|
+
this.historyIdentityScope = undefined;
|
|
351
|
+
this.historyIdentityMode = undefined;
|
|
214
352
|
socket?.close();
|
|
215
353
|
for (const pending of this.pending.values())
|
|
216
354
|
pending.reject(new Error("CDP 已关闭"));
|
|
@@ -227,29 +365,48 @@ class QwenCdpClient {
|
|
|
227
365
|
async direct(text, timeoutMs = 240_000, signal, expectedReply) {
|
|
228
366
|
return (await this.complete(text, timeoutMs, signal, expectedReply)).text;
|
|
229
367
|
}
|
|
230
|
-
async complete(text, timeoutMs = 240_000, signal, expectedReply, attachments, onMessage, preserveDraft = false) {
|
|
368
|
+
async complete(text, timeoutMs = 240_000, signal, expectedReply, attachments, onMessage, preserveDraft = false, expectedBlankTaskToken, expectedSessionId) {
|
|
231
369
|
let stage = "准备千问办公桌面任务";
|
|
232
370
|
let code = "QWEN_TASK_FAILED";
|
|
233
371
|
try {
|
|
234
372
|
(0, attachments_1.validateAttachments)(attachments);
|
|
235
373
|
if (expectedReply) {
|
|
236
|
-
const draft = await this.evaluate(
|
|
374
|
+
const draft = await this.evaluate(`${visibleEditorExpression}?.innerText ?? ''`);
|
|
237
375
|
if (typeof draft === "string" && draft.trim() && !isQwenBridgeHealthPrompt(draft))
|
|
238
376
|
throw new Error("千问输入框有用户草稿,跳过后台健康检测");
|
|
239
377
|
}
|
|
240
378
|
await this.ensureVisible();
|
|
241
379
|
// 冷启动的 CDP 可早于输入框就绪,只在真实请求中等待页面挂载。
|
|
242
380
|
await this.waitForInputReady();
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
381
|
+
signal?.throwIfAborted();
|
|
382
|
+
if (expectedBlankTaskToken && await this.blankTaskToken() !== expectedBlankTaskToken)
|
|
383
|
+
throw new Error("千问空白任务绑定已失效,未发送消息");
|
|
384
|
+
if (expectedSessionId && await this.currentSessionId() !== expectedSessionId)
|
|
385
|
+
throw new Error("千问发送前任务身份不一致,未发送消息");
|
|
386
|
+
let task = await this.readTaskState();
|
|
387
|
+
if (!preserveDraft) {
|
|
388
|
+
await this.recoverDraft(undefined, this.taskGuard(task));
|
|
389
|
+
if (await this.evaluate(this.taskGuard(task)) !== true)
|
|
390
|
+
throw new Error("千问恢复草稿后任务身份已变化,未发送消息");
|
|
391
|
+
task = await this.readTaskState();
|
|
392
|
+
}
|
|
393
|
+
if (expectedSessionId && task.chatId !== expectedSessionId)
|
|
394
|
+
throw new Error("千问发送前任务身份不一致,未发送消息");
|
|
395
|
+
if (!task.chatId && !expectedBlankTaskToken)
|
|
396
|
+
expectedBlankTaskToken = await this.blankTaskToken();
|
|
397
|
+
if (!task.chatId && !expectedBlankTaskToken)
|
|
398
|
+
throw new Error("千问空白任务身份未确认,未发送消息");
|
|
399
|
+
const ready = await this.evaluate(`(() => { const input = ${visibleEditorExpression}; return Boolean(input && !input.innerText.trim() && !document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')); })()`);
|
|
246
400
|
if (!ready)
|
|
247
401
|
throw new Error("千问输入框含有未发送内容或正在生成回复,未发送新消息");
|
|
248
|
-
const snapshot = await this.evaluate(`
|
|
402
|
+
const snapshot = await this.evaluate(`(() => {
|
|
403
|
+
if (!${this.taskGuard(task)}) throw new Error('千问读取消息前任务身份已变化');
|
|
404
|
+
return JSON.stringify([...document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})].map(element => ({ id: element.getAttribute('data-message-id'), text: element.innerText })));
|
|
405
|
+
})()`);
|
|
249
406
|
const before = JSON.parse(snapshot || "[]");
|
|
250
407
|
const beforeIds = new Set(before.map((message) => message.id).filter((id) => Boolean(id)));
|
|
251
408
|
const focused = await this.evaluate(`(() => {
|
|
252
|
-
const element =
|
|
409
|
+
const element = ${visibleEditorExpression};
|
|
253
410
|
if (!element) return false;
|
|
254
411
|
element.focus();
|
|
255
412
|
return true;
|
|
@@ -257,30 +414,56 @@ class QwenCdpClient {
|
|
|
257
414
|
if (!focused)
|
|
258
415
|
throw new Error("千问输入框未找到");
|
|
259
416
|
stage = "向千问办公上传入站附件(任务尚未提交)";
|
|
260
|
-
const addedIds = attachments?.length ? await this.injectAttachments(attachments) : [];
|
|
417
|
+
const addedIds = attachments?.length ? await this.injectAttachments(attachments, this.taskGuard(task)) : [];
|
|
261
418
|
stage = "向千问办公提交任务(尚未确认发送)";
|
|
262
419
|
code = "QWEN_SUBMIT_FAILED";
|
|
263
420
|
let submitUrl = "";
|
|
264
421
|
let inserted = false;
|
|
265
422
|
let submitAttempted = false;
|
|
266
423
|
try {
|
|
424
|
+
signal?.throwIfAborted();
|
|
267
425
|
submitUrl = String(await this.evaluate("location.href"));
|
|
426
|
+
await this.readTaskState();
|
|
427
|
+
if (await this.evaluate(this.taskGuard(task)) !== true)
|
|
428
|
+
throw new Error("千问提交前任务身份不一致,未发送消息");
|
|
429
|
+
if (expectedBlankTaskToken && await this.blankTaskToken() !== expectedBlankTaskToken)
|
|
430
|
+
throw new Error("千问空白任务绑定已失效,未发送消息");
|
|
268
431
|
const readyToSubmit = `(() => {
|
|
269
|
-
const input =
|
|
432
|
+
const input = ${visibleEditorExpression};
|
|
270
433
|
const button = document.querySelector('button[aria-label="发送消息"]');
|
|
271
434
|
const generating = document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]');
|
|
272
435
|
return Boolean(!document.hidden && location.href === ${JSON.stringify(submitUrl)} && input && input.innerText.trim() === ${JSON.stringify(text.trim())}
|
|
436
|
+
&& ${this.taskGuard(task)}
|
|
437
|
+
&& ${expectedBlankTaskToken ? `globalThis.__agentBridgeQwenBlankTask?.token === ${JSON.stringify(expectedBlankTaskToken)} && globalThis.__agentBridgeQwenBlankTask?.editor === input && document.querySelectorAll('[data-message-id]').length === 0` : "true"}
|
|
273
438
|
&& button && !button.disabled && button.getAttribute('aria-disabled') !== 'true' && !generating);
|
|
274
439
|
})()`;
|
|
440
|
+
signal?.throwIfAborted();
|
|
441
|
+
const refocused = await this.evaluate(`(() => {
|
|
442
|
+
if (!${this.taskGuard(task)}) return false;
|
|
443
|
+
const input = ${visibleEditorExpression};
|
|
444
|
+
if (input.innerText.trim()) return false;
|
|
445
|
+
input.focus();
|
|
446
|
+
return ${this.taskGuard(task)} && !input.innerText.trim();
|
|
447
|
+
})()`);
|
|
448
|
+
if (refocused !== true)
|
|
449
|
+
throw new Error("千问插入前编辑器或任务身份已变化,未发送消息");
|
|
450
|
+
signal?.throwIfAborted();
|
|
275
451
|
await this.cdp("Input.insertText", { text });
|
|
276
452
|
inserted = true;
|
|
277
453
|
// 只有复查确认尚未点击时才再试一次,不能重发提交结果未知的任务。
|
|
278
454
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
279
455
|
await this.waitFor(readyToSubmit, "千问发送按钮未就绪或输入校验失败,未发送消息");
|
|
456
|
+
await this.readTaskState();
|
|
457
|
+
if (await this.evaluate(this.taskGuard(task)) !== true)
|
|
458
|
+
throw new Error("千问提交瞬间任务身份已变化,未发送消息");
|
|
459
|
+
signal?.throwIfAborted();
|
|
280
460
|
submitAttempted = true;
|
|
281
461
|
const sent = await this.evaluate(`(() => {
|
|
282
462
|
if (!${readyToSubmit}) return false;
|
|
283
|
-
|
|
463
|
+
const reservation = ${expectedBlankTaskToken ? "globalThis.__agentBridgeQwenBlankTask" : "undefined"};
|
|
464
|
+
if (reservation) reservation.submitting = true;
|
|
465
|
+
try { document.querySelector('button[aria-label="发送消息"]').click(); }
|
|
466
|
+
finally { if (reservation) reservation.submitting = false; }
|
|
284
467
|
return true;
|
|
285
468
|
})()`);
|
|
286
469
|
if (sent === true)
|
|
@@ -289,23 +472,40 @@ class QwenCdpClient {
|
|
|
289
472
|
if (attempt === 1)
|
|
290
473
|
throw new Error("千问发送按钮未就绪或输入校验失败,未发送消息");
|
|
291
474
|
}
|
|
292
|
-
await this.waitFor(`(() => { const input =
|
|
475
|
+
await this.waitFor(`(() => { const input = ${visibleEditorExpression}; return Boolean(input && !input.innerText.trim()); })()`, "千问未确认消息已提交");
|
|
293
476
|
}
|
|
294
477
|
catch (error) {
|
|
295
478
|
// CDP 断开时清理也可能失败,保留最初的发送错误。
|
|
296
479
|
if (inserted && !submitAttempted) {
|
|
297
480
|
try {
|
|
298
|
-
await this.
|
|
481
|
+
if (await this.evaluate(this.taskGuard(task)) === true)
|
|
482
|
+
await this.recoverDraft({ text, url: submitUrl }, this.taskGuard(task));
|
|
299
483
|
}
|
|
300
484
|
catch { /* 清理失败不能覆盖原错。 */ }
|
|
301
485
|
}
|
|
302
486
|
try {
|
|
303
|
-
await this.cleanupAttachments(addedIds);
|
|
487
|
+
await this.cleanupAttachments(addedIds, this.taskGuard(task));
|
|
304
488
|
}
|
|
305
489
|
catch { /* 清理失败不能覆盖原错。 */ }
|
|
306
490
|
throw error;
|
|
307
491
|
}
|
|
308
|
-
const
|
|
492
|
+
const session = expectedBlankTaskToken ? await this.waitForAssignedTask(task, expectedBlankTaskToken, text) : await this.readTaskState();
|
|
493
|
+
const sessionUrl = session.url;
|
|
494
|
+
if (expectedBlankTaskToken) {
|
|
495
|
+
const bound = await this.evaluate(`(() => {
|
|
496
|
+
const reservation = globalThis.__agentBridgeQwenBlankTask;
|
|
497
|
+
if (reservation?.token !== ${JSON.stringify(expectedBlankTaskToken)} || !${this.taskGuard(session)}) throw new Error('千问首轮空白页绑定已失效,任务可能已提交,请勿重复发送');
|
|
498
|
+
reservation.clear();
|
|
499
|
+
return ${JSON.stringify(session.chatId)};
|
|
500
|
+
})()`);
|
|
501
|
+
if (!bound || bound !== session.chatId)
|
|
502
|
+
throw new Error("千问首轮原生任务身份尚未确认,任务可能已提交,请勿重复发送");
|
|
503
|
+
}
|
|
504
|
+
else if (session.chatId !== task.chatId || session.subChatId !== task.subChatId || session.editor !== task.editor || session.url !== task.url) {
|
|
505
|
+
throw new Error("千问提交后任务身份变化,任务可能已提交,请勿重复发送");
|
|
506
|
+
}
|
|
507
|
+
if (!session.chatId)
|
|
508
|
+
throw new Error("千问首轮原生任务身份尚未确认,任务可能已提交,请勿重复发送");
|
|
309
509
|
stage = "等待千问办公回复(任务已提交,桌面未被停止)";
|
|
310
510
|
code = "QWEN_REPLY_FAILED";
|
|
311
511
|
let previousReply = "";
|
|
@@ -313,12 +513,22 @@ class QwenCdpClient {
|
|
|
313
513
|
let seenGenerating = false;
|
|
314
514
|
let stoppedPolls = 0;
|
|
315
515
|
const forwarded = new Set();
|
|
516
|
+
const sessionGuard = this.taskGuard(session);
|
|
517
|
+
const verifySession = async () => {
|
|
518
|
+
await this.readTaskState();
|
|
519
|
+
if (await this.evaluate(sessionGuard) !== true)
|
|
520
|
+
throw new Error("千问会话已切换,停止读取其他任务正文;原任务未被停止");
|
|
521
|
+
};
|
|
316
522
|
let deadline = Date.now() + timeoutMs;
|
|
317
523
|
while (Date.now() < deadline || signal?.aborted) {
|
|
318
524
|
// 上游取消不停止桌面生成;确认结束前保留插件队列。
|
|
319
525
|
await wait(2_000);
|
|
320
526
|
await this.restoreVisible();
|
|
321
|
-
|
|
527
|
+
await verifySession();
|
|
528
|
+
const messagesJson = await this.evaluate(`(() => {
|
|
529
|
+
if (!${sessionGuard}) throw new Error('千问会话已切换,停止读取其他任务正文');
|
|
530
|
+
return JSON.stringify([...document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})].map(element => ({ id: element.getAttribute('data-message-id'), text: element.innerText })));
|
|
531
|
+
})()`);
|
|
322
532
|
const messages = JSON.parse(messagesJson || "[]");
|
|
323
533
|
const fresh = freshAssistantMessages(beforeIds, messages);
|
|
324
534
|
const reply = fresh.at(-1)?.text.trim() ?? "";
|
|
@@ -329,20 +539,23 @@ class QwenCdpClient {
|
|
|
329
539
|
if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
|
|
330
540
|
throw new Error("QWEN_REMOTE_ERROR:千问生成接口不可用;桌面仅返回通用错误,未提供服务端错误码;CDP 仍连接,未重启或重新提交任务");
|
|
331
541
|
const generating = await this.evaluate(`Boolean(document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]'))`);
|
|
542
|
+
await verifySession();
|
|
332
543
|
seenGenerating ||= generating === true;
|
|
333
544
|
stoppedPolls = seenGenerating && generating === false ? stoppedPolls + 1 : 0;
|
|
334
545
|
if (signal?.aborted && !reply && stoppedPolls >= 2 && messages.some(message => message.id && !beforeIds.has(message.id))) {
|
|
335
|
-
const attachments = expectedReply ? [] : await this.readArtifacts(beforeIds, sessionUrl);
|
|
546
|
+
const attachments = expectedReply ? [] : await this.readArtifacts(beforeIds, sessionUrl, sessionGuard);
|
|
547
|
+
await verifySession();
|
|
336
548
|
if (attachments.length)
|
|
337
|
-
return { text: "", sessionId:
|
|
549
|
+
return { text: "", sessionId: session.chatId, attachments };
|
|
338
550
|
code = "QWEN_REQUEST_CANCELLED";
|
|
339
551
|
throw new Error("请求已取消,已确认本轮桌面生成结束,未返回正文或附件");
|
|
340
552
|
}
|
|
341
553
|
if (!generating && (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3)) {
|
|
342
554
|
stage = "读取千问办公已完成任务的产物(尚未上传 AUN FS)";
|
|
343
555
|
code = "QWEN_ARTIFACT_READ_FAILED";
|
|
344
|
-
const attachments = expectedReply ? [] : await this.readArtifacts(beforeIds, sessionUrl);
|
|
345
|
-
|
|
556
|
+
const attachments = expectedReply ? [] : await this.readArtifacts(beforeIds, sessionUrl, sessionGuard);
|
|
557
|
+
await verifySession();
|
|
558
|
+
const sessionId = session.chatId;
|
|
346
559
|
return { text: reply, ...(sessionId ? { sessionId } : {}), ...(attachments.length ? { attachments } : {}) };
|
|
347
560
|
}
|
|
348
561
|
if (onMessage && generating && reply && stablePolls >= 1 && !forwarded.has(reply) && !isQwenApiUnavailableReply(reply)) {
|
|
@@ -350,7 +563,7 @@ class QwenCdpClient {
|
|
|
350
563
|
forwarded.add(reply);
|
|
351
564
|
}
|
|
352
565
|
}
|
|
353
|
-
const permission = await this.permissionStatus(sessionUrl);
|
|
566
|
+
const permission = await this.permissionStatus(sessionUrl, session.chatId);
|
|
354
567
|
throw new Error(permission ?? `QWEN_REPLY_TIMEOUT:千问办公 UI 超时未返回回复(已等待 ${Math.round(timeoutMs / 1000)} 秒);桌面任务未被停止`);
|
|
355
568
|
}
|
|
356
569
|
catch (error) {
|
|
@@ -359,11 +572,11 @@ class QwenCdpClient {
|
|
|
359
572
|
throw new agent_1.AgentOperationError(code, stage, error);
|
|
360
573
|
}
|
|
361
574
|
}
|
|
362
|
-
async permissionStatus(sessionUrl) {
|
|
575
|
+
async permissionStatus(sessionUrl, verifiedSessionId) {
|
|
363
576
|
try {
|
|
364
577
|
if (await this.evaluate("typeof window !== 'undefined' && Boolean(window.electronTRPC)") !== true)
|
|
365
578
|
return;
|
|
366
|
-
const chatId = new URL(sessionUrl).searchParams.get("chat");
|
|
579
|
+
const chatId = verifiedSessionId || new URL(sessionUrl).searchParams.get("chat");
|
|
367
580
|
if (!chatId)
|
|
368
581
|
return;
|
|
369
582
|
const response = await this.trpc("agent.getAllStreamingStates", "query", {});
|
|
@@ -385,7 +598,7 @@ class QwenCdpClient {
|
|
|
385
598
|
catch { /* 旧版客户端不支持该只读接口时,保留原始超时信息。 */ }
|
|
386
599
|
return;
|
|
387
600
|
}
|
|
388
|
-
async injectAttachments(items) {
|
|
601
|
+
async injectAttachments(items, taskGuard = "true") {
|
|
389
602
|
const files = items.map(item => {
|
|
390
603
|
const original = (0, attachments_1.attachmentFilename)(item.filename);
|
|
391
604
|
const dot = original.lastIndexOf(".");
|
|
@@ -394,7 +607,8 @@ class QwenCdpClient {
|
|
|
394
607
|
return { filename, contentType: item.contentType, data: Buffer.from(item.data).toString("base64") };
|
|
395
608
|
});
|
|
396
609
|
const result = await this.evaluate(`(async () => {
|
|
397
|
-
|
|
610
|
+
if (!${taskGuard}) throw new Error('千问附件上传前任务身份已变化');
|
|
611
|
+
const editor = ${visibleEditorExpression};
|
|
398
612
|
if (!editor) throw new Error('千问附件输入框未找到');
|
|
399
613
|
const key = Object.keys(editor).find(key => key.startsWith('__reactFiber'));
|
|
400
614
|
let props;
|
|
@@ -405,7 +619,8 @@ class QwenCdpClient {
|
|
|
405
619
|
const existing = [...(props.files ?? []), ...(props.images ?? []), ...(props.slashAddedFiles ?? [])];
|
|
406
620
|
if (existing.length) throw new Error('千问输入框已有附件,未发送消息');
|
|
407
621
|
const cleanupAdded = (ids, names = []) => {
|
|
408
|
-
|
|
622
|
+
if (!${taskGuard}) return;
|
|
623
|
+
const currentEditor = ${visibleEditorExpression};
|
|
409
624
|
const currentKey = Object.keys(currentEditor ?? {}).find(key => key.startsWith('__reactFiber'));
|
|
410
625
|
let current;
|
|
411
626
|
for (let fiber = currentKey && currentEditor ? currentEditor[currentKey] : null; fiber; fiber = fiber.return) {
|
|
@@ -426,6 +641,7 @@ class QwenCdpClient {
|
|
|
426
641
|
try { cleanupAdded([], files.map(file => file.name)); } catch { /* 保留原生上传错误。 */ }
|
|
427
642
|
throw error;
|
|
428
643
|
}
|
|
644
|
+
if (!${taskGuard}) throw new Error('千问附件上传期间任务身份已变化');
|
|
429
645
|
const added = [...(uploaded?.images ?? []), ...(uploaded?.files ?? [])];
|
|
430
646
|
const ids = added.map(item => item.id).filter(id => typeof id === 'string');
|
|
431
647
|
if (added.length !== files.length || ids.length !== files.length || added.some(item => item.isLoading)) {
|
|
@@ -438,11 +654,12 @@ class QwenCdpClient {
|
|
|
438
654
|
throw new Error("千问附件上传未确认,未发送消息");
|
|
439
655
|
return result;
|
|
440
656
|
}
|
|
441
|
-
async cleanupAttachments(ids) {
|
|
657
|
+
async cleanupAttachments(ids, taskGuard = "true") {
|
|
442
658
|
if (!ids.length)
|
|
443
659
|
return;
|
|
444
660
|
await this.evaluate(`(() => {
|
|
445
|
-
|
|
661
|
+
if (!${taskGuard}) return;
|
|
662
|
+
const editor = ${visibleEditorExpression}; if (!editor) return;
|
|
446
663
|
const key = Object.keys(editor).find(key => key.startsWith('__reactFiber')); const ids = ${JSON.stringify(ids)};
|
|
447
664
|
for (let fiber = editor[key]; fiber; fiber = fiber.return) {
|
|
448
665
|
const props = fiber.memoizedProps; if (typeof props?.onAddAttachments !== 'function') continue;
|
|
@@ -452,9 +669,9 @@ class QwenCdpClient {
|
|
|
452
669
|
}
|
|
453
670
|
})()`);
|
|
454
671
|
}
|
|
455
|
-
async readArtifacts(beforeIds, sessionUrl) {
|
|
672
|
+
async readArtifacts(beforeIds, sessionUrl, taskGuard = "true") {
|
|
456
673
|
const collectArtifacts = `(() => {
|
|
457
|
-
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
674
|
+
if (location.href !== ${JSON.stringify(sessionUrl)} || !${taskGuard}) throw new Error('千问会话已切换,停止采集附件');
|
|
458
675
|
const before = new Set(${JSON.stringify([...beforeIds])}); const files = [];
|
|
459
676
|
for (const part of document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})) {
|
|
460
677
|
if (before.has(part.getAttribute('data-message-id'))) continue;
|
|
@@ -471,7 +688,7 @@ class QwenCdpClient {
|
|
|
471
688
|
})()`;
|
|
472
689
|
// 工具区域由 React 异步展开,点击和读取必须分开执行。
|
|
473
690
|
await this.evaluate(`(() => {
|
|
474
|
-
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
691
|
+
if (location.href !== ${JSON.stringify(sessionUrl)} || !${taskGuard}) throw new Error('千问会话已切换,停止采集附件');
|
|
475
692
|
const before = new Set(${JSON.stringify([...beforeIds])});
|
|
476
693
|
for (const part of document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})) {
|
|
477
694
|
if (before.has(part.getAttribute('data-message-id'))) continue;
|
|
@@ -484,7 +701,7 @@ class QwenCdpClient {
|
|
|
484
701
|
})()`);
|
|
485
702
|
let encoded = "[]";
|
|
486
703
|
for (let attempt = 0; attempt < 12; attempt++) {
|
|
487
|
-
encoded = String(await this.evaluateArtifactResult(collectArtifacts, sessionUrl) ?? "[]");
|
|
704
|
+
encoded = String(await this.evaluateArtifactResult(collectArtifacts, sessionUrl, taskGuard) ?? "[]");
|
|
488
705
|
if (encoded !== "[]")
|
|
489
706
|
break;
|
|
490
707
|
await wait(250);
|
|
@@ -500,7 +717,7 @@ class QwenCdpClient {
|
|
|
500
717
|
return attachments;
|
|
501
718
|
}
|
|
502
719
|
const downloaded = await this.evaluateArtifactResult(`(async () => {
|
|
503
|
-
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
720
|
+
if (location.href !== ${JSON.stringify(sessionUrl)} || !${taskGuard}) throw new Error('千问会话已切换,停止采集附件');
|
|
504
721
|
const urls = ${JSON.stringify(addresses)}; const result = []; let total = 0;
|
|
505
722
|
for (const url of urls) {
|
|
506
723
|
const response = await fetch(url); if (!response.ok || !response.body) continue;
|
|
@@ -512,7 +729,7 @@ class QwenCdpClient {
|
|
|
512
729
|
result.push({ url, data: btoa(binary), contentType: response.headers.get('content-type')?.split(';')[0] || '' });
|
|
513
730
|
}
|
|
514
731
|
return result;
|
|
515
|
-
})()`, sessionUrl);
|
|
732
|
+
})()`, sessionUrl, taskGuard);
|
|
516
733
|
for (const item of downloaded) {
|
|
517
734
|
const data = new Uint8Array(Buffer.from(item.data, "base64"));
|
|
518
735
|
const contentType = (0, attachments_1.detectImageContentType)(data);
|
|
@@ -530,12 +747,12 @@ class QwenCdpClient {
|
|
|
530
747
|
return attachments;
|
|
531
748
|
}
|
|
532
749
|
/** 将页面结果留在本轮临时缓存,避免图片或视频超过 CDP 单条响应上限。 */
|
|
533
|
-
async evaluateArtifactResult(expression, sessionUrl) {
|
|
750
|
+
async evaluateArtifactResult(expression, sessionUrl, taskGuard = "true") {
|
|
534
751
|
const cacheKey = `__mab_qwen_artifacts_${(0, node_crypto_1.randomUUID)()}`;
|
|
535
752
|
const maxLength = Math.ceil(attachments_1.MAX_TOTAL_ATTACHMENT_BYTES / 3) * 4 + 1_048_576;
|
|
536
753
|
try {
|
|
537
754
|
const length = await this.evaluate(`(async () => {
|
|
538
|
-
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
755
|
+
if (location.href !== ${JSON.stringify(sessionUrl)} || !${taskGuard}) throw new Error('千问会话已切换,停止采集附件');
|
|
539
756
|
const encoded = JSON.stringify(await (${expression}));
|
|
540
757
|
if (typeof encoded !== 'string' || encoded.length > ${maxLength}) throw new Error('千问附件结果过大或无效');
|
|
541
758
|
window[${JSON.stringify(cacheKey)}] = encoded;
|
|
@@ -547,7 +764,7 @@ class QwenCdpClient {
|
|
|
547
764
|
for (let offset = 0; offset < length; offset += 262_144) {
|
|
548
765
|
const end = Math.min(offset + 262_144, length);
|
|
549
766
|
const part = await this.evaluate(`(() => {
|
|
550
|
-
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
767
|
+
if (location.href !== ${JSON.stringify(sessionUrl)} || !${taskGuard}) throw new Error('千问会话已切换,停止采集附件');
|
|
551
768
|
return window[${JSON.stringify(cacheKey)}]?.slice(${offset}, ${end});
|
|
552
769
|
})()`);
|
|
553
770
|
if (typeof part !== "string" || part.length !== end - offset)
|
|
@@ -602,8 +819,8 @@ class QwenCdpClient {
|
|
|
602
819
|
if (document.hidden && typeof window.desktopApi?.focusMainWindow === 'function') await window.desktopApi.focusMainWindow();
|
|
603
820
|
})()`);
|
|
604
821
|
}
|
|
605
|
-
recoverDraft(expected) {
|
|
606
|
-
return (0, cdp_draft_1.recoverCdpDraft)(this.evaluate.
|
|
822
|
+
recoverDraft(expected, taskGuard = "true") {
|
|
823
|
+
return (0, cdp_draft_1.recoverCdpDraft)(expression => this.evaluate(`(() => { if (!${taskGuard}) throw new Error('千问草稿恢复期间任务身份已变化'); return (${expression}); })()`.replaceAll(`document.querySelector(${JSON.stringify(exports.inputSelector)})`, visibleEditorExpression)), exports.inputSelector, 'button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]', this.options.dataDir, expected);
|
|
607
824
|
}
|
|
608
825
|
async cdp(method, params = {}, timeoutMs = this.options.timeoutMs) {
|
|
609
826
|
if (!this.socket)
|
|
@@ -656,18 +873,78 @@ class QwenCdpClient {
|
|
|
656
873
|
}
|
|
657
874
|
/** 仅开放已核实的会话历史只读查询,不允许从历史 provider 调用 mutation。 */
|
|
658
875
|
async queryHistory(path, input) {
|
|
659
|
-
const
|
|
660
|
-
const
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
876
|
+
const scope = await this.taskIdentityScope();
|
|
877
|
+
const result = this.historyResult(await this.trpc(path, "query", { ...input, ...(scope ? { expectedScope: scope } : {}) }), path);
|
|
878
|
+
await this.checkTaskIdentityScope(scope);
|
|
879
|
+
return result;
|
|
880
|
+
}
|
|
881
|
+
async taskIdentityScope() {
|
|
882
|
+
const mode = await (this.historyIdentityMode ??= this.readHistoryIdentityMode());
|
|
883
|
+
if (await this.readHistoryIdentityMode() !== mode)
|
|
884
|
+
throw new Error("千问原生身份启动模式已变化,未读取任务内容");
|
|
885
|
+
return mode === "isolated" ? (this.historyIdentityScope ??= this.readHistoryIdentityScope()) : undefined;
|
|
886
|
+
}
|
|
887
|
+
async checkTaskIdentityScope(scope) {
|
|
888
|
+
if (await this.readHistoryIdentityMode() !== (scope ? "isolated" : "shared"))
|
|
889
|
+
throw new Error("千问原生身份启动模式已变化,未返回任务内容");
|
|
890
|
+
if (scope) {
|
|
891
|
+
const checked = this.historyResult(await this.trpc("auth.checkLocalIdentityScope", "query", { scope }), "auth.checkLocalIdentityScope");
|
|
892
|
+
if (checked?.valid !== true)
|
|
893
|
+
throw new Error("千问任务身份上下文已变化,未返回任务内容或发送消息");
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* 新版千问在 shared 模式下明确关闭本地身份隔离,插件不向原生接口附加 expectedScope。
|
|
898
|
+
* 未明确暴露 shared 标记时按隔离模式处理,避免把身份状态误降级为共享模式。
|
|
899
|
+
*/
|
|
900
|
+
async readHistoryIdentityMode() {
|
|
901
|
+
const mode = await this.evaluate(`(() => {
|
|
902
|
+
const startup = globalThis.__localIdentityStartup;
|
|
903
|
+
return startup && startup.version === 2 && startup.mode === "shared" ? "shared" : "isolated";
|
|
904
|
+
})()`);
|
|
905
|
+
if (mode !== "shared" && mode !== "isolated")
|
|
906
|
+
throw new Error("千问原生身份启动模式无效,未读取任务内容");
|
|
907
|
+
return mode;
|
|
908
|
+
}
|
|
909
|
+
async readHistoryIdentityScope() {
|
|
910
|
+
const status = this.historyResult(await this.trpc("auth.getLocalIdentityStatus", "query", {}), "auth.getLocalIdentityStatus");
|
|
911
|
+
const scope = status?.scope;
|
|
912
|
+
if (status?.state !== "active" || typeof status.validUntil !== "number" || !Number.isFinite(status.validUntil) || status.validUntil <= Date.now()
|
|
913
|
+
|| !scope || typeof scope.identityKey !== "string" || !scope.identityKey || scope.identityKey.length > 4096
|
|
914
|
+
|| !Number.isSafeInteger(scope.identityVersion) || scope.identityVersion < 0
|
|
915
|
+
|| typeof scope.activationId !== "string" || !scope.activationId || scope.activationId.length > 256) {
|
|
916
|
+
throw new Error("千问本地身份不可用或已过期,请在千问桌面确认登录和身份后重载插件重试");
|
|
917
|
+
}
|
|
918
|
+
// 与原生渲染器一致,绑定当前身份;身份切换后由主进程拒绝,不改用新身份重试。
|
|
919
|
+
return { identityKey: scope.identityKey, identityVersion: scope.identityVersion, activationId: scope.activationId };
|
|
920
|
+
}
|
|
921
|
+
historyResult(value, path) {
|
|
922
|
+
const envelope = value;
|
|
923
|
+
const error = envelope?.error ?? envelope?.result?.error;
|
|
924
|
+
if (error) {
|
|
925
|
+
const reason = typeof error.json?.message === "string" ? error.json.message : "原生接口未提供具体原因";
|
|
926
|
+
if (reason === "IDENTITY_SCOPE_STALE")
|
|
927
|
+
throw new Error("千问本地身份上下文已变化,请在千问桌面确认当前身份并重载插件后重试(IDENTITY_SCOPE_STALE)");
|
|
928
|
+
if (reason.startsWith("IDENTITY_"))
|
|
929
|
+
throw new Error(`千问本地身份不可用,请在千问桌面确认登录和访问权限后重试(${reason})`);
|
|
930
|
+
throw new Error(`千问历史只读查询 ${path} 失败:${reason}`);
|
|
931
|
+
}
|
|
932
|
+
if (envelope?.result?.type === "data" && envelope.result.data && Object.hasOwn(envelope.result.data, "json"))
|
|
933
|
+
return envelope.result.data.json;
|
|
934
|
+
throw new Error(`千问历史只读查询 ${path} 未返回有效数据`);
|
|
664
935
|
}
|
|
665
936
|
async waitFor(expression, message) {
|
|
666
937
|
const deadline = Date.now() + this.options.timeoutMs;
|
|
667
938
|
while (Date.now() < deadline) {
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
939
|
+
try {
|
|
940
|
+
await this.restoreVisible();
|
|
941
|
+
if (await this.evaluate(expression))
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
catch (error) {
|
|
945
|
+
if (!(error instanceof Error) || !error.message.includes("千问可见编辑器不唯一"))
|
|
946
|
+
throw error;
|
|
947
|
+
}
|
|
671
948
|
await wait(200);
|
|
672
949
|
}
|
|
673
950
|
throw new Error(message);
|
|
@@ -676,7 +953,7 @@ class QwenCdpClient {
|
|
|
676
953
|
const deadline = Date.now() + this.options.timeoutMs;
|
|
677
954
|
while (Date.now() < deadline) {
|
|
678
955
|
await this.restoreVisible();
|
|
679
|
-
if (await this.evaluate(`Boolean(
|
|
956
|
+
if (await this.evaluate(`(() => { try { return Boolean(${visibleEditorExpression}); } catch { return false; } })()`))
|
|
680
957
|
return;
|
|
681
958
|
await wait(200);
|
|
682
959
|
}
|