agent-things 1.2.1 → 1.3.1

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.
@@ -27,6 +27,11 @@ function processHookInput(rawInput) {
27
27
  return {};
28
28
  }
29
29
 
30
+ // 同一轮对话后续多次触发大模型调用时跳过,避免重复生成卡片或重复注入快速通道提示
31
+ if (typeof payload.invocationNum === 'number' && payload.invocationNum > 0) {
32
+ return {};
33
+ }
34
+
30
35
  const lastUserInput = payload.lastUserInput;
31
36
  if (!isThingsCommand(lastUserInput)) {
32
37
  return {};
@@ -99,18 +104,18 @@ function processHookInput(rawInput) {
99
104
  const mdColon = lang === 'en' ? ': ' : ':';
100
105
  const userMarkdown = `${cardResult.embedTag}\n\n**${t('mdProgressHeading')}${mdColon}${stateText}**\n- **${t('mdTasksOverview')}**${mdColon}${tasksText}${noteText}\n- **${t('mdQuickActionsLabel')}**${mdColon}${t('mdQuickActionsText')}`;
101
106
 
107
+ const content = lang === 'en'
108
+ ? `[Agent Things Fast-Path] The session progress card artifact for this conversation has ALREADY been generated locally (conversation_id=${conversationId}). Do NOT call read_file (do NOT read SKILL.md), and do NOT call call_mcp_tool or render_things_card. Output the following markdown verbatim in your response:\n\n${userMarkdown}`
109
+ : `[Agent Things 快速通道] 当前会话任务进度卡片已由本地 Hook 直接生成(conversation_id=${conversationId})。严禁再调用 read_file(不要读取 SKILL.md),严禁调用 call_mcp_tool 或 render_things_card。请直接在本次回复中原样输出以下完整 Markdown(不要遗漏 <agent-embed> 标签):\n\n${userMarkdown}`;
110
+
102
111
  return {
103
112
  injectSteps: [
104
113
  {
105
- systemMessage: {
106
- systemMessage: t('hookPresentedMessage'),
107
- metadata: {
108
- user_markdown: userMarkdown,
109
- },
110
- },
114
+ // Use plain-string ephemeralMessage: language_server_bin panics on map<string,string> metadata fields
115
+ // and rejects hookEphemeralMessage, while plain-string ephemeralMessage stays UI-hidden and renders in 1 turn.
116
+ ephemeralMessage: content,
111
117
  },
112
118
  ],
113
- terminationBehavior: 'terminate',
114
119
  };
115
120
  }
116
121
 
@@ -3,7 +3,33 @@ const fs = require('node:fs');
3
3
  const path = require('node:path');
4
4
  const os = require('node:os');
5
5
  const DEFAULT_FILE = path.join(os.homedir(), '.gemini/antigravity/mcp_config.json');
6
+ const UNIFIED_RELATIVE = '.gemini/config/mcp_config.json';
7
+ const LEGACY_RELATIVE = '.gemini/antigravity/mcp_config.json';
6
8
  const owned = server => Array.isArray(server?.args) && server.args.some(arg => typeof arg === 'string' && path.basename(arg) === 'antigravity-session-status.cjs');
9
+ function resolveConfigFiles({ file, homeDirectory = os.homedir() } = {}) {
10
+ if (file) return [file];
11
+ const files = [path.join(homeDirectory, LEGACY_RELATIVE)];
12
+ const unified = path.join(homeDirectory, UNIFIED_RELATIVE);
13
+ if (fs.existsSync(unified)) files.push(unified);
14
+ return files;
15
+ }
16
+ function mergeServerConfig(existing, nodeBin, scriptPath) {
17
+ const existingTools = existing?.tools && typeof existing.tools === 'object' ? existing.tools : {};
18
+ const existingRenderTool = existingTools.render_things_card && typeof existingTools.render_things_card === 'object'
19
+ ? existingTools.render_things_card
20
+ : {};
21
+ return {
22
+ command: nodeBin,
23
+ args: [scriptPath],
24
+ tools: {
25
+ ...existingTools,
26
+ render_things_card: {
27
+ ...existingRenderTool,
28
+ eager: true,
29
+ },
30
+ },
31
+ };
32
+ }
7
33
  function updateConfig(file, change) {
8
34
  const original = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
9
35
  const data = original === null ? {} : JSON.parse(original);
@@ -17,20 +43,24 @@ function updateConfig(file, change) {
17
43
  try { fs.writeFileSync(temporary, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 }); fs.renameSync(temporary, file); }
18
44
  finally { fs.rmSync(temporary, { force: true }); }
19
45
  }
20
- function installAntigravityMcp({ file = DEFAULT_FILE, scriptPath, nodeBin = process.execPath } = {}) {
21
- updateConfig(file, servers => {
22
- const key = Object.keys(servers).find(key => owned(servers[key])) || 'session_status';
23
- if (servers[key] && !owned(servers[key])) throw new Error('Antigravity session_status 名称已被其他服务使用');
24
- servers[key] = { command: nodeBin, args: [scriptPath] };
25
- return true;
26
- });
46
+ function installAntigravityMcp({ file, homeDirectory = os.homedir(), scriptPath, nodeBin = process.execPath } = {}) {
47
+ for (const target of resolveConfigFiles({ file, homeDirectory })) {
48
+ updateConfig(target, servers => {
49
+ const key = Object.keys(servers).find(key => owned(servers[key])) || 'session_status';
50
+ if (servers[key] && !owned(servers[key])) throw new Error('Antigravity session_status 名称已被其他服务使用');
51
+ servers[key] = mergeServerConfig(servers[key], nodeBin, scriptPath);
52
+ return true;
53
+ });
54
+ }
27
55
  }
28
- function disableAntigravityMcp({ file = DEFAULT_FILE } = {}) {
29
- if (!fs.existsSync(file)) return;
30
- updateConfig(file, servers => {
31
- const keys = Object.keys(servers).filter(key => owned(servers[key]));
32
- for (const key of keys) delete servers[key];
33
- return keys.length > 0;
34
- });
56
+ function disableAntigravityMcp({ file, homeDirectory = os.homedir() } = {}) {
57
+ for (const target of resolveConfigFiles({ file, homeDirectory })) {
58
+ if (!fs.existsSync(target)) continue;
59
+ updateConfig(target, servers => {
60
+ const keys = Object.keys(servers).filter(key => owned(servers[key]));
61
+ for (const key of keys) delete servers[key];
62
+ return keys.length > 0;
63
+ });
64
+ }
35
65
  }
36
- module.exports = { installAntigravityMcp, disableAntigravityMcp };
66
+ module.exports = { installAntigravityMcp, disableAntigravityMcp, resolveConfigFiles };
@@ -267,18 +267,20 @@ async function executeSetupUnlocked({ lang = 'zh', enabledApps = ['codex', 'anti
267
267
  const claude = require('../../scripts/setup-claude-service.cjs');
268
268
  const codexConfig = path.join(home, '.codex/config.toml');
269
269
  const agyConfig = path.join(home, '.gemini/antigravity/mcp_config.json');
270
+ const agyUnifiedConfig = path.join(home, '.gemini/config/mcp_config.json');
270
271
  const claudeConfig = path.join(home, '.claude.json');
271
272
  if (enabledApps.includes('codex') && !fs.existsSync(codexConfig)) {
272
273
  throw new Error(en ? 'Please open ChatGPT.app and sign in to Codex first so its configuration file is created.' : '请先启动 ChatGPT.app 并完成 Codex 登录,以建立配置文件。');
273
274
  }
274
275
  if (enabledApps.includes('antigravity') && fs.existsSync(agyConfig)) JSON.parse(fs.readFileSync(agyConfig, 'utf8'));
276
+ if (enabledApps.includes('antigravity') && fs.existsSync(agyUnifiedConfig)) JSON.parse(fs.readFileSync(agyUnifiedConfig, 'utf8'));
275
277
  if (enabledApps.includes('claude') && fs.existsSync(claudeConfig)) JSON.parse(fs.readFileSync(claudeConfig, 'utf8'));
276
278
  for (const file of [path.join(DATA_DIR, 'manual-state.json'), path.join(home, '.gemini/antigravity/session-status/manual-state.json'), require('../harnesses/claude/claude-service.cjs').DEFAULT_STATE_FILE]) {
277
279
  if (fs.existsSync(file) && JSON.parse(fs.readFileSync(file, 'utf8')).timeline?.some(event => event.status === 'pending')) {
278
280
  throw new Error(en ? 'Please wait for the active analysis to finish before modifying components.' : '请等待当前分析结束后再修改组件。');
279
281
  }
280
282
  }
281
- const files = [CONFIG_FILE, codexConfig, agyConfig, claudeConfig, PLIST_FILE, agy.PLIST_PATH, claude.PLIST_PATH,
283
+ const files = [CONFIG_FILE, codexConfig, agyConfig, agyUnifiedConfig, claudeConfig, PLIST_FILE, agy.PLIST_PATH, claude.PLIST_PATH,
282
284
  path.join(DATA_DIR, 'bridge'), path.join(DATA_DIR, 'autostart.json'),
283
285
  path.join(home, '.codex/skills/agent-things/SKILL.md'),
284
286
  path.join(home, '.codex/skills/agent-things-card/SKILL.md'),
@@ -315,10 +317,10 @@ async function executeSetupUnlocked({ lang = 'zh', enabledApps = ['codex', 'anti
315
317
  }
316
318
  if (enabledApps.includes('antigravity')) {
317
319
  await agy.install({ root: runtime });
318
- installAntigravityMcp({ scriptPath: path.join(runtime, 'bin/antigravity-session-status.cjs') });
320
+ installAntigravityMcp({ homeDirectory: home, scriptPath: path.join(runtime, 'bin/antigravity-session-status.cjs') });
319
321
  syncAntigravityHooks(true, { homeDirectory: home, runtime });
320
322
  } else {
321
- disableAntigravityMcp();
323
+ disableAntigravityMcp({ homeDirectory: home });
322
324
  syncAntigravityHooks(false, { homeDirectory: home, runtime });
323
325
  }
324
326
  if (enabledApps.includes('claude')) {
@@ -407,7 +409,7 @@ async function uninstallAllUnlocked() {
407
409
  await require('../../scripts/setup-antigravity-service.cjs').uninstall();
408
410
  await require('../../scripts/setup-claude-service.cjs').uninstall();
409
411
  disableCodexMcp({});
410
- disableAntigravityMcp();
412
+ disableAntigravityMcp({ homeDirectory: home });
411
413
  disableClaudeMcp();
412
414
  const agyPluginDir = path.join(home, '.gemini/config/plugins/things');
413
415
  if (fs.existsSync(agyPluginDir)) {
@@ -127,9 +127,15 @@
127
127
  const prevShadow = bubble.style.boxShadow;
128
128
  const prevTransition = bubble.style.transition;
129
129
 
130
- bubble.style.transition = 'all 0.25s ease';
131
- bubble.style.outline = '2px solid #0169cc';
132
- bubble.style.boxShadow = '0 0 0 4px rgba(1, 105, 204, 0.25), 0 8px 24px rgba(1, 105, 204, 0.35)';
130
+ let accentHex = '#2F75C3';
131
+ try {
132
+ const rootAccent = getComputedStyle(document.documentElement).getPropertyValue('--primary').trim();
133
+ if (rootAccent) accentHex = rootAccent;
134
+ } catch (_) {}
135
+
136
+ bubble.style.transition = 'outline-color 200ms cubic-bezier(0.23, 1, 0.32, 1), box-shadow 200ms cubic-bezier(0.23, 1, 0.32, 1)';
137
+ bubble.style.outline = `2px solid ${accentHex}`;
138
+ bubble.style.boxShadow = `0 0 0 4px color-mix(in srgb, ${accentHex} 25%, transparent), 0 8px 24px color-mix(in srgb, ${accentHex} 35%, transparent)`;
133
139
 
134
140
  setTimeout(() => {
135
141
  bubble.style.outline = prevOutline;
@@ -202,9 +208,10 @@
202
208
 
203
209
  const seen = new Set();
204
210
  const queue = [rootFiber];
211
+ let head = 0;
205
212
  let steps = 0;
206
- while (queue.length && steps++ < 6000) {
207
- const node = queue.shift();
213
+ while (head < queue.length && steps++ < 20000) {
214
+ const node = queue[head++];
208
215
  if (!node || seen.has(node)) continue;
209
216
  seen.add(node);
210
217
  const mp = node.memoizedProps;
@@ -274,33 +281,86 @@
274
281
  }
275
282
  }
276
283
 
284
+ function isThingsSidecarOpenInStore(store, convId) {
285
+ if (!store?.getState) return null;
286
+ try {
287
+ const st = store.getState();
288
+ const paneV1 = convId ? st?.sidePanel?.conversationPanes?.[convId] : st?.sidePanel?.homePane;
289
+ const paneV2 = convId ? st?.sidePanelV2?.conversationPanes?.[convId] : st?.sidePanelV2?.homePane;
290
+ const activeTabId = paneV2?.activeTabId ?? paneV1?.activeTabId ?? '';
291
+ if (paneV1?.isPaneOpen === true && typeof activeTabId === 'string' && activeTabId.startsWith(`sidecar__${THINGS_SIDECAR_ID}__`)) {
292
+ return true;
293
+ }
294
+ if (paneV1 || paneV2) return false;
295
+ } catch (_) {}
296
+ return null;
297
+ }
298
+
277
299
  function isThingsSidecarOpen(store, convId) {
278
- if (store?.getState) {
279
- try {
280
- const st = store.getState();
281
- const paneV1 = convId ? st?.sidePanel?.conversationPanes?.[convId] : st?.sidePanel?.homePane;
282
- const paneV2 = convId ? st?.sidePanelV2?.conversationPanes?.[convId] : st?.sidePanelV2?.homePane;
283
- const activeTabId = paneV2?.activeTabId ?? paneV1?.activeTabId ?? '';
284
- if (paneV1?.isPaneOpen === true && typeof activeTabId === 'string' && activeTabId.startsWith(`sidecar__${THINGS_SIDECAR_ID}__`)) {
285
- return true;
286
- }
287
- } catch (_) {}
288
- }
300
+ const storeResult = isThingsSidecarOpenInStore(store, convId);
301
+ if (storeResult !== null) return storeResult;
289
302
  if (typeof document !== 'undefined') {
290
303
  const slot = document.querySelector(`[data-testid="sidecar-iframe-slot"][data-sidecar-id="${THINGS_SIDECAR_ID}"][data-visible="true"]`);
291
304
  if (slot && typeof slot.getBoundingClientRect === 'function' && slot.getBoundingClientRect().width > 0) {
292
- return true;
305
+ const slotUrl = slot.getAttribute?.('data-sidecar-url') || '';
306
+ if (!slotUrl || !convId || slotUrl.includes(`conversationId=${convId}`)) {
307
+ return true;
308
+ }
293
309
  }
294
310
  const frames = document.querySelectorAll('iframe[data-testid="sidecar-iframe"]');
295
311
  for (const frame of frames) {
296
312
  if (frame.src?.includes('things--things_board') && typeof frame.getBoundingClientRect === 'function' && frame.getBoundingClientRect().width > 0) {
297
- return true;
313
+ if (!convId || !frame.src.includes('conversationId=') || frame.src.includes(`conversationId=${convId}`)) {
314
+ return true;
315
+ }
298
316
  }
299
317
  }
300
318
  }
301
319
  return false;
302
320
  }
303
321
 
322
+ function openViaReduxBridge(bridge, descriptor, activeConvId, { avoidReload = true } = {}) {
323
+ const targetUrl = buildConversationSidecarUrl(descriptor.baseViewUrl, activeConvId);
324
+ if (avoidReload && typeof bridge.sidecarPool?.setIframeSrc === 'function') {
325
+ bridge.sidecarPool.setIframeSrc(targetUrl, targetUrl);
326
+ } else if (typeof bridge.sidecarPool?.navigateIframe === 'function') {
327
+ bridge.sidecarPool.navigateIframe(descriptor.baseViewUrl, targetUrl);
328
+ } else if (typeof bridge.sidecarPool?.setIframeSrc === 'function') {
329
+ bridge.sidecarPool.setIframeSrc(targetUrl, targetUrl);
330
+ }
331
+ const treeId = activeConvId ? { kind: 'cascadeId', cascadeId: activeConvId } : { kind: 'home' };
332
+ const st = bridge.store.getState();
333
+ const setContentType = st?.sidePanelV2 ? 'sidePanelV2/setContent' : 'sidePanel/setContent';
334
+ bridge.store.dispatch({
335
+ type: setContentType,
336
+ payload: {
337
+ treeId,
338
+ content: {
339
+ type: 'sidecarView',
340
+ sidecarView: {
341
+ sidecarId: descriptor.sidecarId,
342
+ path: descriptor.path,
343
+ url: descriptor.baseViewUrl,
344
+ title: descriptor.title,
345
+ },
346
+ },
347
+ tabId: descriptor.tabId,
348
+ },
349
+ });
350
+ bridge.store.dispatch({
351
+ type: 'sidePanel/setSidePanelOpen',
352
+ payload: { treeId, isOpen: true },
353
+ });
354
+ if (typeof bridge.router?.navigate === 'function') {
355
+ try {
356
+ bridge.router.navigate({
357
+ search: prev => ({ ...(prev || {}), tab: descriptor.tabId }),
358
+ replace: true,
359
+ });
360
+ } catch (_) {}
361
+ }
362
+ }
363
+
304
364
  async function tryOpenViaDomFallback() {
305
365
  if (typeof document === 'undefined') return;
306
366
  const toggleBtn = document.querySelector('[data-testid="toggle-aux-sidebar"]');
@@ -373,6 +433,20 @@
373
433
  throw new Error(getUiText(null, 'Things sidebar plugin is not enabled. Enable it in Plugins Manager first.', 'Things 侧边栏插件未启用,请先在 Plugins Manager 中启用 Things 插件'));
374
434
  }
375
435
 
436
+ if (isThingsSidecarOpen(bridge.store, activeConvId)) {
437
+ syncSidecarConversation(activeConvId);
438
+ return { ok: true, method: 'alreadyOpen', conversationId: activeConvId };
439
+ }
440
+
441
+ if (descriptor && bridge.store?.dispatch && typeof bridge.sidecarPool?.setIframeSrc === 'function') {
442
+ openViaReduxBridge(bridge, descriptor, activeConvId, { avoidReload: true });
443
+ await waitMs(80);
444
+ if (isThingsSidecarOpen(bridge.store, activeConvId)) {
445
+ syncSidecarConversation(activeConvId);
446
+ return { ok: true, method: 'reduxStore', conversationId: activeConvId };
447
+ }
448
+ }
449
+
376
450
  if (bridge.onSidecarLinkClick) {
377
451
  bridge.onSidecarLinkClick(THINGS_SIDECAR_ID);
378
452
  await waitMs(80);
@@ -383,43 +457,7 @@
383
457
  }
384
458
 
385
459
  if (descriptor && bridge.store?.dispatch) {
386
- const targetUrl = buildConversationSidecarUrl(descriptor.baseViewUrl, activeConvId);
387
- if (typeof bridge.sidecarPool?.navigateIframe === 'function') {
388
- bridge.sidecarPool.navigateIframe(descriptor.baseViewUrl, targetUrl);
389
- } else if (typeof bridge.sidecarPool?.setIframeSrc === 'function') {
390
- bridge.sidecarPool.setIframeSrc(descriptor.baseViewUrl, targetUrl);
391
- }
392
- const treeId = activeConvId ? { kind: 'cascadeId', cascadeId: activeConvId } : { kind: 'home' };
393
- const st = bridge.store.getState();
394
- const setContentType = st?.sidePanelV2 ? 'sidePanelV2/setContent' : 'sidePanel/setContent';
395
- bridge.store.dispatch({
396
- type: setContentType,
397
- payload: {
398
- treeId,
399
- content: {
400
- type: 'sidecarView',
401
- sidecarView: {
402
- sidecarId: descriptor.sidecarId,
403
- path: descriptor.path,
404
- url: descriptor.baseViewUrl,
405
- title: descriptor.title,
406
- },
407
- },
408
- tabId: descriptor.tabId,
409
- },
410
- });
411
- bridge.store.dispatch({
412
- type: 'sidePanel/setSidePanelOpen',
413
- payload: { treeId, isOpen: true },
414
- });
415
- if (typeof bridge.router?.navigate === 'function') {
416
- try {
417
- bridge.router.navigate({
418
- search: prev => ({ ...(prev || {}), tab: descriptor.tabId }),
419
- replace: true,
420
- });
421
- } catch (_) {}
422
- }
460
+ openViaReduxBridge(bridge, descriptor, activeConvId, { avoidReload: false });
423
461
  await waitMs(80);
424
462
  if (isThingsSidecarOpen(bridge.store, activeConvId)) {
425
463
  syncSidecarConversation(activeConvId);
@@ -962,7 +1000,7 @@
962
1000
  type: data.type === 'AGENT_THINGS_AUTH_REQUEST' ? 'AGENT_THINGS_AUTH_RESPONSE' : 'AGENT_THINGS_ACTION_RESULT',
963
1001
  nonce: data.nonce,
964
1002
  success: false,
965
- error: getUiText(null, 'Session identity mismatch: cross-session action blocked', '会话身份不匹配:禁止跨会话操作'),
1003
+ error: '会话身份不匹配:禁止跨会话操作',
966
1004
  });
967
1005
  return;
968
1006
  }
@@ -1025,14 +1063,21 @@
1025
1063
  if (reply.snapshot) {
1026
1064
  window.__codexSessionStatus?.receive?.(reply.snapshot);
1027
1065
  }
1028
- const targetRecord = reply.snapshot?.records?.[key];
1029
- const sessionData = targetRecord ? {
1066
+ const targetRecord = reply.snapshot?.records?.[key] || null;
1067
+ const targetAnalysis = reply.snapshot?.analysis?.[key] || null;
1068
+ const analysisTasks = Array.isArray(targetAnalysis?.ledger?.tasks) ? targetAnalysis.ledger.tasks : null;
1069
+ const analysisSummary = targetAnalysis?.ledger?.summary || '';
1070
+ const sessionData = {
1030
1071
  conversationId: boundConvId,
1031
- recordRevision: targetRecord.revision ?? 0,
1032
- progress: targetRecord.progress ?? null,
1033
- state: targetRecord.state ?? null,
1034
- note: targetRecord.note ?? '',
1035
- } : null;
1072
+ recordRevision: targetRecord?.revision ?? 0,
1073
+ progress: targetRecord ? (targetRecord.progress ?? null) : null,
1074
+ state: targetRecord ? (targetRecord.state ?? null) : 'unstarted',
1075
+ note: targetRecord ? (targetRecord.note ?? '') : '',
1076
+ source: targetRecord?.source || (targetAnalysis ? 'analysis' : 'manual'),
1077
+ updatedAt: targetRecord?.updatedAt || new Date().toISOString(),
1078
+ summary: (targetRecord?.note || analysisSummary) ?? '',
1079
+ ...(analysisTasks ? { tasks: analysisTasks } : {}),
1080
+ };
1036
1081
  sendReplyToCard(binding, targetPort, {
1037
1082
  type: 'AGENT_THINGS_ACTION_RESULT',
1038
1083
  nonce,
@@ -1049,7 +1094,7 @@
1049
1094
  nonce,
1050
1095
  action,
1051
1096
  success: false,
1052
- error: err.message || getUiText(null, 'Proxy request failed', '代理请求失败'),
1097
+ error: err.message || '代理请求失败',
1053
1098
  });
1054
1099
  }
1055
1100
  return;
@@ -1071,7 +1116,7 @@
1071
1116
  action: 'locate',
1072
1117
  success: Boolean(result?.located),
1073
1118
  data: result,
1074
- error: result?.located ? undefined : (result?.message || getUiText(null, 'Source message not found', '未找到来源消息')),
1119
+ error: result?.located ? undefined : (result?.message || '未找到来源消息'),
1075
1120
  });
1076
1121
  }
1077
1122
  } catch (err) {
@@ -1081,7 +1126,7 @@
1081
1126
  nonce,
1082
1127
  action: 'locate',
1083
1128
  success: false,
1084
- error: err?.message || getUiText(null, 'Failed to locate source', '定位来源失败'),
1129
+ error: err?.message || '定位来源失败',
1085
1130
  });
1086
1131
  }
1087
1132
  }
@@ -1109,7 +1154,7 @@
1109
1154
  nonce,
1110
1155
  action: 'open-pane',
1111
1156
  success: false,
1112
- error: err?.message || getUiText(null, 'Failed to open the sidebar plugin', '打开侧栏插件失败'),
1157
+ error: err?.message || '打开侧栏插件失败',
1113
1158
  });
1114
1159
  }
1115
1160
  }
@@ -1290,14 +1335,21 @@
1290
1335
  }
1291
1336
  const rawContent = String(val);
1292
1337
  const isCard = rawContent.includes('AGENT_THINGS_AUTH_REQUEST') || rawContent.includes('agentThingsCard');
1293
- const isInAux = !!iframe.closest?.('[data-testid="aux-pane-split"]') || iframe.getAttribute('data-testid') === 'artifact-dynamic-ui-iframe';
1338
+ const testId = iframe.getAttribute?.('data-testid');
1339
+ // 主对话气泡内的 <agent-embed> 会随右侧栏开启而整体位于 aux-pane-split 容器下,不能误按右侧独立工件 Tab 拦截
1340
+ const agentEmbedAncestor = iframe.closest?.('[data-testid="agent-embed"]');
1341
+ const auxSplitAncestor = iframe.closest?.('[data-testid="aux-pane-split"]');
1342
+ const hasDistinctEmbedAncestor = !!agentEmbedAncestor && agentEmbedAncestor !== auxSplitAncestor;
1343
+ const isInlineEmbed = testId === 'agent-embed-iframe'
1344
+ || (hasDistinctEmbedAncestor && testId !== 'artifact-dynamic-ui-iframe');
1345
+ const isInAux = !isInlineEmbed && (!!auxSplitAncestor || testId === 'artifact-dynamic-ui-iframe');
1294
1346
  let currentTab = '';
1295
1347
  try { currentTab = new URL(window.location.href).searchParams.get('tab') || ''; } catch (_) {}
1296
1348
  const isCardTab = currentTab.includes('things-card.html');
1297
1349
 
1298
1350
  if (isCard && (isInAux ? isCardTab : true)) {
1299
1351
  let tabConvId = null;
1300
- if (isCardTab) {
1352
+ if (isInAux && isCardTab) {
1301
1353
  try {
1302
1354
  const match = currentTab.match(/[/\\\\]([^/\\\\]+)[/\\\\]things-card\.html/i) || currentTab.match(/([^/]+)\/things-card\.html/i);
1303
1355
  if (match) tabConvId = match[1];
@@ -1335,7 +1387,7 @@
1335
1387
 
1336
1388
  // 检查工件文档边界与恶意追加:
1337
1389
  // 若为独立 HTML(非官方外层包装模板),必须严格等于 fullDoc;在 </html> 后追加任何脚本均视为非法篡改
1338
- const isOfficialWrapper = rawContent.startsWith('<!DOCTYPE html><html class="dark"><head><meta http-equiv="Content-Security-Policy"');
1390
+ const isOfficialWrapper = /^<!DOCTYPE html><html class="(?:dark|light)"><head><meta http-equiv="Content-Security-Policy"/.test(rawContent);
1339
1391
  if (!isOfficialWrapper && rawContent.trim() !== fullDoc.trim()) {
1340
1392
  return originalSet.call(iframe, val);
1341
1393
  }
@@ -1346,7 +1398,7 @@
1346
1398
  // Hold the document until verification completes; no card script runs while awaiting the service.
1347
1399
  return (async () => {
1348
1400
  const isCurrent = () => pendingCardLoads.get(iframe) === controller && !controller.signal.aborted
1349
- && iframe.isConnected && (isCardTab ? new URL(window.location.href).searchParams.get('tab') === currentTab : true);
1401
+ && iframe.isConnected && (isInAux && isCardTab ? new URL(window.location.href).searchParams.get('tab') === currentTab : true);
1350
1402
  let verifiedDigest;
1351
1403
  try {
1352
1404
  const response = await fetch(`${getServiceOrigin()}/session/verify-artifact`, {
@@ -1364,7 +1416,7 @@
1364
1416
  } catch (_) {
1365
1417
  // An explicit replacement/disposal must never reinstall an obsolete document.
1366
1418
  if (pendingCardLoads.get(iframe) === controller && iframe.isConnected
1367
- && (isCardTab ? new URL(window.location.href).searchParams.get('tab') === currentTab : true)) originalSet.call(iframe, val);
1419
+ && (isInAux && isCardTab ? new URL(window.location.href).searchParams.get('tab') === currentTab : true)) originalSet.call(iframe, val);
1368
1420
  return;
1369
1421
  } finally { clearTimeout(timeout); }
1370
1422
 
@@ -1384,12 +1436,46 @@
1384
1436
  })) return originalSet.call(iframe, val);
1385
1437
 
1386
1438
  // 以通过校验的工件内容 fullDoc 为唯一渲染输入,彻底剔除外部未经验证的追加字符与脚本
1387
- const tokenScript = '<script>window.__agentThingsLoadToken = ' + JSON.stringify(dynamicToken) + ';</' + 'script>';
1439
+ let hostAccent = '';
1440
+ let hostAccentFg = '';
1441
+ let hostMode = '';
1442
+ try {
1443
+ const rs = getComputedStyle(document.documentElement);
1444
+ hostAccent = rs.getPropertyValue('--primary').trim();
1445
+ hostAccentFg = rs.getPropertyValue('--primary-foreground').trim();
1446
+ if (document.body?.classList?.contains('theme-light')) hostMode = 'light';
1447
+ else if (document.body?.classList?.contains('theme-dark')) hostMode = 'dark';
1448
+ else {
1449
+ const bg = rs.getPropertyValue('--background').trim();
1450
+ if (bg) {
1451
+ if (bg.startsWith('#') && bg.length >= 7) {
1452
+ const r = parseInt(bg.slice(1, 3), 16), g = parseInt(bg.slice(3, 5), 16), b = parseInt(bg.slice(5, 7), 16);
1453
+ hostMode = (0.299 * r + 0.587 * g + 0.114 * b) > 130 ? 'light' : 'dark';
1454
+ } else if (bg.startsWith('rgb')) {
1455
+ const m = bg.match(/\d+/g);
1456
+ if (m && m.length >= 3) hostMode = (0.299 * m[0] + 0.587 * m[1] + 0.114 * m[2]) > 130 ? 'light' : 'dark';
1457
+ }
1458
+ }
1459
+ }
1460
+ } catch (_) {}
1461
+ const tokenScript = '<script>window.__agentThingsLoadToken = ' + JSON.stringify(dynamicToken) + ';'
1462
+ + (hostAccent ? 'window.__agentThingsHostAccent = ' + JSON.stringify(hostAccent) + ';' : '')
1463
+ + (hostAccentFg ? 'window.__agentThingsHostAccentFg = ' + JSON.stringify(hostAccentFg) + ';' : '')
1464
+ + (hostMode ? 'window.__agentThingsHostTheme = ' + JSON.stringify(hostMode) + ';' : '')
1465
+ + '</' + 'script>';
1388
1466
  let modifiedHtml = fullDoc;
1389
1467
  // 彻底清理之前注入过的所有 loadToken 脚本(兼容普通与转义关闭标签)
1390
1468
  modifiedHtml = modifiedHtml
1391
1469
  .replace(/<script[^>]*>window\.__agentThingsLoadToken[\s\S]*?<\/script>/gi, '')
1392
1470
  .replace(/<script[^>]*>window\.__agentThingsLoadToken[\s\S]*?<\\\/script>/gi, '');
1471
+ if (hostMode) {
1472
+ modifiedHtml = modifiedHtml.replace(/<html\b([^>]*)>/i, (_, attrs) => {
1473
+ const cleaned = attrs
1474
+ .replace(/\s+data-color-mode\s*=\s*["'][^"']*["']/gi, '')
1475
+ .replace(/\s+style\s*=\s*["']color-scheme:[^"']*["']/gi, '');
1476
+ return '<html data-color-mode="' + hostMode + '" style="color-scheme:' + hostMode + '"' + cleaned + '>';
1477
+ });
1478
+ }
1393
1479
  if (modifiedHtml.includes('<head>')) {
1394
1480
  modifiedHtml = modifiedHtml.replace('<head>', '<head>' + tokenScript);
1395
1481
  } else {