agent-things 0.0.0-stage → 1.2.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.
- package/LICENSE +21 -0
- package/NOTICE +5 -0
- package/README.md +221 -2
- package/README.zh-CN.md +222 -0
- package/bin/agent-things.cjs +8 -0
- package/bin/antigravity-session-status.cjs +96 -0
- package/bin/claude-session-status.cjs +55 -0
- package/bin/codex-session-status.cjs +287 -0
- package/mods/agent-things-ui/.claude-plugin/plugin.json +12 -0
- package/mods/agent-things-ui/SKILL.md +10 -0
- package/mods/agent-things-ui/hooks/controls.js +112 -0
- package/mods/agent-things-ui/hooks/foundation.js +431 -0
- package/mods/agent-things-ui/hooks/hooks.json +1 -0
- package/mods/agent-things-ui/hooks/presentation.js +223 -0
- package/mods/agent-things-ui/hooks/progress.js +1 -0
- package/mods/agent-things-ui/hooks/register.js +382 -0
- package/native/bin/bridge +0 -0
- package/native/bin/bridge.json +20 -0
- package/native/session-status-bridge.swift +280 -0
- package/outputs/antigravity-session-status.js +2476 -0
- package/outputs/codex-session-status.js +1761 -0
- package/package.json +75 -4
- package/scripts/build-antigravity-bundle.cjs +35 -0
- package/scripts/build-codex-bundle.cjs +31 -0
- package/scripts/build-native-bridge.cjs +55 -0
- package/scripts/build-shared-ui.cjs +16 -0
- package/scripts/setup-antigravity-service.cjs +71 -0
- package/scripts/setup-claude-service.cjs +21 -0
- package/skills/agent-things/SKILL.en.md +95 -0
- package/skills/agent-things/SKILL.md +99 -0
- package/skills/codex/things/SKILL.en.md +10 -0
- package/skills/codex/things/SKILL.md +10 -0
- package/skills/things/SKILL.en.md +10 -0
- package/skills/things/SKILL.md +10 -0
- package/skills/things/checklist.en.md +91 -0
- package/skills/things/checklist.md +95 -0
- package/src/analysis-app-server.cjs +74 -0
- package/src/analysis-assets/output.en.schema.json +93 -0
- package/src/analysis-assets/output.schema.json +93 -0
- package/src/analysis-assets/prompt.en.txt +17 -0
- package/src/analysis-assets/prompt.zh-CN.txt +18 -0
- package/src/analysis-budget.cjs +105 -0
- package/src/analysis-git.cjs +38 -0
- package/src/analysis-history.cjs +150 -0
- package/src/analysis-ledger.cjs +82 -0
- package/src/analysis-log.cjs +62 -0
- package/src/analysis-runner.cjs +203 -0
- package/src/analysis-service.cjs +197 -0
- package/src/analysis-source.cjs +72 -0
- package/src/antigravity-card.cjs +2063 -0
- package/src/antigravity-hook.cjs +138 -0
- package/src/antigravity-mcp-config.cjs +36 -0
- package/src/app-server.cjs +96 -0
- package/src/cdp.cjs +115 -0
- package/src/claude-inline-install.cjs +38 -0
- package/src/claude-mcp-config.cjs +29 -0
- package/src/cli/arguments.cjs +30 -0
- package/src/cli/environment-probe.cjs +130 -0
- package/src/cli/integration-state.cjs +15 -0
- package/src/cli/interactive-cli.cjs +236 -0
- package/src/cli/prompt-tui.cjs +420 -0
- package/src/cli/setup-orchestrator.cjs +449 -0
- package/src/codex-mcp-config.cjs +67 -0
- package/src/harnesses/antigravity/analysis-profile.cjs +41 -0
- package/src/harnesses/antigravity/antigravity-git.cjs +89 -0
- package/src/harnesses/antigravity/antigravity-harness.js +1477 -0
- package/src/harnesses/antigravity/antigravity-injector.cjs +104 -0
- package/src/harnesses/antigravity/antigravity-migration.cjs +235 -0
- package/src/harnesses/antigravity/antigravity-service.cjs +357 -0
- package/src/harnesses/antigravity/antigravity-title.cjs +155 -0
- package/src/harnesses/antigravity/gemini-runner.cjs +304 -0
- package/src/harnesses/antigravity/transcript-cleaner.cjs +129 -0
- package/src/harnesses/antigravity/transcript-source.cjs +100 -0
- package/src/harnesses/claude/claude-harness.js +93 -0
- package/src/harnesses/claude/claude-host-helper.cjs +176 -0
- package/src/harnesses/claude/claude-injector.cjs +95 -0
- package/src/harnesses/claude/claude-local-source.cjs +106 -0
- package/src/harnesses/claude/claude-navigation.cjs +99 -0
- package/src/harnesses/claude/claude-runner.cjs +74 -0
- package/src/harnesses/claude/claude-service.cjs +313 -0
- package/src/harnesses/claude/claude-source.cjs +70 -0
- package/src/harnesses/codex/codex-analysis.cjs +10 -0
- package/src/harnesses/codex/codex-card-bridge.js +123 -0
- package/src/harnesses/codex/codex-card-events.cjs +76 -0
- package/src/harnesses/codex/codex-card.cjs +169 -0
- package/src/harnesses/codex/codex-git.cjs +24 -0
- package/src/harnesses/codex/codex-harness.js +229 -0
- package/src/harnesses/codex/codex-local-card.js +97 -0
- package/src/harnesses/codex/codex-progress-context.cjs +84 -0
- package/src/harnesses/codex/codex-service.cjs +502 -0
- package/src/i18n.cjs +174 -0
- package/src/launchd.cjs +105 -0
- package/src/lifecycle-lock.cjs +13 -0
- package/src/local-progress-http.cjs +267 -0
- package/src/manual-status-agent.cjs +12 -0
- package/src/manual-status-startup.cjs +66 -0
- package/src/manual-status-store.cjs +466 -0
- package/src/mcp-stdio.cjs +67 -0
- package/src/model-router.cjs +63 -0
- package/src/native-bridge.cjs +17 -0
- package/src/npm-updates.cjs +228 -0
- package/src/plugins/things/assets/logo.svg +13 -0
- package/src/plugins/things/plugin.json +6 -0
- package/src/plugins/things/sidecars/things_board/app.js +447 -0
- package/src/plugins/things/sidecars/things_board/index.html +2141 -0
- package/src/plugins/things/sidecars/things_board/main.mjs +652 -0
- package/src/plugins/things/sidecars/things_board/package.json +6 -0
- package/src/plugins/things/sidecars/things_board/sidecar.json +21 -0
- package/src/plugins/things/sidecars/things_board/styles.css +560 -0
- package/src/plugins/things/sidecars/things_board/ui-i18n.mjs +434 -0
- package/src/progress-error.cjs +54 -0
- package/src/progress-tools.cjs +145 -0
- package/src/project-path.cjs +15 -0
- package/src/renderer-resource.cjs +17 -0
- package/src/request-budget.cjs +24 -0
- package/src/resolve.cjs +51 -0
- package/src/runtime-install.cjs +635 -0
- package/src/session-status-filter.cjs +136 -0
- package/src/session-status.js +992 -0
- package/src/session-view.cjs +34 -0
- package/src/startup/controller.cjs +354 -0
- package/src/startup/watch.cjs +126 -0
- package/src/state-file-lock.cjs +31 -0
- package/src/task-provenance.cjs +42 -0
- package/src/ui-foundation.cjs +435 -0
|
@@ -0,0 +1,2476 @@
|
|
|
1
|
+
// Antigravity Session Status Bundle (Auto-generated)
|
|
2
|
+
// Zero-friction embedded panel for Antigravity
|
|
3
|
+
|
|
4
|
+
'use strict';
|
|
5
|
+
(function () {
|
|
6
|
+
const connection = window.__agentThingsConnection;
|
|
7
|
+
const SERVICE_ORIGIN = connection.origin;
|
|
8
|
+
const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${connection.token}` };
|
|
9
|
+
const getServiceOrigin = () => window.__agentThingsConnection?.origin || SERVICE_ORIGIN;
|
|
10
|
+
const getServiceHeaders = () => {
|
|
11
|
+
const conn = window.__agentThingsConnection;
|
|
12
|
+
if (conn?.token) return { 'Content-Type': 'application/json', Authorization: `Bearer ${conn.token}` };
|
|
13
|
+
return headers;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const THINGS_SIDECAR_ID = 'things/things_board';
|
|
17
|
+
const THINGS_SIDECAR_DEFAULT_PATH = '/';
|
|
18
|
+
const waitMs = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
19
|
+
const getUiText = (key, enFallback, zhFallback) => {
|
|
20
|
+
const p = window.__agentThingsPresentation;
|
|
21
|
+
const lang = window.__agentThingsConnection?.lang || window.__agentThingsLang || p?.lang || 'zh';
|
|
22
|
+
if (key) {
|
|
23
|
+
const ui = p?.forLang ? p.forLang(lang) : null;
|
|
24
|
+
const val = ui?.strings?.[key] ?? p?.strings?.[key];
|
|
25
|
+
if (val) return val;
|
|
26
|
+
}
|
|
27
|
+
return lang === 'en' ? enFallback : (zhFallback || enFallback);
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function normalizeLocatorText(text) {
|
|
31
|
+
return String(text || '')
|
|
32
|
+
.replace(/```[\s\S]*?```/g, m => m.replace(/```[^\n]*\n?/g, '').replace(/```/g, ''))
|
|
33
|
+
.replace(/`([^`]*)`/g, '$1')
|
|
34
|
+
.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
35
|
+
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
|
|
36
|
+
.replace(/[*_~]{1,3}([^*_~]+)[*_~]{1,3}/g, '$1')
|
|
37
|
+
.replace(/^#{1,6}\s+/gm, '')
|
|
38
|
+
.replace(/\s+/g, ' ')
|
|
39
|
+
.trim();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function findSourceMessageElement(viewport, source) {
|
|
43
|
+
if (!viewport || !source) return null;
|
|
44
|
+
const quote = normalizeLocatorText(source.locator);
|
|
45
|
+
const containers = [...viewport.querySelectorAll('[data-testid="user-input-step"], [data-testid="agent-response"]')];
|
|
46
|
+
|
|
47
|
+
if (quote) {
|
|
48
|
+
let matchedContainer = null;
|
|
49
|
+
for (const container of containers) {
|
|
50
|
+
if (normalizeLocatorText(container.textContent).includes(quote)) {
|
|
51
|
+
matchedContainer = container;
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (!matchedContainer && quote.length >= 28) {
|
|
57
|
+
const head = quote.slice(0, 22);
|
|
58
|
+
const tail = quote.slice(-18);
|
|
59
|
+
matchedContainer = containers.find(container => {
|
|
60
|
+
const text = normalizeLocatorText(container.textContent);
|
|
61
|
+
return text.includes(head) && text.includes(tail);
|
|
62
|
+
}) || null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (matchedContainer) {
|
|
66
|
+
if (matchedContainer.getAttribute?.('data-testid') === 'user-input-step') {
|
|
67
|
+
return matchedContainer.querySelector?.('[data-testid="user-message-bubble"]') || matchedContainer;
|
|
68
|
+
}
|
|
69
|
+
const innerCandidates = [...(matchedContainer.querySelectorAll?.(
|
|
70
|
+
'[data-testid="user-message-bubble"], p, li, pre, blockquote, h1, h2, h3, h4, h5, h6, td, [data-content-search-unit-key], [data-step-id]'
|
|
71
|
+
) || [])];
|
|
72
|
+
const anchorNeedle = quote.length >= 24 ? quote.slice(0, 24) : quote;
|
|
73
|
+
let innerMatch = null;
|
|
74
|
+
for (const el of innerCandidates) {
|
|
75
|
+
const norm = normalizeLocatorText(el.textContent);
|
|
76
|
+
if (norm.includes(quote) || (anchorNeedle.length >= 16 && norm.includes(anchorNeedle))) {
|
|
77
|
+
innerMatch = el;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return innerMatch || matchedContainer;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (source.turnId) {
|
|
85
|
+
const index = Number(source.turnId);
|
|
86
|
+
const userSteps = [...viewport.querySelectorAll('[data-testid="user-input-step"]')];
|
|
87
|
+
if (Number.isInteger(index) && index > 0 && index <= userSteps.length) {
|
|
88
|
+
const step = userSteps[index - 1];
|
|
89
|
+
return step.querySelector?.('[data-testid="user-message-bubble"]') || step;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function clickNavigatorForTurn(turnNumber) {
|
|
96
|
+
if (typeof document === 'undefined' || !Number.isInteger(turnNumber) || turnNumber < 1) {
|
|
97
|
+
return { clickedExactTurn: false, clickedChapter: false };
|
|
98
|
+
}
|
|
99
|
+
const turnIdx = turnNumber - 1;
|
|
100
|
+
const exactTurnBtn = document.querySelector(`[data-testid="conversation-navigator-turn"][data-turn-index="${turnIdx}"]`);
|
|
101
|
+
if (exactTurnBtn) {
|
|
102
|
+
exactTurnBtn.click();
|
|
103
|
+
return { clickedExactTurn: true, clickedChapter: false };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const groups = [...document.querySelectorAll('[data-testid="conversation-navigator-group"]')];
|
|
107
|
+
let offset = 0;
|
|
108
|
+
for (const groupBtn of groups) {
|
|
109
|
+
const label = groupBtn.getAttribute('aria-label') || '';
|
|
110
|
+
const countMatch = label.match(/(\d+)\s*turns?\b/i);
|
|
111
|
+
const count = countMatch ? Number(countMatch[1]) : 0;
|
|
112
|
+
if (count > 0) {
|
|
113
|
+
if (turnNumber >= offset + 1 && turnNumber <= offset + count) {
|
|
114
|
+
groupBtn.click();
|
|
115
|
+
return { clickedExactTurn: false, clickedChapter: true };
|
|
116
|
+
}
|
|
117
|
+
offset += count;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return { clickedExactTurn: false, clickedChapter: false };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function highlightLocatedElement(targetEl) {
|
|
124
|
+
if (!targetEl) return;
|
|
125
|
+
const bubble = targetEl.querySelector?.('[data-testid="user-message-bubble"]') || targetEl;
|
|
126
|
+
bubble.scrollIntoView?.({ block: 'center', behavior: 'smooth' });
|
|
127
|
+
|
|
128
|
+
if (!bubble.style) return;
|
|
129
|
+
const prevOutline = bubble.style.outline;
|
|
130
|
+
const prevShadow = bubble.style.boxShadow;
|
|
131
|
+
const prevTransition = bubble.style.transition;
|
|
132
|
+
|
|
133
|
+
bubble.style.transition = 'all 0.25s ease';
|
|
134
|
+
bubble.style.outline = '2px solid #0169cc';
|
|
135
|
+
bubble.style.boxShadow = '0 0 0 4px rgba(1, 105, 204, 0.25), 0 8px 24px rgba(1, 105, 204, 0.35)';
|
|
136
|
+
|
|
137
|
+
setTimeout(() => {
|
|
138
|
+
bubble.style.outline = prevOutline;
|
|
139
|
+
bubble.style.boxShadow = prevShadow;
|
|
140
|
+
bubble.style.transition = prevTransition;
|
|
141
|
+
}, 3500);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function findSidebarRowByCascadeId(cascadeId) {
|
|
145
|
+
if (!cascadeId || typeof document === 'undefined') return null;
|
|
146
|
+
const rows = document.querySelectorAll('.agy-sidebar-row[data-cascade-id]');
|
|
147
|
+
for (const row of rows) {
|
|
148
|
+
if (row.getAttribute('data-cascade-id') === cascadeId) return row;
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function extractSidebarRowTitle(row) {
|
|
154
|
+
if (!row || typeof row.querySelector !== 'function') return '';
|
|
155
|
+
const anchor = row.querySelector('a');
|
|
156
|
+
const ariaLabel = typeof anchor?.getAttribute === 'function' ? anchor.getAttribute('aria-label')?.trim() : '';
|
|
157
|
+
if (ariaLabel) return ariaLabel;
|
|
158
|
+
const truncate = row.querySelector('span.truncate')?.textContent?.trim();
|
|
159
|
+
if (truncate) return truncate;
|
|
160
|
+
return '';
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function getConversationTitle(convId) {
|
|
164
|
+
if (typeof document === 'undefined') return '';
|
|
165
|
+
const row = (convId && findSidebarRowByCascadeId(convId))
|
|
166
|
+
|| document.querySelector('.agy-sidebar-row[data-selected="true"]')
|
|
167
|
+
|| document.querySelector('.agy-sidebar-row.bg-sidebar-secondary');
|
|
168
|
+
return extractSidebarRowTitle(row);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function switchConversationIfNeeded(threadId, rowFallback = null, timeoutMs = 4000) {
|
|
172
|
+
if (!threadId) return null;
|
|
173
|
+
const readUrlConvId = () => window.location?.pathname?.split('/')?.filter(Boolean)?.pop() || '';
|
|
174
|
+
if (readUrlConvId() === threadId) return findSidebarRowByCascadeId(threadId) || rowFallback || true;
|
|
175
|
+
|
|
176
|
+
const row = findSidebarRowByCascadeId(threadId) || rowFallback;
|
|
177
|
+
if (!row) throw new Error(getUiText(null, 'Session item not found', '找不到对应的会话项'));
|
|
178
|
+
|
|
179
|
+
if (!harness.isRowSelected(row)) {
|
|
180
|
+
const link = row.querySelector?.('a');
|
|
181
|
+
if (link) link.click();
|
|
182
|
+
else row.click();
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const deadline = Date.now() + timeoutMs;
|
|
186
|
+
while (Date.now() < deadline) {
|
|
187
|
+
const currentRow = findSidebarRowByCascadeId(threadId) || row;
|
|
188
|
+
if (readUrlConvId() === threadId || harness.isRowSelected(currentRow)) {
|
|
189
|
+
await waitMs(120);
|
|
190
|
+
return currentRow;
|
|
191
|
+
}
|
|
192
|
+
await waitMs(80);
|
|
193
|
+
}
|
|
194
|
+
throw new Error(getUiText(null, 'Timed out switching to target session', '切换到目标会话超时'));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function collectReactBridge() {
|
|
198
|
+
const out = { store: null, ext: null, sidecarPool: null, router: null, onSidecarLinkClick: null };
|
|
199
|
+
if (typeof document === 'undefined') return out;
|
|
200
|
+
const rootEl = document.querySelector('#root') || document.body?.firstElementChild;
|
|
201
|
+
if (!rootEl) return out;
|
|
202
|
+
const containerKey = Object.keys(rootEl).find(k => k.startsWith('__reactContainer') || k.startsWith('__reactFiber'));
|
|
203
|
+
const rootFiber = containerKey ? rootEl[containerKey] : null;
|
|
204
|
+
if (!rootFiber) return out;
|
|
205
|
+
|
|
206
|
+
const seen = new Set();
|
|
207
|
+
const queue = [rootFiber];
|
|
208
|
+
let steps = 0;
|
|
209
|
+
while (queue.length && steps++ < 6000) {
|
|
210
|
+
const node = queue.shift();
|
|
211
|
+
if (!node || seen.has(node)) continue;
|
|
212
|
+
seen.add(node);
|
|
213
|
+
const mp = node.memoizedProps;
|
|
214
|
+
if (mp && typeof mp === 'object') {
|
|
215
|
+
if (!out.store && mp.store && typeof mp.store.getState === 'function' && typeof mp.store.dispatch === 'function') {
|
|
216
|
+
out.store = mp.store;
|
|
217
|
+
}
|
|
218
|
+
if (!out.onSidecarLinkClick && typeof mp.onSidecarLinkClick === 'function') {
|
|
219
|
+
out.onSidecarLinkClick = mp.onSidecarLinkClick;
|
|
220
|
+
}
|
|
221
|
+
const ctxVal = mp.value;
|
|
222
|
+
if (ctxVal && typeof ctxVal === 'object') {
|
|
223
|
+
if (!out.ext && typeof ctxVal.get === 'function') {
|
|
224
|
+
try {
|
|
225
|
+
const candidate = ctxVal.get('extensibility');
|
|
226
|
+
if (candidate) out.ext = candidate;
|
|
227
|
+
} catch (_) {}
|
|
228
|
+
}
|
|
229
|
+
if (!out.sidecarPool && (typeof ctxVal.navigateIframe === 'function' || typeof ctxVal.setIframeSrc === 'function')) {
|
|
230
|
+
out.sidecarPool = ctxVal;
|
|
231
|
+
}
|
|
232
|
+
if (!out.router && ctxVal.router && typeof ctxVal.router.navigate === 'function') {
|
|
233
|
+
out.router = ctxVal.router;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (!out.router && mp.router && typeof mp.router.navigate === 'function') {
|
|
237
|
+
out.router = mp.router;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (out.store && out.ext && out.sidecarPool && out.router && out.onSidecarLinkClick) break;
|
|
241
|
+
if (node.child) queue.push(node.child);
|
|
242
|
+
if (node.sibling) queue.push(node.sibling);
|
|
243
|
+
}
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function resolveThingsSidecarDescriptor(ext) {
|
|
248
|
+
const items = ext?.provider?.getState?.();
|
|
249
|
+
if (!Array.isArray(items)) return null;
|
|
250
|
+
const item = items.find(d => d && d.sidecarId === THINGS_SIDECAR_ID);
|
|
251
|
+
if (!item || !item.config?.uiConfig || !item.baseUrl) return null;
|
|
252
|
+
const views = Array.isArray(item.config.uiConfig.views) ? item.config.uiConfig.views : [];
|
|
253
|
+
const view = views.find(v => v && v.entrypoint === 1) || views[0];
|
|
254
|
+
if (!view) return null;
|
|
255
|
+
const viewPath = view.path || THINGS_SIDECAR_DEFAULT_PATH;
|
|
256
|
+
const title = view.title || item.config.uiConfig.displayName || 'Things';
|
|
257
|
+
const baseViewUrl = typeof ext.resolveSidecarUrl === 'function'
|
|
258
|
+
? ext.resolveSidecarUrl(item.baseUrl, viewPath)
|
|
259
|
+
: item.baseUrl;
|
|
260
|
+
return {
|
|
261
|
+
sidecarId: item.sidecarId,
|
|
262
|
+
path: viewPath,
|
|
263
|
+
title,
|
|
264
|
+
baseViewUrl,
|
|
265
|
+
tabId: `sidecar__${item.sidecarId}__${viewPath}`,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function buildConversationSidecarUrl(baseViewUrl, convId) {
|
|
270
|
+
if (!baseViewUrl || !convId) return baseViewUrl;
|
|
271
|
+
try {
|
|
272
|
+
const url = new URL(baseViewUrl);
|
|
273
|
+
url.searchParams.set('conversationId', convId);
|
|
274
|
+
return url.toString();
|
|
275
|
+
} catch (_) {
|
|
276
|
+
return baseViewUrl;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function isThingsSidecarOpen(store, convId) {
|
|
281
|
+
if (store?.getState) {
|
|
282
|
+
try {
|
|
283
|
+
const st = store.getState();
|
|
284
|
+
const paneV1 = convId ? st?.sidePanel?.conversationPanes?.[convId] : st?.sidePanel?.homePane;
|
|
285
|
+
const paneV2 = convId ? st?.sidePanelV2?.conversationPanes?.[convId] : st?.sidePanelV2?.homePane;
|
|
286
|
+
const activeTabId = paneV2?.activeTabId ?? paneV1?.activeTabId ?? '';
|
|
287
|
+
if (paneV1?.isPaneOpen === true && typeof activeTabId === 'string' && activeTabId.startsWith(`sidecar__${THINGS_SIDECAR_ID}__`)) {
|
|
288
|
+
return true;
|
|
289
|
+
}
|
|
290
|
+
} catch (_) {}
|
|
291
|
+
}
|
|
292
|
+
if (typeof document !== 'undefined') {
|
|
293
|
+
const slot = document.querySelector(`[data-testid="sidecar-iframe-slot"][data-sidecar-id="${THINGS_SIDECAR_ID}"][data-visible="true"]`);
|
|
294
|
+
if (slot && typeof slot.getBoundingClientRect === 'function' && slot.getBoundingClientRect().width > 0) {
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
const frames = document.querySelectorAll('iframe[data-testid="sidecar-iframe"]');
|
|
298
|
+
for (const frame of frames) {
|
|
299
|
+
if (frame.src?.includes('things--things_board') && typeof frame.getBoundingClientRect === 'function' && frame.getBoundingClientRect().width > 0) {
|
|
300
|
+
return true;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return false;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function tryOpenViaDomFallback() {
|
|
308
|
+
if (typeof document === 'undefined') return;
|
|
309
|
+
const toggleBtn = document.querySelector('[data-testid="toggle-aux-sidebar"]');
|
|
310
|
+
if (toggleBtn && toggleBtn.getAttribute('aria-expanded') !== 'true') {
|
|
311
|
+
toggleBtn.click();
|
|
312
|
+
await waitMs(150);
|
|
313
|
+
}
|
|
314
|
+
const submenuItem = document.querySelector(`[data-testid="plugins-submenu-item"][data-sidecar-id="${THINGS_SIDECAR_ID}"]`);
|
|
315
|
+
if (submenuItem) {
|
|
316
|
+
submenuItem.click();
|
|
317
|
+
await waitMs(120);
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
const existingTab = [...document.querySelectorAll('[data-testid="aux-pane-split"] [role="tab"]')]
|
|
321
|
+
.find(tab => (tab.textContent || '').trim() === 'Things');
|
|
322
|
+
if (existingTab) {
|
|
323
|
+
existingTab.click();
|
|
324
|
+
await waitMs(120);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const harness = {
|
|
329
|
+
globalName: '__antigravitySessionStatus',
|
|
330
|
+
attributeFilter: ['data-cascade-id', 'class', 'hidden', 'aria-expanded', 'style'],
|
|
331
|
+
|
|
332
|
+
send(payload) {
|
|
333
|
+
fetch(`${getServiceOrigin()}/rpc`, {
|
|
334
|
+
method: 'POST',
|
|
335
|
+
headers: getServiceHeaders(),
|
|
336
|
+
body: payload,
|
|
337
|
+
})
|
|
338
|
+
.then(res => res.json())
|
|
339
|
+
.then(reply => {
|
|
340
|
+
if (window.__codexSessionStatus?.reply) {
|
|
341
|
+
window.__codexSessionStatus.reply(reply);
|
|
342
|
+
}
|
|
343
|
+
})
|
|
344
|
+
.catch(err => {
|
|
345
|
+
try {
|
|
346
|
+
const msg = JSON.parse(payload);
|
|
347
|
+
if (window.__codexSessionStatus?.reply) {
|
|
348
|
+
window.__codexSessionStatus.reply({
|
|
349
|
+
requestId: msg.requestId,
|
|
350
|
+
error: `${getUiText(null, 'Background service connection failed: ', '后台服务连接失败:')}${err.message}`,
|
|
351
|
+
snapshot: { revision: 0, records: {} },
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
} catch { /* ignore */ }
|
|
355
|
+
});
|
|
356
|
+
},
|
|
357
|
+
|
|
358
|
+
isRowSelected(row) {
|
|
359
|
+
if (!row) return false;
|
|
360
|
+
if (row.getAttribute('data-selected') === 'true') return true;
|
|
361
|
+
if (row.classList.contains('bg-sidebar-secondary')) return true;
|
|
362
|
+
const id = row.getAttribute('data-cascade-id');
|
|
363
|
+
const currentId = window.location.pathname.split('/').filter(Boolean).pop();
|
|
364
|
+
return Boolean(id && id === currentId);
|
|
365
|
+
},
|
|
366
|
+
|
|
367
|
+
async openPane({ entry } = {}) {
|
|
368
|
+
const requestedThreadId = entry?.threadId || null;
|
|
369
|
+
if (requestedThreadId) {
|
|
370
|
+
await switchConversationIfNeeded(requestedThreadId, entry?.row);
|
|
371
|
+
}
|
|
372
|
+
const activeConvId = requestedThreadId || getCurrentConversationId();
|
|
373
|
+
const bridge = collectReactBridge();
|
|
374
|
+
const descriptor = bridge.ext ? resolveThingsSidecarDescriptor(bridge.ext) : null;
|
|
375
|
+
if (bridge.ext && !descriptor) {
|
|
376
|
+
throw new Error(getUiText(null, 'Things sidebar plugin is not enabled. Enable it in Plugins Manager first.', 'Things 侧边栏插件未启用,请先在 Plugins Manager 中启用 Things 插件'));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
if (bridge.onSidecarLinkClick) {
|
|
380
|
+
bridge.onSidecarLinkClick(THINGS_SIDECAR_ID);
|
|
381
|
+
await waitMs(80);
|
|
382
|
+
if (isThingsSidecarOpen(bridge.store, activeConvId)) {
|
|
383
|
+
syncSidecarConversation(activeConvId);
|
|
384
|
+
return { ok: true, method: 'onSidecarLinkClick', conversationId: activeConvId };
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (descriptor && bridge.store?.dispatch) {
|
|
389
|
+
const targetUrl = buildConversationSidecarUrl(descriptor.baseViewUrl, activeConvId);
|
|
390
|
+
if (typeof bridge.sidecarPool?.navigateIframe === 'function') {
|
|
391
|
+
bridge.sidecarPool.navigateIframe(descriptor.baseViewUrl, targetUrl);
|
|
392
|
+
} else if (typeof bridge.sidecarPool?.setIframeSrc === 'function') {
|
|
393
|
+
bridge.sidecarPool.setIframeSrc(descriptor.baseViewUrl, targetUrl);
|
|
394
|
+
}
|
|
395
|
+
const treeId = activeConvId ? { kind: 'cascadeId', cascadeId: activeConvId } : { kind: 'home' };
|
|
396
|
+
const st = bridge.store.getState();
|
|
397
|
+
const setContentType = st?.sidePanelV2 ? 'sidePanelV2/setContent' : 'sidePanel/setContent';
|
|
398
|
+
bridge.store.dispatch({
|
|
399
|
+
type: setContentType,
|
|
400
|
+
payload: {
|
|
401
|
+
treeId,
|
|
402
|
+
content: {
|
|
403
|
+
type: 'sidecarView',
|
|
404
|
+
sidecarView: {
|
|
405
|
+
sidecarId: descriptor.sidecarId,
|
|
406
|
+
path: descriptor.path,
|
|
407
|
+
url: descriptor.baseViewUrl,
|
|
408
|
+
title: descriptor.title,
|
|
409
|
+
},
|
|
410
|
+
},
|
|
411
|
+
tabId: descriptor.tabId,
|
|
412
|
+
},
|
|
413
|
+
});
|
|
414
|
+
bridge.store.dispatch({
|
|
415
|
+
type: 'sidePanel/setSidePanelOpen',
|
|
416
|
+
payload: { treeId, isOpen: true },
|
|
417
|
+
});
|
|
418
|
+
if (typeof bridge.router?.navigate === 'function') {
|
|
419
|
+
try {
|
|
420
|
+
bridge.router.navigate({
|
|
421
|
+
search: prev => ({ ...(prev || {}), tab: descriptor.tabId }),
|
|
422
|
+
replace: true,
|
|
423
|
+
});
|
|
424
|
+
} catch (_) {}
|
|
425
|
+
}
|
|
426
|
+
await waitMs(80);
|
|
427
|
+
if (isThingsSidecarOpen(bridge.store, activeConvId)) {
|
|
428
|
+
syncSidecarConversation(activeConvId);
|
|
429
|
+
return { ok: true, method: 'reduxStore', conversationId: activeConvId };
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
await tryOpenViaDomFallback();
|
|
434
|
+
if (isThingsSidecarOpen(bridge.store, activeConvId)) {
|
|
435
|
+
syncSidecarConversation(activeConvId);
|
|
436
|
+
return { ok: true, method: 'domFallback', conversationId: activeConvId };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
throw new Error(getUiText(null, 'Unable to open Things sidebar plugin; verify the extension is enabled in Antigravity.', '未能打开 Things 侧边栏插件,请确认已在 Antigravity 中启用该扩展'));
|
|
440
|
+
},
|
|
441
|
+
|
|
442
|
+
async locate({ entry, source, analysisMessage } = {}) {
|
|
443
|
+
const setMsg = text => { if (analysisMessage) analysisMessage.textContent = text; };
|
|
444
|
+
const targetThreadId = entry?.threadId || source?.threadId || getCurrentConversationId();
|
|
445
|
+
|
|
446
|
+
if (targetThreadId && targetThreadId !== getCurrentConversationId()) {
|
|
447
|
+
try {
|
|
448
|
+
await switchConversationIfNeeded(targetThreadId, entry?.row, 5000);
|
|
449
|
+
} catch (err) {
|
|
450
|
+
const message = err?.message || getUiText(null, 'Session item not found', '找不到对应的会话项');
|
|
451
|
+
setMsg(message);
|
|
452
|
+
return { ok: false, located: false, conversationId: getCurrentConversationId(), message };
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const deadline = Date.now() + 3000;
|
|
457
|
+
while (targetThreadId && getCurrentConversationId() !== targetThreadId && Date.now() < deadline) {
|
|
458
|
+
await waitMs(80);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const activeConvId = getCurrentConversationId();
|
|
462
|
+
const getViewport = () => (
|
|
463
|
+
document.querySelector('[data-testid="autoscroll-viewport"]') ||
|
|
464
|
+
document.querySelector('main') ||
|
|
465
|
+
document.body
|
|
466
|
+
);
|
|
467
|
+
|
|
468
|
+
let targetEl = findSourceMessageElement(getViewport(), source);
|
|
469
|
+
const jumpedMsg = getUiText('locatedJumpMessage', 'Jumped to source message', '已跳转到来源消息');
|
|
470
|
+
if (targetEl) {
|
|
471
|
+
highlightLocatedElement(targetEl);
|
|
472
|
+
setMsg(jumpedMsg);
|
|
473
|
+
return { ok: true, located: true, method: 'dom', conversationId: activeConvId, message: jumpedMsg };
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
let navResult = { clickedExactTurn: false, clickedChapter: false };
|
|
477
|
+
const turnNum = source?.turnId ? Number(source.turnId) : null;
|
|
478
|
+
if (Number.isInteger(turnNum) && turnNum > 0) {
|
|
479
|
+
navResult = clickNavigatorForTurn(turnNum);
|
|
480
|
+
if (navResult.clickedExactTurn || navResult.clickedChapter) {
|
|
481
|
+
await waitMs(280);
|
|
482
|
+
targetEl = findSourceMessageElement(getViewport(), source);
|
|
483
|
+
if (targetEl) {
|
|
484
|
+
highlightLocatedElement(targetEl);
|
|
485
|
+
setMsg(jumpedMsg);
|
|
486
|
+
return { ok: true, located: true, method: 'navigator', conversationId: activeConvId, message: jumpedMsg };
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
let stagnantCount = 0;
|
|
492
|
+
let prevMarker = '';
|
|
493
|
+
for (let attempt = 0; attempt < 35; attempt++) {
|
|
494
|
+
const load = document.querySelector('button[aria-label^="Load older messages"]') ||
|
|
495
|
+
[...document.querySelectorAll('button')].find(b => b.textContent?.trim() === 'Load older messages');
|
|
496
|
+
if (!load || load.disabled || load.getAttribute?.('aria-disabled') === 'true') break;
|
|
497
|
+
|
|
498
|
+
const vp = getViewport();
|
|
499
|
+
const curMarker = `${load.getAttribute?.('aria-label') || ''}|${vp?.scrollHeight || 0}`;
|
|
500
|
+
setMsg(getUiText(null, 'Loading earlier history...', '正在展开历史消息…'));
|
|
501
|
+
load.click();
|
|
502
|
+
await waitMs(240);
|
|
503
|
+
|
|
504
|
+
targetEl = findSourceMessageElement(getViewport(), source);
|
|
505
|
+
if (targetEl) {
|
|
506
|
+
highlightLocatedElement(targetEl);
|
|
507
|
+
setMsg(jumpedMsg);
|
|
508
|
+
return { ok: true, located: true, method: 'loadOlder', conversationId: activeConvId, message: jumpedMsg };
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const vpAfter = getViewport();
|
|
512
|
+
const afterMarker = `${load.getAttribute?.('aria-label') || ''}|${vpAfter?.scrollHeight || 0}`;
|
|
513
|
+
if (curMarker === prevMarker && afterMarker === curMarker) {
|
|
514
|
+
stagnantCount++;
|
|
515
|
+
if (stagnantCount >= 2) break;
|
|
516
|
+
} else {
|
|
517
|
+
stagnantCount = 0;
|
|
518
|
+
}
|
|
519
|
+
prevMarker = afterMarker;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
if (navResult.clickedExactTurn) {
|
|
523
|
+
const turnMsg = getUiText(null, 'Jumped to this turn via session navigator', '已通过会话导航跳转至该轮次');
|
|
524
|
+
setMsg(turnMsg);
|
|
525
|
+
return { ok: true, located: true, method: 'turnNavigator', conversationId: activeConvId, message: turnMsg };
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const failMsg = getUiText(null, 'Source message not found; check if it was deleted or collapsed', '来源消息尚未找到,请确认该消息未被删除或折叠');
|
|
529
|
+
setMsg(failMsg);
|
|
530
|
+
return { ok: false, located: false, conversationId: activeConvId, message: failMsg };
|
|
531
|
+
},
|
|
532
|
+
|
|
533
|
+
reconcile({ mounted, unmount, attachHost, paint, paintVisibility, openPanel, closePanel, isPanelBusy, isPanelEntry }) {
|
|
534
|
+
const extractSessionTitle = row => extractSidebarRowTitle(row) || getUiText('fallbackThreadTitle', 'Session', '会话');
|
|
535
|
+
|
|
536
|
+
// 1. 清理已断开连接、非侧边栏行、或绑定的 cascadeId 已被 React 复用给其他会话的 slot(解决串台)
|
|
537
|
+
for (const [row, entry] of [...mounted.entries()]) {
|
|
538
|
+
const isSidebarRow = row.classList.contains('agy-sidebar-row');
|
|
539
|
+
const currentCascadeId = row.getAttribute('data-cascade-id');
|
|
540
|
+
if (!row.isConnected || !entry.host.isConnected || !isSidebarRow || !currentCascadeId || currentCascadeId !== entry.threadId) {
|
|
541
|
+
if (entry.slot?.isConnected) {
|
|
542
|
+
entry.slot.remove();
|
|
543
|
+
}
|
|
544
|
+
if (row.style?.getPropertyValue('padding-left') === '8px') {
|
|
545
|
+
row.style.removeProperty('padding-left');
|
|
546
|
+
}
|
|
547
|
+
unmount(entry);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// 2. 严格仅在侧边栏行内查询与注入,彻底杜绝主聊天区顶部被污染
|
|
552
|
+
const rows = document.querySelectorAll('.agy-sidebar-row[data-cascade-id]');
|
|
553
|
+
for (const row of rows) {
|
|
554
|
+
const cascadeId = row.getAttribute('data-cascade-id');
|
|
555
|
+
if (!cascadeId) continue;
|
|
556
|
+
|
|
557
|
+
// 统一对齐(方案 A):项目子会话被官方硬编码 pl-[30px],在注入圆环后会产生双重避让,统一重置为 8px 与普通会话平齐
|
|
558
|
+
if (row.className && row.className.includes('pl-[') && row.style.getPropertyValue('padding-left') !== '8px') {
|
|
559
|
+
row.style.setProperty('padding-left', '8px', 'important');
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const title = extractSessionTitle(row);
|
|
563
|
+
let entry = mounted.get(row);
|
|
564
|
+
if (entry) {
|
|
565
|
+
if (entry.title !== title) {
|
|
566
|
+
entry.title = title;
|
|
567
|
+
paint(entry);
|
|
568
|
+
}
|
|
569
|
+
paintVisibility(entry);
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const key = JSON.stringify(['local', cascadeId]);
|
|
574
|
+
// Title container is typically children[1]
|
|
575
|
+
const titleContainer = row.children[1] || row;
|
|
576
|
+
let slot = titleContainer.querySelector(':scope > [data-antigravity-status-slot]');
|
|
577
|
+
if (!slot) {
|
|
578
|
+
slot = document.createElement('div');
|
|
579
|
+
slot.setAttribute('data-antigravity-status-slot', '');
|
|
580
|
+
slot.style.cssText = 'flex:none;width:24px;height:24px;display:flex;align-items:center;justify-content:center;pointer-events:auto;z-index:2;';
|
|
581
|
+
titleContainer.prepend(slot);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
const { host, button, original } = attachHost(slot, false, null);
|
|
585
|
+
|
|
586
|
+
const onEnter = () => { entry.hovered = true; paintVisibility(entry); };
|
|
587
|
+
const onLeave = () => { entry.hovered = false; paintVisibility(entry); };
|
|
588
|
+
row.addEventListener('pointerenter', onEnter);
|
|
589
|
+
row.addEventListener('pointerleave', onLeave);
|
|
590
|
+
|
|
591
|
+
button.addEventListener('click', event => {
|
|
592
|
+
event.stopPropagation();
|
|
593
|
+
event.preventDefault();
|
|
594
|
+
// 先关旧面板再开新面板,支持从 A 顺畅切换到 B
|
|
595
|
+
if (isPanelEntry(entry)) {
|
|
596
|
+
closePanel();
|
|
597
|
+
} else {
|
|
598
|
+
closePanel();
|
|
599
|
+
// 打开面板时,瞬时重采样当前行最新的首句 Prompt 会话标题,确保完全对齐
|
|
600
|
+
entry.title = extractSessionTitle(row);
|
|
601
|
+
openPanel(entry);
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
entry = {
|
|
606
|
+
row,
|
|
607
|
+
key,
|
|
608
|
+
threadId: cascadeId,
|
|
609
|
+
rawHost: 'local',
|
|
610
|
+
slot,
|
|
611
|
+
host,
|
|
612
|
+
button,
|
|
613
|
+
title,
|
|
614
|
+
hovered: false,
|
|
615
|
+
ringKey: null,
|
|
616
|
+
original,
|
|
617
|
+
onEnter,
|
|
618
|
+
onLeave,
|
|
619
|
+
};
|
|
620
|
+
mounted.set(row, entry);
|
|
621
|
+
|
|
622
|
+
paint(entry);
|
|
623
|
+
}
|
|
624
|
+
},
|
|
625
|
+
};
|
|
626
|
+
|
|
627
|
+
window.__sessionStatusHarness = harness;
|
|
628
|
+
|
|
629
|
+
// Sync snapshot periodically
|
|
630
|
+
let lastRevision = -1;
|
|
631
|
+
const syncSnapshot = async () => {
|
|
632
|
+
try {
|
|
633
|
+
checkConversationChange();
|
|
634
|
+
const res = await fetch(`${getServiceOrigin()}/snapshot`, { headers: getServiceHeaders() });
|
|
635
|
+
if (res.ok) {
|
|
636
|
+
const data = await res.json();
|
|
637
|
+
if (data.snapshot && data.snapshot.revision !== lastRevision) {
|
|
638
|
+
lastRevision = data.snapshot.revision;
|
|
639
|
+
window.__codexSessionStatus?.receive(data.snapshot);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
} catch { /* service not started yet, retry */ }
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
const syncTimer = setInterval(syncSnapshot, 3000);
|
|
646
|
+
if (typeof syncTimer.unref === 'function') syncTimer.unref();
|
|
647
|
+
harness.dispose = () => clearInterval(syncTimer);
|
|
648
|
+
syncSnapshot();
|
|
649
|
+
|
|
650
|
+
// 注销旧版本遗留的全局监听器(支持凭据轮换与重载清理)
|
|
651
|
+
if (typeof window.__antigravityHarnessDispose === 'function') {
|
|
652
|
+
try { window.__antigravityHarnessDispose(); } catch (_) {}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// 清理旧版本遗留的重复全局定位监听器,统一收口到 onCardMessage / dispatchCardRequest
|
|
656
|
+
if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function' && window.__agentThingsLocateListener) {
|
|
657
|
+
try { window.removeEventListener('message', window.__agentThingsLocateListener); } catch (_) {}
|
|
658
|
+
window.__agentThingsLocateListener = null;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// 保持单例 Map 对象身份不变,实现生命周期重入无缝衔接
|
|
662
|
+
const registeredCards = (typeof window !== 'undefined' && window.__agentThingsCardBindings instanceof Map)
|
|
663
|
+
? window.__agentThingsCardBindings
|
|
664
|
+
: new Map(); // Window -> { conversationId, iframe, expectedPath, win, port, handshakeDone, active, loadToken }
|
|
665
|
+
if (typeof window !== 'undefined') {
|
|
666
|
+
window.__agentThingsCardBindings = registeredCards;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// 会话切换毫秒级广播机制(驱动 Sidecar 面板与卡片即时跟随宿主活动会话)
|
|
670
|
+
const getCurrentConversationId = () => {
|
|
671
|
+
try {
|
|
672
|
+
return (window.location.pathname.split('/').filter(Boolean).pop() || '').trim();
|
|
673
|
+
} catch (_) {
|
|
674
|
+
return '';
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
let lastActiveConversationId = getCurrentConversationId();
|
|
678
|
+
|
|
679
|
+
function buildConversationChangedMessage(convId) {
|
|
680
|
+
const title = getConversationTitle(convId);
|
|
681
|
+
return title
|
|
682
|
+
? { type: 'ANTIGRAVITY_CONVERSATION_CHANGED', conversationId: convId, title }
|
|
683
|
+
: { type: 'ANTIGRAVITY_CONVERSATION_CHANGED', conversationId: convId };
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function syncSidecarConversation(convId) {
|
|
687
|
+
if (!convId || typeof document === 'undefined') return;
|
|
688
|
+
const message = buildConversationChangedMessage(convId);
|
|
689
|
+
try {
|
|
690
|
+
const allIframes = document.querySelectorAll('iframe');
|
|
691
|
+
for (const ifr of allIframes) {
|
|
692
|
+
try {
|
|
693
|
+
ifr.contentWindow?.postMessage(message, '*');
|
|
694
|
+
} catch (_) {}
|
|
695
|
+
}
|
|
696
|
+
} catch (_) {}
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
const notifyConversationChanged = (newId) => {
|
|
700
|
+
if (!newId || newId === lastActiveConversationId) return;
|
|
701
|
+
lastActiveConversationId = newId;
|
|
702
|
+
const message = buildConversationChangedMessage(newId);
|
|
703
|
+
syncSidecarConversation(newId);
|
|
704
|
+
try {
|
|
705
|
+
for (const binding of registeredCards.values()) {
|
|
706
|
+
try {
|
|
707
|
+
binding.port?.postMessage(message);
|
|
708
|
+
} catch (_) {}
|
|
709
|
+
}
|
|
710
|
+
} catch (_) {}
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
const checkConversationChange = () => {
|
|
714
|
+
const curId = getCurrentConversationId();
|
|
715
|
+
if (curId && curId !== lastActiveConversationId) {
|
|
716
|
+
notifyConversationChanged(curId);
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
if (typeof window !== 'undefined' && !window.__agentThingsRouteHooked) {
|
|
721
|
+
window.__agentThingsRouteHooked = true;
|
|
722
|
+
window.addEventListener('popstate', checkConversationChange);
|
|
723
|
+
window.addEventListener('hashchange', checkConversationChange);
|
|
724
|
+
if (window.history && typeof window.history.pushState === 'function') {
|
|
725
|
+
const origPush = window.history.pushState;
|
|
726
|
+
window.history.pushState = function() {
|
|
727
|
+
const ret = origPush.apply(this, arguments);
|
|
728
|
+
setTimeout(checkConversationChange, 0);
|
|
729
|
+
return ret;
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
if (window.history && typeof window.history.replaceState === 'function') {
|
|
733
|
+
const origReplace = window.history.replaceState;
|
|
734
|
+
window.history.replaceState = function() {
|
|
735
|
+
const ret = origReplace.apply(this, arguments);
|
|
736
|
+
setTimeout(checkConversationChange, 0);
|
|
737
|
+
return ret;
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// 内部辅助:处理已绑定专属端口收到的业务消息
|
|
743
|
+
let dispatchCardRequest;
|
|
744
|
+
|
|
745
|
+
// 继承上一代宿主桥遗留的可信卡片绑定(后台重启导致宿主桥重新注入时,旧卡片端口无缝接管)
|
|
746
|
+
if (typeof window !== 'undefined') {
|
|
747
|
+
registeredCards.forEach((prevBinding, win) => {
|
|
748
|
+
if (!/^[a-f0-9]{64}$/.test(prevBinding?.digest)) {
|
|
749
|
+
if (prevBinding) prevBinding.active = false;
|
|
750
|
+
prevBinding?.port?.close();
|
|
751
|
+
registeredCards.delete(win);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
if (prevBinding && prevBinding.active && prevBinding.iframe?.isConnected && prevBinding.port) {
|
|
755
|
+
const boundConvId = prevBinding.conversationId;
|
|
756
|
+
const currentUrlId = window.location?.pathname?.split('/')?.filter(Boolean)?.pop();
|
|
757
|
+
const iframeAttrId = prevBinding.iframe.getAttribute?.('data-conversation-id');
|
|
758
|
+
if (boundConvId === currentUrlId || (iframeAttrId && iframeAttrId === boundConvId)) {
|
|
759
|
+
prevBinding.handshakeDone = true;
|
|
760
|
+
// 重新将端口消息监听器绑定到新一代宿主桥的 dispatchCardRequest 处理逻辑
|
|
761
|
+
try {
|
|
762
|
+
prevBinding.port.onmessage = async (portEvt) => {
|
|
763
|
+
if (portEvt && portEvt.data && typeof portEvt.data === 'object') {
|
|
764
|
+
if (typeof dispatchCardRequest === 'function') {
|
|
765
|
+
await dispatchCardRequest(prevBinding, prevBinding.port, portEvt.data);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
} catch (_) {}
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
function normalizeArtifactPath(urlString) {
|
|
776
|
+
if (!urlString || typeof urlString !== 'string') return null;
|
|
777
|
+
try {
|
|
778
|
+
const parsed = new URL(urlString, typeof window !== 'undefined' ? window.location?.href : 'file:///');
|
|
779
|
+
if (parsed.protocol !== 'file:' && parsed.protocol !== 'vscode-file:') return null;
|
|
780
|
+
let pathname = decodeURIComponent(parsed.pathname);
|
|
781
|
+
const parts = pathname.split('/').filter(Boolean);
|
|
782
|
+
const stack = [];
|
|
783
|
+
for (const p of parts) {
|
|
784
|
+
if (p === '.') continue;
|
|
785
|
+
if (p === '..') stack.pop();
|
|
786
|
+
else stack.push(p);
|
|
787
|
+
}
|
|
788
|
+
return '/' + stack.join('/');
|
|
789
|
+
} catch (_) {
|
|
790
|
+
return null;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function getIframeHref(iframe) {
|
|
795
|
+
try {
|
|
796
|
+
return iframe.contentWindow?.location?.href || '';
|
|
797
|
+
} catch (_) {
|
|
798
|
+
return ''; // 跨域受限抛错直接返回空,彻底移除静态 src 授权回退
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function registerCardIframe(iframe, explicitConvId = null, options = {}) {
|
|
803
|
+
if (!iframe || !iframe.contentWindow) return false;
|
|
804
|
+
|
|
805
|
+
// brainDir 和会话 ID 必须来自宿主可信上下文,缺失时拒绝登记
|
|
806
|
+
const knownBrainDir = window.__agentThingsConnection?.brainDir || '';
|
|
807
|
+
if (!knownBrainDir) return false;
|
|
808
|
+
const normBrain = normalizeArtifactPath('file://' + knownBrainDir);
|
|
809
|
+
if (!normBrain) return false;
|
|
810
|
+
|
|
811
|
+
const currentUrlId = explicitConvId || (iframe.getAttribute && iframe.getAttribute('data-conversation-id')) || (typeof window !== 'undefined' ? window.location?.pathname?.split('/')?.filter(Boolean)?.pop() : null);
|
|
812
|
+
if (!currentUrlId || typeof currentUrlId !== 'string') return false;
|
|
813
|
+
|
|
814
|
+
// 基于宿主可信上下文推导唯一法定路径
|
|
815
|
+
const expectedPath = normalizeArtifactPath(`file://${normBrain}/${currentUrlId}/things-card.html`);
|
|
816
|
+
if (!expectedPath) return false;
|
|
817
|
+
|
|
818
|
+
const win = iframe.contentWindow;
|
|
819
|
+
const existing = registeredCards.get(win);
|
|
820
|
+
const passedToken = options.loadToken || null;
|
|
821
|
+
if (!passedToken) return false;
|
|
822
|
+
|
|
823
|
+
// 若当前 iframe 实例已登记且持有活跃专属端口和完成的握手:
|
|
824
|
+
if (existing && existing.active && existing.iframe === iframe && existing.port && existing.handshakeDone) {
|
|
825
|
+
// 只有在新的 loadToken 与现有活跃 token 一致时(如常规扫描),才保留现有活跃通道;
|
|
826
|
+
// 若提供了全新的 loadToken,说明宿主通过可信流程重新装入了新文档,必须重置通道以允许新文档握手。
|
|
827
|
+
if (passedToken === existing.loadToken) {
|
|
828
|
+
return true;
|
|
829
|
+
}
|
|
830
|
+
try { existing.port?.close(); } catch (_) {}
|
|
831
|
+
existing.port = null;
|
|
832
|
+
existing.handshakeDone = false;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
// 若工件能读取到 location.href(非沙盒或同源模式),严格全等预期路径
|
|
836
|
+
const curHref = getIframeHref(iframe);
|
|
837
|
+
// A verified setter is about to replace the initial blank document.
|
|
838
|
+
const initialBlank = curHref === 'about:blank' && options.loading === true && /^[a-f0-9]{64}$/.test(options.digest);
|
|
839
|
+
if (curHref && !initialBlank) {
|
|
840
|
+
const normPath = normalizeArtifactPath(curHref);
|
|
841
|
+
if (!normPath || normPath !== expectedPath) return false;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const binding = {
|
|
845
|
+
conversationId: currentUrlId,
|
|
846
|
+
iframe,
|
|
847
|
+
expectedPath,
|
|
848
|
+
win,
|
|
849
|
+
port: null,
|
|
850
|
+
handshakeDone: false,
|
|
851
|
+
active: true,
|
|
852
|
+
loadToken: passedToken,
|
|
853
|
+
digest: options.digest || null,
|
|
854
|
+
};
|
|
855
|
+
registeredCards.set(win, binding);
|
|
856
|
+
|
|
857
|
+
if (iframe.__agentThingsNavHandler && typeof iframe.removeEventListener === 'function') {
|
|
858
|
+
try { iframe.removeEventListener('load', iframe.__agentThingsNavHandler); } catch (_) {}
|
|
859
|
+
}
|
|
860
|
+
let loadCount = 0;
|
|
861
|
+
const onNav = () => {
|
|
862
|
+
loadCount++;
|
|
863
|
+
// 任何后续加载(二次 load)或失效,证明发生了文档内部导航或重载
|
|
864
|
+
if (loadCount > 1 || !binding.active) {
|
|
865
|
+
binding.active = false;
|
|
866
|
+
try { binding.port?.close(); } catch (_) {}
|
|
867
|
+
binding.port = null;
|
|
868
|
+
registeredCards.delete(win);
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
iframe.__agentThingsNavHandler = onNav;
|
|
872
|
+
if (typeof iframe.addEventListener === 'function') {
|
|
873
|
+
iframe.addEventListener('load', onNav);
|
|
874
|
+
}
|
|
875
|
+
return true;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function sendReplyToCard(binding, capturedPort, replyData) {
|
|
879
|
+
// 异步回包前二次核验(TOCTOU 防御):必须仍处于登记簿中、同一活动对象且未偏离
|
|
880
|
+
if (!binding || !binding.active || !registeredCards.has(binding.win) || registeredCards.get(binding.win) !== binding) return false;
|
|
881
|
+
if (!binding.iframe?.isConnected || binding.iframe.contentWindow !== binding.win) {
|
|
882
|
+
binding.active = false;
|
|
883
|
+
try { binding.port?.close(); } catch (_) {}
|
|
884
|
+
registeredCards.delete(binding.win);
|
|
885
|
+
return false;
|
|
886
|
+
}
|
|
887
|
+
const currentHref = getIframeHref(binding.iframe);
|
|
888
|
+
if (currentHref) {
|
|
889
|
+
const currentNorm = normalizeArtifactPath(currentHref);
|
|
890
|
+
if (currentNorm !== binding.expectedPath) {
|
|
891
|
+
binding.active = false;
|
|
892
|
+
try { binding.port?.close(); } catch (_) {}
|
|
893
|
+
registeredCards.delete(binding.win);
|
|
894
|
+
return false;
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
// 票据和备注只走绑定的专属端口;绝不使用 postMessage('*') 回退
|
|
898
|
+
if (!capturedPort || binding.port !== capturedPort) {
|
|
899
|
+
return false;
|
|
900
|
+
}
|
|
901
|
+
try {
|
|
902
|
+
capturedPort.postMessage(replyData);
|
|
903
|
+
return true;
|
|
904
|
+
} catch (_) {
|
|
905
|
+
return false;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
function scanAndRegisterIframes() {
|
|
910
|
+
try {
|
|
911
|
+
const iframes = document.querySelectorAll('iframe');
|
|
912
|
+
for (const f of iframes) registerCardIframe(f);
|
|
913
|
+
} catch (_) {}
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
const cardObserver = typeof MutationObserver !== 'undefined' ? new MutationObserver(mutations => {
|
|
917
|
+
checkConversationChange();
|
|
918
|
+
for (const m of mutations) {
|
|
919
|
+
for (const node of m.addedNodes) {
|
|
920
|
+
if (node.tagName === 'IFRAME') registerCardIframe(node);
|
|
921
|
+
else if (node.querySelectorAll) {
|
|
922
|
+
const ifs = node.querySelectorAll('iframe');
|
|
923
|
+
for (const f of ifs) registerCardIframe(f);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
for (const node of m.removedNodes) {
|
|
927
|
+
if (node.tagName === 'IFRAME' && node.contentWindow) {
|
|
928
|
+
const b = registeredCards.get(node.contentWindow);
|
|
929
|
+
if (b) {
|
|
930
|
+
b.active = false;
|
|
931
|
+
try { b.port?.close(); } catch (_) {}
|
|
932
|
+
registeredCards.delete(node.contentWindow);
|
|
933
|
+
}
|
|
934
|
+
} else if (node.querySelectorAll) {
|
|
935
|
+
const ifs = node.querySelectorAll('iframe');
|
|
936
|
+
for (const f of ifs) {
|
|
937
|
+
if (f.contentWindow) {
|
|
938
|
+
const b = registeredCards.get(f.contentWindow);
|
|
939
|
+
if (b) {
|
|
940
|
+
b.active = false;
|
|
941
|
+
try { b.port?.close(); } catch (_) {}
|
|
942
|
+
registeredCards.delete(f.contentWindow);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
}) : null;
|
|
950
|
+
|
|
951
|
+
try {
|
|
952
|
+
if (cardObserver) {
|
|
953
|
+
cardObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
|
|
954
|
+
}
|
|
955
|
+
} catch (_) {}
|
|
956
|
+
scanAndRegisterIframes();
|
|
957
|
+
|
|
958
|
+
// 内部辅助:处理已绑定专属端口收到的业务消息
|
|
959
|
+
dispatchCardRequest = async (binding, targetPort, data) => {
|
|
960
|
+
const boundConvId = binding.conversationId;
|
|
961
|
+
|
|
962
|
+
// 强制核对会话 ID:若不匹配,仅通过当前端口回传错误,绝不注销合法绑定通道
|
|
963
|
+
if (data.conversationId && data.conversationId !== boundConvId) {
|
|
964
|
+
sendReplyToCard(binding, targetPort, {
|
|
965
|
+
type: data.type === 'AGENT_THINGS_AUTH_REQUEST' ? 'AGENT_THINGS_AUTH_RESPONSE' : 'AGENT_THINGS_ACTION_RESULT',
|
|
966
|
+
nonce: data.nonce,
|
|
967
|
+
success: false,
|
|
968
|
+
error: getUiText(null, 'Session identity mismatch: cross-session action blocked', '会话身份不匹配:禁止跨会话操作'),
|
|
969
|
+
});
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// 卡片渲染更新确认通知
|
|
974
|
+
if (data.type === 'AGENT_THINGS_CARD_UPDATED') {
|
|
975
|
+
binding.lastReportedProgress = data.progress;
|
|
976
|
+
binding.lastReportedRevision = data.revision;
|
|
977
|
+
binding.lastReportedState = data.state;
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// 签发单会话短期只读订阅票据(含首次拿票与后台重启后原通道自动换票)
|
|
982
|
+
if (data.type === 'AGENT_THINGS_AUTH_REQUEST') {
|
|
983
|
+
const { nonce } = data;
|
|
984
|
+
if (!nonce) return;
|
|
985
|
+
try {
|
|
986
|
+
const activeOrigin = getServiceOrigin();
|
|
987
|
+
const res = await fetch(`${activeOrigin}/session/ticket`, {
|
|
988
|
+
method: 'POST',
|
|
989
|
+
headers: getServiceHeaders(),
|
|
990
|
+
body: JSON.stringify({ conversationId: boundConvId }),
|
|
991
|
+
});
|
|
992
|
+
if (res.ok) {
|
|
993
|
+
const reply = await res.json();
|
|
994
|
+
sendReplyToCard(binding, targetPort, {
|
|
995
|
+
type: 'AGENT_THINGS_AUTH_RESPONSE',
|
|
996
|
+
nonce,
|
|
997
|
+
conversationId: boundConvId,
|
|
998
|
+
ticket: reply.ticket,
|
|
999
|
+
expiresAt: reply.expiresAt,
|
|
1000
|
+
origin: activeOrigin,
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
} catch (_) {}
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// 宿主桥代发写操作(保存、清除、分析)
|
|
1008
|
+
if (data.type === 'AGENT_THINGS_ACTION_PROXY') {
|
|
1009
|
+
const { nonce, action, payload } = data;
|
|
1010
|
+
if (!nonce) return;
|
|
1011
|
+
try {
|
|
1012
|
+
const key = JSON.stringify(['local', boundConvId]);
|
|
1013
|
+
let rpcMsg = null;
|
|
1014
|
+
if (action === 'update') {
|
|
1015
|
+
rpcMsg = { type: 'update', key, record: payload.record, expectedRevision: payload.expectedRevision, requestId: 'proxy-update-' + Date.now() };
|
|
1016
|
+
} else if (action === 'clear') {
|
|
1017
|
+
rpcMsg = { type: 'clear', key, expectedRevision: payload.expectedRevision, requestId: 'proxy-clear-' + Date.now() };
|
|
1018
|
+
} else if (action === 'analyze') {
|
|
1019
|
+
rpcMsg = { type: 'analyze', key, requestId: 'proxy-analyze-' + Date.now() };
|
|
1020
|
+
}
|
|
1021
|
+
if (rpcMsg) {
|
|
1022
|
+
const res = await fetch(`${getServiceOrigin()}/rpc`, {
|
|
1023
|
+
method: 'POST',
|
|
1024
|
+
headers: getServiceHeaders(),
|
|
1025
|
+
body: JSON.stringify(rpcMsg),
|
|
1026
|
+
});
|
|
1027
|
+
const reply = await res.json();
|
|
1028
|
+
if (reply.snapshot) {
|
|
1029
|
+
window.__codexSessionStatus?.receive?.(reply.snapshot);
|
|
1030
|
+
}
|
|
1031
|
+
const targetRecord = reply.snapshot?.records?.[key];
|
|
1032
|
+
const sessionData = targetRecord ? {
|
|
1033
|
+
conversationId: boundConvId,
|
|
1034
|
+
recordRevision: targetRecord.revision ?? 0,
|
|
1035
|
+
progress: targetRecord.progress ?? null,
|
|
1036
|
+
state: targetRecord.state ?? null,
|
|
1037
|
+
note: targetRecord.note ?? '',
|
|
1038
|
+
} : null;
|
|
1039
|
+
sendReplyToCard(binding, targetPort, {
|
|
1040
|
+
type: 'AGENT_THINGS_ACTION_RESULT',
|
|
1041
|
+
nonce,
|
|
1042
|
+
action,
|
|
1043
|
+
success: !reply.error,
|
|
1044
|
+
error: reply.error || null,
|
|
1045
|
+
session: sessionData,
|
|
1046
|
+
data: { session: sessionData },
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
} catch (err) {
|
|
1050
|
+
sendReplyToCard(binding, targetPort, {
|
|
1051
|
+
type: 'AGENT_THINGS_ACTION_RESULT',
|
|
1052
|
+
nonce,
|
|
1053
|
+
action,
|
|
1054
|
+
success: false,
|
|
1055
|
+
error: err.message || getUiText(null, 'Proxy request failed', '代理请求失败'),
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// 定位跳转(强制使用 boundConvId)
|
|
1062
|
+
if (data.type === 'AGENT_THINGS_LOCATE' && data.source) {
|
|
1063
|
+
const { nonce } = data;
|
|
1064
|
+
try {
|
|
1065
|
+
const result = await harness.locate({
|
|
1066
|
+
entry: { threadId: boundConvId },
|
|
1067
|
+
source: data.source,
|
|
1068
|
+
analysisMessage: { textContent: '' },
|
|
1069
|
+
});
|
|
1070
|
+
if (nonce) {
|
|
1071
|
+
sendReplyToCard(binding, targetPort, {
|
|
1072
|
+
type: 'AGENT_THINGS_ACTION_RESULT',
|
|
1073
|
+
nonce,
|
|
1074
|
+
action: 'locate',
|
|
1075
|
+
success: Boolean(result?.located),
|
|
1076
|
+
data: result,
|
|
1077
|
+
error: result?.located ? undefined : (result?.message || getUiText(null, 'Source message not found', '未找到来源消息')),
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
} catch (err) {
|
|
1081
|
+
if (nonce) {
|
|
1082
|
+
sendReplyToCard(binding, targetPort, {
|
|
1083
|
+
type: 'AGENT_THINGS_ACTION_RESULT',
|
|
1084
|
+
nonce,
|
|
1085
|
+
action: 'locate',
|
|
1086
|
+
success: false,
|
|
1087
|
+
error: err?.message || getUiText(null, 'Failed to locate source', '定位来源失败'),
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// 在侧栏打开 Things 插件(强制使用 boundConvId)
|
|
1095
|
+
if (data.type === 'AGENT_THINGS_OPEN_PANE') {
|
|
1096
|
+
const { nonce } = data;
|
|
1097
|
+
try {
|
|
1098
|
+
await harness.openPane({ entry: { threadId: boundConvId } });
|
|
1099
|
+
if (nonce) {
|
|
1100
|
+
sendReplyToCard(binding, targetPort, {
|
|
1101
|
+
type: 'AGENT_THINGS_ACTION_RESULT',
|
|
1102
|
+
nonce,
|
|
1103
|
+
action: 'open-pane',
|
|
1104
|
+
success: true,
|
|
1105
|
+
data: { opened: true, conversationId: boundConvId },
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
} catch (err) {
|
|
1109
|
+
if (nonce) {
|
|
1110
|
+
sendReplyToCard(binding, targetPort, {
|
|
1111
|
+
type: 'AGENT_THINGS_ACTION_RESULT',
|
|
1112
|
+
nonce,
|
|
1113
|
+
action: 'open-pane',
|
|
1114
|
+
success: false,
|
|
1115
|
+
error: err?.message || getUiText(null, 'Failed to open the sidebar plugin', '打开侧栏插件失败'),
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
};
|
|
1122
|
+
|
|
1123
|
+
// 监听来自全局 window 的初始握手及操作消息
|
|
1124
|
+
const onCardMessage = async event => {
|
|
1125
|
+
try {
|
|
1126
|
+
const data = event.data;
|
|
1127
|
+
if (!data || typeof data !== 'object') return;
|
|
1128
|
+
|
|
1129
|
+
// 允许未完成专属端口接管的内嵌卡片或纯 MCP 面板发起跨会话/会话内跳转定位
|
|
1130
|
+
if (data.type === 'AGENT_THINGS_LOCATE' && data.source) {
|
|
1131
|
+
const existingBinding = registeredCards.get(event.source);
|
|
1132
|
+
if (!existingBinding?.handshakeDone) {
|
|
1133
|
+
const targetThreadId = data.conversationId || getCurrentConversationId();
|
|
1134
|
+
const result = await harness.locate({
|
|
1135
|
+
entry: { threadId: targetThreadId },
|
|
1136
|
+
source: data.source,
|
|
1137
|
+
analysisMessage: { textContent: '' },
|
|
1138
|
+
});
|
|
1139
|
+
if (data.nonce && event.source && typeof event.source.postMessage === 'function') {
|
|
1140
|
+
try {
|
|
1141
|
+
event.source.postMessage({
|
|
1142
|
+
type: 'AGENT_THINGS_LOCATE_RESULT',
|
|
1143
|
+
nonce: data.nonce,
|
|
1144
|
+
located: Boolean(result?.located),
|
|
1145
|
+
success: Boolean(result?.located),
|
|
1146
|
+
message: result?.message || '',
|
|
1147
|
+
data: result,
|
|
1148
|
+
}, '*');
|
|
1149
|
+
} catch (_) {}
|
|
1150
|
+
}
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// 1. 查找宿主登记簿:必须是已由宿主登记且仍处于活动连接状态的同一 iframe 实例
|
|
1156
|
+
let binding = registeredCards.get(event.source);
|
|
1157
|
+
if (!binding) {
|
|
1158
|
+
// 若消息先于 MutationObserver 微任务到达,尝试从当前 DOM 中定位 contentWindow 匹配的 iframe 按可信规则登记
|
|
1159
|
+
try {
|
|
1160
|
+
const matching = Array.from(document.querySelectorAll('iframe')).find(f => f.contentWindow === event.source);
|
|
1161
|
+
if (matching) {
|
|
1162
|
+
registerCardIframe(matching, data.conversationId, {
|
|
1163
|
+
loadToken: data.loadToken || null,
|
|
1164
|
+
digest: data.digest || null,
|
|
1165
|
+
});
|
|
1166
|
+
binding = registeredCards.get(event.source);
|
|
1167
|
+
}
|
|
1168
|
+
} catch (_) {}
|
|
1169
|
+
}
|
|
1170
|
+
if (!binding || !binding.active || !binding.iframe?.isConnected || binding.iframe.contentWindow !== event.source) {
|
|
1171
|
+
if (binding) {
|
|
1172
|
+
binding.active = false;
|
|
1173
|
+
try { binding.port?.close(); } catch (_) {}
|
|
1174
|
+
registeredCards.delete(event.source);
|
|
1175
|
+
}
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// 2. 检查实时地址偏离(可读地址模式下的同步前置防御)
|
|
1180
|
+
const curHref = getIframeHref(binding.iframe);
|
|
1181
|
+
if (curHref) {
|
|
1182
|
+
const currentNorm = normalizeArtifactPath(curHref);
|
|
1183
|
+
if (currentNorm !== binding.expectedPath) {
|
|
1184
|
+
binding.active = false;
|
|
1185
|
+
try { binding.port?.close(); } catch (_) {}
|
|
1186
|
+
registeredCards.delete(event.source);
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
// 3. 跨会话违规检查:无论是否已完成握手,若消息声明了非法会话 ID,坚决拒绝并释放临时端口,原卡片通道完好保留
|
|
1192
|
+
if (data.conversationId && data.conversationId !== binding.conversationId) {
|
|
1193
|
+
if (event.ports && event.ports[0]) {
|
|
1194
|
+
const tempPort = event.ports[0];
|
|
1195
|
+
try {
|
|
1196
|
+
tempPort.postMessage({
|
|
1197
|
+
type: data.type === 'AGENT_THINGS_AUTH_REQUEST' ? 'AGENT_THINGS_AUTH_RESPONSE' : 'AGENT_THINGS_ACTION_RESULT',
|
|
1198
|
+
nonce: data.nonce,
|
|
1199
|
+
success: false,
|
|
1200
|
+
error: getUiText(null, 'Session identity mismatch: cross-session action blocked', '会话身份不匹配:禁止跨会话操作'),
|
|
1201
|
+
});
|
|
1202
|
+
tempPort.close?.();
|
|
1203
|
+
} catch (_) {}
|
|
1204
|
+
}
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
// 4. 握手完成后的窗口入口旁路彻底封锁:
|
|
1209
|
+
if (binding.handshakeDone) {
|
|
1210
|
+
// 握手已完成:窗口入口在握手完成后直接拒绝所有操作,绝不转交给端口执行写入 RPC!
|
|
1211
|
+
// 若消息携带了端口,坚决关闭
|
|
1212
|
+
if (event.ports && event.ports[0]) {
|
|
1213
|
+
try { event.ports[0].close?.(); } catch (_) {}
|
|
1214
|
+
}
|
|
1215
|
+
return;
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// 5. 首次握手分支(尚未完成握手)
|
|
1219
|
+
// 约束 1:防住首次握手前的抢占与无令牌绕过
|
|
1220
|
+
// 若绑定中设定了 loadToken,发送方必须提供严格匹配的 loadToken,否则坚决阻断
|
|
1221
|
+
if (binding.loadToken && (!data.loadToken || data.loadToken !== binding.loadToken)) {
|
|
1222
|
+
if (event.ports && event.ports[0]) {
|
|
1223
|
+
try { event.ports[0].close?.(); } catch (_) {}
|
|
1224
|
+
}
|
|
1225
|
+
return;
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
const port = event.ports?.[0];
|
|
1229
|
+
if (!port) return;
|
|
1230
|
+
if (data.type !== 'AGENT_THINGS_AUTH_REQUEST' || binding.handshakePending) {
|
|
1231
|
+
port.close?.();
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
binding.handshakePending = true;
|
|
1235
|
+
let isVerified = false;
|
|
1236
|
+
const currentBrainDir = window.__agentThingsConnection?.brainDir || '';
|
|
1237
|
+
if (/^[a-f0-9]{64}$/.test(binding.digest)) {
|
|
1238
|
+
try {
|
|
1239
|
+
const verifyRes = await fetch(`${getServiceOrigin()}/session/verify-artifact`, {
|
|
1240
|
+
method: 'POST',
|
|
1241
|
+
headers: getServiceHeaders(),
|
|
1242
|
+
body: JSON.stringify({ conversationId: binding.conversationId, digest: binding.digest, brainDir: currentBrainDir }),
|
|
1243
|
+
});
|
|
1244
|
+
const verifyData = await verifyRes.json();
|
|
1245
|
+
if (verifyRes.ok && verifyData.valid) {
|
|
1246
|
+
isVerified = true;
|
|
1247
|
+
}
|
|
1248
|
+
} catch (_) {}
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
binding.handshakePending = false;
|
|
1252
|
+
if (registeredCards.get(event.source) !== binding || !binding.active || !binding.iframe.isConnected) {
|
|
1253
|
+
port.close?.();
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
if (!isVerified) {
|
|
1257
|
+
binding.active = false;
|
|
1258
|
+
registeredCards.delete(event.source);
|
|
1259
|
+
port.close?.();
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
// 前置校验全部通过:安全接收并锁定专属端口
|
|
1264
|
+
binding.port = port;
|
|
1265
|
+
binding.handshakeDone = true;
|
|
1266
|
+
binding.loadToken = null; // 单次消费,防止重放
|
|
1267
|
+
|
|
1268
|
+
// 为专属端口安装消息监听器,后台重启换票及代理写操作收敛于该端口
|
|
1269
|
+
try {
|
|
1270
|
+
binding.port.onmessage = async portEvt => {
|
|
1271
|
+
if (portEvt && portEvt.data && typeof portEvt.data === 'object') {
|
|
1272
|
+
await dispatchCardRequest(binding, binding.port, portEvt.data);
|
|
1273
|
+
}
|
|
1274
|
+
};
|
|
1275
|
+
} catch (_) {}
|
|
1276
|
+
|
|
1277
|
+
// 处理首次握手请求
|
|
1278
|
+
await dispatchCardRequest(binding, binding.port, data);
|
|
1279
|
+
} catch (_) {}
|
|
1280
|
+
};
|
|
1281
|
+
|
|
1282
|
+
const pendingCardLoads = new Map();
|
|
1283
|
+
|
|
1284
|
+
// 原生工件可信装入点拦截处理函数(动态委托)
|
|
1285
|
+
const handleSrcdocSetter = function(iframe, val, originalSet) {
|
|
1286
|
+
pendingCardLoads.get(iframe)?.abort();
|
|
1287
|
+
pendingCardLoads.delete(iframe);
|
|
1288
|
+
const previous = registeredCards.get(iframe.contentWindow);
|
|
1289
|
+
if (previous) {
|
|
1290
|
+
previous.active = false;
|
|
1291
|
+
previous.port?.close();
|
|
1292
|
+
registeredCards.delete(previous.win);
|
|
1293
|
+
}
|
|
1294
|
+
const rawContent = String(val);
|
|
1295
|
+
const isCard = rawContent.includes('AGENT_THINGS_AUTH_REQUEST') || rawContent.includes('agentThingsCard');
|
|
1296
|
+
const isInAux = !!iframe.closest?.('[data-testid="aux-pane-split"]') || iframe.getAttribute('data-testid') === 'artifact-dynamic-ui-iframe';
|
|
1297
|
+
let currentTab = '';
|
|
1298
|
+
try { currentTab = new URL(window.location.href).searchParams.get('tab') || ''; } catch (_) {}
|
|
1299
|
+
const isCardTab = currentTab.includes('things-card.html');
|
|
1300
|
+
|
|
1301
|
+
if (isCard && (isInAux ? isCardTab : true)) {
|
|
1302
|
+
let tabConvId = null;
|
|
1303
|
+
if (isCardTab) {
|
|
1304
|
+
try {
|
|
1305
|
+
const match = currentTab.match(/[/\\\\]([^/\\\\]+)[/\\\\]things-card\.html/i) || currentTab.match(/([^/]+)\/things-card\.html/i);
|
|
1306
|
+
if (match) tabConvId = match[1];
|
|
1307
|
+
} catch (_) {}
|
|
1308
|
+
}
|
|
1309
|
+
if (!tabConvId) {
|
|
1310
|
+
try {
|
|
1311
|
+
const match = rawContent.match(/conversationId\s*=\s*["']([^"']+)["']/);
|
|
1312
|
+
if (match) tabConvId = match[1];
|
|
1313
|
+
} catch (_) {}
|
|
1314
|
+
}
|
|
1315
|
+
if (!tabConvId && typeof window !== 'undefined') {
|
|
1316
|
+
tabConvId = window.location?.pathname?.split('/')?.filter(Boolean)?.pop() || null;
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
// 提取内嵌的完整工件文档(完整涵盖 <!DOCTYPE html> 到 </html>,包含完整 <head> 与 <body>)
|
|
1320
|
+
let fullDoc = rawContent;
|
|
1321
|
+
const cardAnchor = rawContent.indexOf('agentThingsCard') !== -1 ? rawContent.indexOf('agentThingsCard') : rawContent.indexOf('AGENT_THINGS_AUTH_REQUEST');
|
|
1322
|
+
if (cardAnchor !== -1) {
|
|
1323
|
+
const dtIndex = rawContent.lastIndexOf('<!DOCTYPE html>', cardAnchor);
|
|
1324
|
+
const htmlIndex = rawContent.lastIndexOf('<html', cardAnchor);
|
|
1325
|
+
let docStart = -1;
|
|
1326
|
+
if (dtIndex !== -1 && (htmlIndex === -1 || dtIndex < htmlIndex)) {
|
|
1327
|
+
docStart = dtIndex;
|
|
1328
|
+
} else if (htmlIndex !== -1) {
|
|
1329
|
+
docStart = htmlIndex;
|
|
1330
|
+
}
|
|
1331
|
+
if (docStart !== -1) {
|
|
1332
|
+
const docEnd = rawContent.indexOf('</html>', cardAnchor);
|
|
1333
|
+
if (docEnd !== -1) {
|
|
1334
|
+
fullDoc = rawContent.slice(docStart, docEnd + 7);
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
// 检查工件文档边界与恶意追加:
|
|
1340
|
+
// 若为独立 HTML(非官方外层包装模板),必须严格等于 fullDoc;在 </html> 后追加任何脚本均视为非法篡改
|
|
1341
|
+
const isOfficialWrapper = rawContent.startsWith('<!DOCTYPE html><html class="dark"><head><meta http-equiv="Content-Security-Policy"');
|
|
1342
|
+
if (!isOfficialWrapper && rawContent.trim() !== fullDoc.trim()) {
|
|
1343
|
+
return originalSet.call(iframe, val);
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
const controller = new AbortController();
|
|
1347
|
+
pendingCardLoads.set(iframe, controller);
|
|
1348
|
+
const timeout = setTimeout(() => controller.abort(), 5000);
|
|
1349
|
+
// Hold the document until verification completes; no card script runs while awaiting the service.
|
|
1350
|
+
return (async () => {
|
|
1351
|
+
const isCurrent = () => pendingCardLoads.get(iframe) === controller && !controller.signal.aborted
|
|
1352
|
+
&& iframe.isConnected && (isCardTab ? new URL(window.location.href).searchParams.get('tab') === currentTab : true);
|
|
1353
|
+
let verifiedDigest;
|
|
1354
|
+
try {
|
|
1355
|
+
const response = await fetch(`${getServiceOrigin()}/session/verify-artifact`, {
|
|
1356
|
+
method: 'POST',
|
|
1357
|
+
headers: { ...getServiceHeaders(), 'Content-Type': 'application/json' },
|
|
1358
|
+
body: JSON.stringify({ conversationId: tabConvId, content: fullDoc, brainDir: window.__agentThingsConnection?.brainDir || '' }),
|
|
1359
|
+
signal: controller.signal,
|
|
1360
|
+
});
|
|
1361
|
+
const result = await response.json();
|
|
1362
|
+
if (!isCurrent()) return;
|
|
1363
|
+
if (!response.ok || result.valid !== true || !/^[a-f0-9]{64}$/.test(result.expectedDigest)) {
|
|
1364
|
+
return originalSet.call(iframe, val);
|
|
1365
|
+
}
|
|
1366
|
+
verifiedDigest = result.expectedDigest;
|
|
1367
|
+
} catch (_) {
|
|
1368
|
+
// An explicit replacement/disposal must never reinstall an obsolete document.
|
|
1369
|
+
if (pendingCardLoads.get(iframe) === controller && iframe.isConnected
|
|
1370
|
+
&& (isCardTab ? new URL(window.location.href).searchParams.get('tab') === currentTab : true)) originalSet.call(iframe, val);
|
|
1371
|
+
return;
|
|
1372
|
+
} finally { clearTimeout(timeout); }
|
|
1373
|
+
|
|
1374
|
+
let dynamicToken = null;
|
|
1375
|
+
try {
|
|
1376
|
+
const arr = new Uint8Array(16);
|
|
1377
|
+
window.crypto.getRandomValues(arr);
|
|
1378
|
+
dynamicToken = 'dyn-token-' + Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
1379
|
+
} catch (_) {
|
|
1380
|
+
return originalSet.call(iframe, val);
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
if (!registerCardIframe(iframe, tabConvId, {
|
|
1384
|
+
loadToken: dynamicToken,
|
|
1385
|
+
digest: verifiedDigest,
|
|
1386
|
+
loading: true,
|
|
1387
|
+
})) return originalSet.call(iframe, val);
|
|
1388
|
+
|
|
1389
|
+
// 以通过校验的工件内容 fullDoc 为唯一渲染输入,彻底剔除外部未经验证的追加字符与脚本
|
|
1390
|
+
const tokenScript = '<script>window.__agentThingsLoadToken = ' + JSON.stringify(dynamicToken) + ';</' + 'script>';
|
|
1391
|
+
let modifiedHtml = fullDoc;
|
|
1392
|
+
// 彻底清理之前注入过的所有 loadToken 脚本(兼容普通与转义关闭标签)
|
|
1393
|
+
modifiedHtml = modifiedHtml
|
|
1394
|
+
.replace(/<script[^>]*>window\.__agentThingsLoadToken[\s\S]*?<\/script>/gi, '')
|
|
1395
|
+
.replace(/<script[^>]*>window\.__agentThingsLoadToken[\s\S]*?<\\\/script>/gi, '');
|
|
1396
|
+
if (modifiedHtml.includes('<head>')) {
|
|
1397
|
+
modifiedHtml = modifiedHtml.replace('<head>', '<head>' + tokenScript);
|
|
1398
|
+
} else {
|
|
1399
|
+
modifiedHtml = tokenScript + modifiedHtml;
|
|
1400
|
+
}
|
|
1401
|
+
return originalSet.call(iframe, modifiedHtml);
|
|
1402
|
+
})().finally(() => {
|
|
1403
|
+
clearTimeout(timeout);
|
|
1404
|
+
if (pendingCardLoads.get(iframe) === controller) pendingCardLoads.delete(iframe);
|
|
1405
|
+
});
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
return originalSet.call(iframe, val);
|
|
1409
|
+
};
|
|
1410
|
+
|
|
1411
|
+
if (typeof window !== 'undefined') {
|
|
1412
|
+
if (typeof window.addEventListener === 'function') {
|
|
1413
|
+
window.addEventListener('message', onCardMessage);
|
|
1414
|
+
}
|
|
1415
|
+
window.__antigravityHarnessSecurity = {
|
|
1416
|
+
normalizeArtifactPath,
|
|
1417
|
+
registerCardIframe,
|
|
1418
|
+
onCardMessage,
|
|
1419
|
+
registeredCards,
|
|
1420
|
+
sendReplyToCard,
|
|
1421
|
+
handleSrcdocSetter,
|
|
1422
|
+
};
|
|
1423
|
+
|
|
1424
|
+
// 锁定最纯正的底层宿主原生 descriptor(跨 Realm 获取,穿透所有历史猴子补丁)
|
|
1425
|
+
if (typeof HTMLIFrameElement !== 'undefined' && typeof document !== 'undefined') {
|
|
1426
|
+
if (!window.__agentThingsBaseSrcdocDesc || !window.__agentThingsBaseSrcdocDesc.set?.toString()?.includes('[native code]')) {
|
|
1427
|
+
try {
|
|
1428
|
+
const freshRealm = document.createElement('iframe');
|
|
1429
|
+
if (document.body) {
|
|
1430
|
+
document.body.appendChild(freshRealm);
|
|
1431
|
+
const nativeDesc = Object.getOwnPropertyDescriptor(freshRealm.contentWindow?.HTMLIFrameElement?.prototype, 'srcdoc');
|
|
1432
|
+
freshRealm.remove();
|
|
1433
|
+
if (nativeDesc && nativeDesc.set) {
|
|
1434
|
+
window.__agentThingsBaseSrcdocDesc = nativeDesc;
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
} catch (_) {}
|
|
1438
|
+
}
|
|
1439
|
+
if (!window.__agentThingsBaseSrcdocDesc) {
|
|
1440
|
+
window.__agentThingsBaseSrcdocDesc = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'srcdoc');
|
|
1441
|
+
}
|
|
1442
|
+
const baseDesc = window.__agentThingsBaseSrcdocDesc;
|
|
1443
|
+
|
|
1444
|
+
// 原生工件可信装入点拦截器(动态委托模式:固定委托给最新的 handleSrcdocSetter)
|
|
1445
|
+
if (baseDesc && baseDesc.set) {
|
|
1446
|
+
try {
|
|
1447
|
+
Object.defineProperty(HTMLIFrameElement.prototype, 'srcdoc', {
|
|
1448
|
+
get() {
|
|
1449
|
+
return baseDesc.get.call(this);
|
|
1450
|
+
},
|
|
1451
|
+
set(val) {
|
|
1452
|
+
const handler = window.__antigravityHarnessSecurity?.handleSrcdocSetter;
|
|
1453
|
+
if (typeof handler === 'function') {
|
|
1454
|
+
return handler(this, val, baseDesc.set);
|
|
1455
|
+
}
|
|
1456
|
+
return baseDesc.set.call(this, val);
|
|
1457
|
+
},
|
|
1458
|
+
configurable: true,
|
|
1459
|
+
});
|
|
1460
|
+
window.__agentThingsSrcdocHookInstalled = true;
|
|
1461
|
+
} catch (_) {}
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
window.__antigravityHarnessDispose = () => {
|
|
1467
|
+
for (const controller of pendingCardLoads.values()) controller.abort();
|
|
1468
|
+
pendingCardLoads.clear();
|
|
1469
|
+
clearInterval(syncTimer);
|
|
1470
|
+
if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
|
|
1471
|
+
window.removeEventListener('message', onCardMessage);
|
|
1472
|
+
if (window.__agentThingsLocateListener) {
|
|
1473
|
+
window.removeEventListener('message', window.__agentThingsLocateListener);
|
|
1474
|
+
window.__agentThingsLocateListener = null;
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
try { cardObserver?.disconnect(); } catch (_) {}
|
|
1478
|
+
// 注意:不清除活跃卡片端口,以便新宿主桥注入后可信接管原通道
|
|
1479
|
+
};
|
|
1480
|
+
})();
|
|
1481
|
+
|
|
1482
|
+
|
|
1483
|
+
/* Manual session marks. Loaded in a dedicated CDP isolated world. */
|
|
1484
|
+
function installCodexSessionStatus(version, restored, embedded) {
|
|
1485
|
+
if (window.__codexSessionStatus && !embedded?.independent) return;
|
|
1486
|
+
const harness = embedded?.independent ? null : window.__sessionStatusHarness || null;
|
|
1487
|
+
let localCards = null;
|
|
1488
|
+
const send = payload => {
|
|
1489
|
+
if (embedded) embedded.send(payload);
|
|
1490
|
+
else if (harness?.send) harness.send(payload);
|
|
1491
|
+
else window.__codexSessionStatusSend(payload);
|
|
1492
|
+
};
|
|
1493
|
+
const presentation = window.__agentThingsPresentation;
|
|
1494
|
+
let activeLang = embedded?.lang || embedded?.snapshot?.lang || window.__agentThingsConnection?.lang || window.__agentThingsLang || presentation?.lang || 'zh';
|
|
1495
|
+
let ui = presentation?.forLang ? presentation.forLang(activeLang) : null;
|
|
1496
|
+
let strings = ui?.strings || presentation?.strings || {};
|
|
1497
|
+
let labels = ui?.labels || presentation?.labels || {
|
|
1498
|
+
unstarted: '尚未开始', unfinished: '有遗留事项', completed: '全部完成', pushed: '全部完成并已推送',
|
|
1499
|
+
};
|
|
1500
|
+
let taskLabels = ui?.taskLabels || presentation?.taskLabels || {
|
|
1501
|
+
todo: '待开始', in_progress: '进行中', blocked: '受阻', needs_verification: '待验收', done: '已完成',
|
|
1502
|
+
};
|
|
1503
|
+
const S = (key, vars) => (ui?.t ? ui.t(key, vars) : (strings[key] || key));
|
|
1504
|
+
const setLang = nextLang => {
|
|
1505
|
+
const resolved = nextLang === 'en' ? 'en' : nextLang === 'zh' ? 'zh' : activeLang;
|
|
1506
|
+
if (!presentation?.forLang || (resolved === activeLang && ui)) return false;
|
|
1507
|
+
activeLang = resolved;
|
|
1508
|
+
ui = presentation.forLang(activeLang);
|
|
1509
|
+
strings = ui.strings;
|
|
1510
|
+
labels = ui.labels;
|
|
1511
|
+
taskLabels = ui.taskLabels;
|
|
1512
|
+
return true;
|
|
1513
|
+
};
|
|
1514
|
+
const colors = presentation?.colors || { unstarted: '#9098a2', unfinished: '#c89b38', completed: '#548eea', pushed: '#a17be3' };
|
|
1515
|
+
let snapshot = { revision: 0, records: {} };
|
|
1516
|
+
const mounted = new Map();
|
|
1517
|
+
const pending = new Map();
|
|
1518
|
+
const panelStates = new Map(restored?.panelStates || []);
|
|
1519
|
+
let panel = null;
|
|
1520
|
+
let serial = 0;
|
|
1521
|
+
const requestPrefix = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
1522
|
+
let frame = 0;
|
|
1523
|
+
let destroyed = false;
|
|
1524
|
+
const startup = { installedAt: Date.now(), sidebarReadyAt: null, badgesReadyAt: null };
|
|
1525
|
+
function measureStartup() {
|
|
1526
|
+
if (startup.badgesReadyAt !== null) return;
|
|
1527
|
+
const rows = harness?.startupRows ? harness.startupRows().filter(visible)
|
|
1528
|
+
: [...document.querySelectorAll('[data-app-action-sidebar-project-list-id] [data-app-action-sidebar-thread-row]')].filter(row => ['local', 'remote'].includes(row.getAttribute('data-app-action-sidebar-thread-kind')) && visible(row));
|
|
1529
|
+
if (!rows.length) return;
|
|
1530
|
+
startup.sidebarReadyAt ??= Date.now();
|
|
1531
|
+
if (rows.every(row => row.querySelector('[data-codex-session-status]'))) startup.badgesReadyAt = Date.now();
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
function rememberPanel(target) {
|
|
1535
|
+
const active = target.root.shadowRoot.activeElement;
|
|
1536
|
+
const state = { key: target.entry.key, mode: target.mode, dirty: target.dirty, revision: target.revision,
|
|
1537
|
+
note: target.note.value, progress: target.progress.value, draft: { ...target.draft },
|
|
1538
|
+
remainingExpanded: target.remainingExpanded, scrollTop: target.body.scrollTop,
|
|
1539
|
+
noteScrollTop: target.note.scrollTop, selectionStart: target.note.selectionStart, selectionEnd: target.note.selectionEnd,
|
|
1540
|
+
focus: active === target.note ? 'note' : active === target.progress ? 'progress' : null,
|
|
1541
|
+
error: target.error.textContent, conflict: target.conflict };
|
|
1542
|
+
panelStates.set(target.entry.key, state);
|
|
1543
|
+
try { sessionStorage.setItem(`codex-session-status-panel:v1:${target.entry.key}`, JSON.stringify(state)); } catch { /* Keep the in-memory copy when storage is unavailable. */ }
|
|
1544
|
+
return state;
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
function rememberedPanel(key) {
|
|
1548
|
+
if (panelStates.has(key)) return panelStates.get(key);
|
|
1549
|
+
try {
|
|
1550
|
+
const state = JSON.parse(sessionStorage.getItem(`codex-session-status-panel:v1:${key}`));
|
|
1551
|
+
if (state && ['overview', 'edit', 'history'].includes(state.mode)) { panelStates.set(key, state); return state; }
|
|
1552
|
+
} catch { /* Start from the current saved record if a browser cache cannot be read. */ }
|
|
1553
|
+
return null;
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
function restorePanel(target, state) {
|
|
1557
|
+
target.remainingExpanded = state.remainingExpanded;
|
|
1558
|
+
if (state.dirty) {
|
|
1559
|
+
target.dirty = true; target.revision = state.revision;
|
|
1560
|
+
target.draft = state.draft || { state: recordFor(state.key)?.state || 'unfinished',
|
|
1561
|
+
progress: state.progress === '' ? null : Number(state.progress), note: state.note || '' };
|
|
1562
|
+
target.note.value = state.note; updateDraft(target, target.draft); target.progress.value = state.progress;
|
|
1563
|
+
}
|
|
1564
|
+
target.restoreScroll = state.scrollTop || 0;
|
|
1565
|
+
target.setView(state.mode || (state.dirty ? 'edit' : 'overview'));
|
|
1566
|
+
target.error.textContent = state.error || '';
|
|
1567
|
+
target.conflict = Boolean(state.dirty && state.conflict);
|
|
1568
|
+
target.resolveConflict.hidden = !target.conflict;
|
|
1569
|
+
if (target.mode === 'edit') {
|
|
1570
|
+
if (state.focus === 'note') {
|
|
1571
|
+
target.note.focus({ preventScroll: true });
|
|
1572
|
+
target.note.setSelectionRange(state.selectionStart ?? target.note.value.length, state.selectionEnd ?? target.note.value.length);
|
|
1573
|
+
} else if (state.focus === 'progress') target.progress.focus({ preventScroll: true });
|
|
1574
|
+
target.note.scrollTop = state.noteScrollTop || 0;
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
function panelEvent(action, entry) {
|
|
1579
|
+
try { send(JSON.stringify({ type: 'panel-event', action,
|
|
1580
|
+
requestId: `${requestPrefix}:${++serial}`, key: entry.key })); } catch { /* Diagnostic only. */ }
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
function element(tag, text, parent, className) {
|
|
1584
|
+
const node = document.createElement(tag);
|
|
1585
|
+
if (text != null) node.textContent = text;
|
|
1586
|
+
if (className) node.className = className;
|
|
1587
|
+
parent?.append(node);
|
|
1588
|
+
return node;
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
function recordFor(key) {
|
|
1592
|
+
const record = snapshot.records[key];
|
|
1593
|
+
return record?.state ? record : null;
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
function summary(key) {
|
|
1597
|
+
const record = recordFor(key);
|
|
1598
|
+
if (!record) return S('badgeNotOrganized');
|
|
1599
|
+
return `${labels[record.state]}${record.progress === null ? S('badgeProgressUnrecordedSuffix') : ` · ${record.progress}%`}`;
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
function makeRing(button, record, pie = false, loading = false) {
|
|
1603
|
+
button.replaceChildren();
|
|
1604
|
+
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
|
1605
|
+
svg.setAttribute('viewBox', '0 0 24 24');
|
|
1606
|
+
svg.setAttribute('width', '24'); svg.setAttribute('height', '24');
|
|
1607
|
+
svg.setAttribute('aria-hidden', 'true');
|
|
1608
|
+
if (loading) {
|
|
1609
|
+
svg.setAttribute('class', 'loading');
|
|
1610
|
+
const circle = document.createElementNS(svg.namespaceURI, 'circle');
|
|
1611
|
+
for (const [name, value] of Object.entries({ cx: 12, cy: 12, r: 10, fill: 'none', stroke: '#0169cc', 'stroke-width': 1.6, 'stroke-dasharray': '42 63', 'stroke-linecap': 'round' })) circle.setAttribute(name, value);
|
|
1612
|
+
svg.append(circle); button.append(svg); return;
|
|
1613
|
+
}
|
|
1614
|
+
const color = record ? colors[record.state] : '#858991';
|
|
1615
|
+
for (const progress of pie ? [null] : [null, record?.progress]) {
|
|
1616
|
+
if (progress === undefined || progress === null && svg.childElementCount) continue;
|
|
1617
|
+
const circle = document.createElementNS(svg.namespaceURI, 'circle');
|
|
1618
|
+
for (const [name, value] of Object.entries({ cx: 12, cy: 12, r: 10, fill: 'none', stroke: color, 'stroke-width': 1.6 })) {
|
|
1619
|
+
circle.setAttribute(name, value);
|
|
1620
|
+
}
|
|
1621
|
+
if (progress === null) circle.setAttribute('opacity', pie ? '1' : record?.progress != null ? '.25' : '.85');
|
|
1622
|
+
else {
|
|
1623
|
+
circle.setAttribute('stroke-dasharray', `${62.832 * progress / 100} 62.832`);
|
|
1624
|
+
circle.setAttribute('transform', 'rotate(-90 12 12)');
|
|
1625
|
+
circle.setAttribute('stroke-linecap', 'round');
|
|
1626
|
+
}
|
|
1627
|
+
svg.append(circle);
|
|
1628
|
+
}
|
|
1629
|
+
if (pie && record?.progress > 0) {
|
|
1630
|
+
const sector = document.createElementNS(svg.namespaceURI, 'path');
|
|
1631
|
+
const angle = record.progress / 100 * Math.PI * 2;
|
|
1632
|
+
const x = 12 + 7.4 * Math.sin(angle);
|
|
1633
|
+
const y = 12 - 7.4 * Math.cos(angle);
|
|
1634
|
+
sector.setAttribute('d', record.progress === 100
|
|
1635
|
+
? 'M12 4.6a7.4 7.4 0 1 1 0 14.8a7.4 7.4 0 1 1 0-14.8'
|
|
1636
|
+
: `M12 12L12 4.6A7.4 7.4 0 ${record.progress > 50 ? 1 : 0} 1 ${x} ${y}Z`);
|
|
1637
|
+
sector.setAttribute('fill', color); sector.setAttribute('class', 'progress-pie');
|
|
1638
|
+
svg.append(sector);
|
|
1639
|
+
}
|
|
1640
|
+
if (pie || record) {
|
|
1641
|
+
const text = document.createElementNS(svg.namespaceURI, 'text');
|
|
1642
|
+
text.setAttribute('x', '12'); text.setAttribute('y', '12.4');
|
|
1643
|
+
text.setAttribute('text-anchor', 'middle'); text.setAttribute('dominant-baseline', 'middle');
|
|
1644
|
+
text.setAttribute('fill', color);
|
|
1645
|
+
text.setAttribute('style', `font:600 ${pie ? 6.4 : 8}px -apple-system,BlinkMacSystemFont,sans-serif;font-variant-numeric:tabular-nums`);
|
|
1646
|
+
text.textContent = record?.progress == null ? '—' : pie ? `${record.progress}%` : String(record.progress);
|
|
1647
|
+
if (record?.progress == null) text.setAttribute('class', 'progress-unknown');
|
|
1648
|
+
svg.append(text);
|
|
1649
|
+
}
|
|
1650
|
+
button.append(svg);
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
function paintVisibility(entry) {
|
|
1654
|
+
const selected = harness?.isRowSelected ? harness.isRowSelected(entry.row) : entry.row.getAttribute('data-app-action-sidebar-thread-selected') === 'true';
|
|
1655
|
+
entry.host.toggleAttribute('data-visible', Boolean(recordFor(entry.key) || snapshot.analyzingKeys?.includes(entry.key) || entry.hovered || selected));
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
function paint(entry) {
|
|
1659
|
+
const record = recordFor(entry.key);
|
|
1660
|
+
const loading = snapshot.analyzingKeys?.includes(entry.key) || false;
|
|
1661
|
+
const ringKey = JSON.stringify([record?.state, record?.progress, loading]);
|
|
1662
|
+
if (entry.ringKey !== ringKey) { makeRing(entry.button, record, false, loading); entry.ringKey = ringKey; }
|
|
1663
|
+
paintVisibility(entry);
|
|
1664
|
+
entry.button.setAttribute('aria-busy', String(loading));
|
|
1665
|
+
const description = S('ringAriaPattern', { title: entry.title, summary: loading ? S('ringUpdating') : summary(entry.key) });
|
|
1666
|
+
entry.button.setAttribute('aria-label', description);
|
|
1667
|
+
entry.button.title = description;
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
function unmount(entry) {
|
|
1671
|
+
harness?.unmount?.(entry);
|
|
1672
|
+
entry.row.removeEventListener('pointerenter', entry.onEnter); entry.row.removeEventListener('pointerleave', entry.onLeave);
|
|
1673
|
+
entry.host.remove();
|
|
1674
|
+
for (const [name, previous] of Object.entries(entry.original)) {
|
|
1675
|
+
if (previous.value) entry.slot.style.setProperty(name, previous.value, previous.priority);
|
|
1676
|
+
else entry.slot.style.removeProperty(name);
|
|
1677
|
+
}
|
|
1678
|
+
if (entry.slot.classList.contains('status-slot-injected')) entry.slot.remove();
|
|
1679
|
+
mounted.delete(entry.row);
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
function attachHost(slot, emptyWrapper, placeholder) {
|
|
1683
|
+
const original = Object.fromEntries(['width', 'min-width', 'flex-basis'].map(name => [name, {
|
|
1684
|
+
value: slot.style.getPropertyValue(name), priority: slot.style.getPropertyPriority(name)
|
|
1685
|
+
}]));
|
|
1686
|
+
for (const name of Object.keys(original)) slot.style.setProperty(name, '24px');
|
|
1687
|
+
const target = emptyWrapper ? placeholder : slot;
|
|
1688
|
+
for (const existing of target.querySelectorAll('span[data-codex-session-status]')) {
|
|
1689
|
+
existing.remove();
|
|
1690
|
+
}
|
|
1691
|
+
const host = element('span', null, target);
|
|
1692
|
+
host.setAttribute('data-codex-session-status', '');
|
|
1693
|
+
host.style.cssText = 'display:flex;width:24px;height:28px;flex:none;align-items:center;justify-content:center';
|
|
1694
|
+
const shadow = host.attachShadow({ mode: 'open' });
|
|
1695
|
+
element('style', `:host{opacity:0}:host([data-visible]),:host(:focus-within){opacity:1}@keyframes status-spin{to{transform:rotate(360deg)}}svg.loading{animation:status-spin .85s linear infinite;transform-origin:center}button{all:unset;box-sizing:border-box;width:28px;height:28px;display:grid;place-items:center;cursor:pointer;border-radius:7px}button:hover{background:color-mix(in srgb,currentColor 8%,transparent)}button:focus-visible{outline:2px solid #0169cc;outline-offset:1px}svg{display:block;pointer-events:none}`, shadow);
|
|
1696
|
+
const button = element('button', null, shadow);
|
|
1697
|
+
button.type = 'button'; button.setAttribute('aria-haspopup', 'dialog'); button.setAttribute('aria-expanded', 'false');
|
|
1698
|
+
return { host, button, original };
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
function reconcile() {
|
|
1702
|
+
frame = 0;
|
|
1703
|
+
if (destroyed) return;
|
|
1704
|
+
measureStartup();
|
|
1705
|
+
if (harness?.reconcile) {
|
|
1706
|
+
harness.reconcile({ mounted, unmount, attachHost, paint, paintVisibility, openPanel, closePanel, isPanelBusy: () => panel?.busy, isPanelEntry: e => panel?.entry === e });
|
|
1707
|
+
measureStartup();
|
|
1708
|
+
if (panel && (!panel.entry.host.isConnected || !visible(panel.entry.host))) closePanel(false);
|
|
1709
|
+
else positionPanel();
|
|
1710
|
+
return;
|
|
1711
|
+
}
|
|
1712
|
+
for (const entry of mounted.values()) {
|
|
1713
|
+
if (!entry.row.isConnected || !entry.host.isConnected || !entry.row.closest('[data-app-action-sidebar-project-list-id]') ||
|
|
1714
|
+
!['local', 'remote'].includes(entry.row.getAttribute('data-app-action-sidebar-thread-kind')) ||
|
|
1715
|
+
entry.row.getAttribute('data-app-action-sidebar-thread-id') !== entry.threadId ||
|
|
1716
|
+
entry.row.getAttribute('data-app-action-sidebar-thread-host-id') !== entry.rawHost) unmount(entry);
|
|
1717
|
+
}
|
|
1718
|
+
const rows = document.querySelectorAll('[data-app-action-sidebar-project-list-id] [data-app-action-sidebar-thread-row]');
|
|
1719
|
+
for (const row of rows) {
|
|
1720
|
+
const kind = row.getAttribute('data-app-action-sidebar-thread-kind');
|
|
1721
|
+
if (kind !== 'local' && kind !== 'remote') continue;
|
|
1722
|
+
const threadId = row.getAttribute('data-app-action-sidebar-thread-id');
|
|
1723
|
+
if (!threadId) continue;
|
|
1724
|
+
const titleNode = row.querySelector('[data-thread-title]');
|
|
1725
|
+
const title = row.getAttribute('data-app-action-sidebar-thread-title') || titleNode?.textContent || S('sessionFallbackTitle');
|
|
1726
|
+
const existing = mounted.get(row);
|
|
1727
|
+
if (existing) {
|
|
1728
|
+
if (existing.title !== title) { existing.title = title; paint(existing); }
|
|
1729
|
+
paintVisibility(existing);
|
|
1730
|
+
continue;
|
|
1731
|
+
}
|
|
1732
|
+
// Target the existing reserved leading slot; leave occupied native icons intact.
|
|
1733
|
+
const trigger = titleNode?.closest('[data-thread-title-trigger]');
|
|
1734
|
+
const slot = trigger?.previousElementSibling;
|
|
1735
|
+
if (!slot || !slot.classList.contains('w-4')) continue;
|
|
1736
|
+
// Native rows keep an empty relative wrapper inside the leading slot.
|
|
1737
|
+
const placeholder = slot.firstElementChild;
|
|
1738
|
+
const emptyWrapper = slot.childElementCount === 1 && placeholder.tagName === 'DIV' &&
|
|
1739
|
+
placeholder.childElementCount === 0 && !placeholder.textContent.trim();
|
|
1740
|
+
if (slot.childElementCount !== 0 && !emptyWrapper) continue;
|
|
1741
|
+
const rawHost = row.getAttribute('data-app-action-sidebar-thread-host-id');
|
|
1742
|
+
const key = JSON.stringify([rawHost || (kind === 'remote' ? 'cloud' : 'local'), threadId]);
|
|
1743
|
+
const { host, button, original } = attachHost(slot, emptyWrapper, placeholder);
|
|
1744
|
+
const entry = { row, key, threadId, rawHost, title, slot, host, button, original, hovered: row.matches(':hover') };
|
|
1745
|
+
entry.onEnter = () => { entry.hovered = true; paintVisibility(entry); };
|
|
1746
|
+
entry.onLeave = () => { entry.hovered = false; paintVisibility(entry); };
|
|
1747
|
+
row.addEventListener('pointerenter', entry.onEnter); row.addEventListener('pointerleave', entry.onLeave);
|
|
1748
|
+
for (const type of ['pointerdown', 'dblclick']) host.addEventListener(type, e => e.stopPropagation());
|
|
1749
|
+
button.addEventListener('click', async e => {
|
|
1750
|
+
e.preventDefault(); e.stopPropagation();
|
|
1751
|
+
if (panel?.busy) return;
|
|
1752
|
+
if (panel?.entry === entry) closePanel();
|
|
1753
|
+
else { closePanel(); openPanel(entry); }
|
|
1754
|
+
});
|
|
1755
|
+
mounted.set(row, entry); paint(entry);
|
|
1756
|
+
}
|
|
1757
|
+
if (panel && (!panel.entry.host.isConnected || !visible(panel.entry.host))) closePanel(false);
|
|
1758
|
+
else positionPanel();
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
function schedule() {
|
|
1762
|
+
if (!frame && !destroyed) frame = requestAnimationFrame(reconcile);
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
function visible(node) {
|
|
1766
|
+
const r = node.getBoundingClientRect();
|
|
1767
|
+
return r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight;
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
function positionPanel() {
|
|
1771
|
+
if (!panel) return;
|
|
1772
|
+
if (embedded) {
|
|
1773
|
+
panel.root.setAttribute('data-color-mode', embedded.theme || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'));
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
// Foreground colors change when the host window becomes inactive.
|
|
1777
|
+
// Read the painted page background, whose luminance represents its theme.
|
|
1778
|
+
let mode = null;
|
|
1779
|
+
for (let node = panel.entry.row; node; node = node.parentElement) {
|
|
1780
|
+
const rgba = getComputedStyle(node).backgroundColor.match(/[\d.]+/g)?.map(Number);
|
|
1781
|
+
if (!rgba || (rgba[3] ?? 1) < .95) continue;
|
|
1782
|
+
mode = rgba[0] * .2126 + rgba[1] * .7152 + rgba[2] * .0722 < 150 ? 'dark' : 'light';
|
|
1783
|
+
break;
|
|
1784
|
+
}
|
|
1785
|
+
mode ||= panel.root.getAttribute('data-color-mode') || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
|
1786
|
+
if (panel.root.getAttribute('data-color-mode') !== mode) panel.root.setAttribute('data-color-mode', mode);
|
|
1787
|
+
const anchor = panel.entry.host.getBoundingClientRect();
|
|
1788
|
+
const rect = panel.shell.getBoundingClientRect();
|
|
1789
|
+
const left = Math.max(8, Math.min(anchor.right + 10, innerWidth - rect.width - 8));
|
|
1790
|
+
const top = Math.max(8, Math.min(anchor.top - 12, innerHeight - rect.height - 8));
|
|
1791
|
+
panel.shell.style.left = `${left}px`; panel.shell.style.top = `${top}px`;
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
function updateDraft(target, patch) {
|
|
1795
|
+
target.draft = presentation ? presentation.draftTransition({ draft: target.draft, baseRevision: target.revision }, { type: 'patch', patch }).draft : { ...target.draft, ...patch };
|
|
1796
|
+
target.dirty = true;
|
|
1797
|
+
const draft = target.draft;
|
|
1798
|
+
target.progress.value = draft.progress ?? '';
|
|
1799
|
+
target.slider.value = draft.progress ?? 0;
|
|
1800
|
+
target.range.style.setProperty('--fill', `${draft.progress ?? 0}%`);
|
|
1801
|
+
target.range.style.setProperty('--mark', colors[draft.state] || colors.unfinished);
|
|
1802
|
+
for (const [state, button] of target.choices) button.setAttribute('aria-pressed', String(draft.state === state));
|
|
1803
|
+
rememberPanel(target);
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
function refreshPanel() {
|
|
1807
|
+
if (!panel) return;
|
|
1808
|
+
const target = panel, record = recordFor(target.entry.key);
|
|
1809
|
+
target.choices.get('pushed').hidden = target.projectGit?.hasRemote !== true;
|
|
1810
|
+
target.git.textContent = target.projectGit?.status === 'unknown' ? S('gitCheckUnavailable') : '';
|
|
1811
|
+
if (!target.busy && !target.dirty) {
|
|
1812
|
+
target.revision = snapshot.records[target.entry.key]?.revision ?? 0;
|
|
1813
|
+
target.draft = presentation ? presentation.draftTransition({}, { type: 'begin', record, revision: target.revision }).draft : { state: record?.state || 'unfinished', progress: record?.progress ?? null, note: record?.note || '' };
|
|
1814
|
+
target.note.value = target.draft.note;
|
|
1815
|
+
target.progress.value = target.draft.progress ?? '';
|
|
1816
|
+
target.slider.value = target.draft.progress ?? 0;
|
|
1817
|
+
target.range.style.setProperty('--fill', `${target.draft.progress ?? 0}%`);
|
|
1818
|
+
target.range.style.setProperty('--mark', colors[target.draft.state]);
|
|
1819
|
+
for (const [state, button] of target.choices) button.setAttribute('aria-pressed', String(target.draft.state === state));
|
|
1820
|
+
}
|
|
1821
|
+
makeRing(target.titleProgress, record, true);
|
|
1822
|
+
target.heading.setAttribute('aria-label', `${target.entry.title}, ${summary(target.entry.key)}`);
|
|
1823
|
+
target.statusLabel.textContent = record ? labels[record.state] : S('statusUnrecorded');
|
|
1824
|
+
target.statusDot.style.borderColor = record ? colors[record.state] : colors.unstarted;
|
|
1825
|
+
target.timestamp.textContent = record ? (ui?.formatDate ? ui.formatDate(record.updatedAt) : new Date(record.updatedAt).toLocaleString(activeLang === 'en' ? 'en-US' : 'zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' })) : '';
|
|
1826
|
+
target.scoreNumber.textContent = record?.progress ?? '—';
|
|
1827
|
+
target.scoreUnit.hidden = record?.progress == null;
|
|
1828
|
+
target.meter.style.setProperty('--fill', `${record?.progress ?? 0}%`);
|
|
1829
|
+
target.meter.style.setProperty('--mark', record ? colors[record.state] : colors.unstarted);
|
|
1830
|
+
target.sourceLabel.textContent = record ? (record.source === 'analysis' ? S('sourceAuto') : S('sourceManual')) : '';
|
|
1831
|
+
const summaryText = record?.note || '';
|
|
1832
|
+
if (target.overviewSummary.textContent !== summaryText) {
|
|
1833
|
+
target.overviewSummary.textContent = summaryText;
|
|
1834
|
+
target.setSummaryExpanded(false);
|
|
1835
|
+
}
|
|
1836
|
+
target.summaryBlock.hidden = !summaryText;
|
|
1837
|
+
target.noteOpen.textContent = record?.note ? S('editLabel') : S('addLabel');
|
|
1838
|
+
target.analyze.disabled = presentation ? presentation.analysisDisabled(target.busy || target.capabilities?.analyze === false, target.analyzing, target.updateInfo?.update?.stage) : target.busy || target.analyzing || ['waiting', 'installing'].includes(target.updateInfo?.update?.stage);
|
|
1839
|
+
target.renderHistory?.();
|
|
1840
|
+
positionPanel();
|
|
1841
|
+
target.scheduleMarquees?.();
|
|
1842
|
+
if (target.restoreScroll != null && (target.mode === 'edit' || target.analysisState)) {
|
|
1843
|
+
target.body.scrollTop = target.restoreScroll; target.restoreScroll = null;
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
async function save(patch = {}, reset = false, target = panel) {
|
|
1848
|
+
if (!target || target.busy) return false;
|
|
1849
|
+
const raw = target.progress.value.trim();
|
|
1850
|
+
const progress = raw === '' ? null : Number(raw);
|
|
1851
|
+
if (!reset && progress !== null && (!Number.isInteger(progress) || progress < 0 || progress > 100)) {
|
|
1852
|
+
target.error.textContent = S('invalidProgressError'); return false;
|
|
1853
|
+
}
|
|
1854
|
+
const record = reset ? null : { ...target.draft, progress, note: target.note.value, ...patch };
|
|
1855
|
+
target.busy = true; target.error.textContent = '';
|
|
1856
|
+
for (const control of target.controls) control.disabled = true;
|
|
1857
|
+
try {
|
|
1858
|
+
const state = await target.request('update', 7000, { expectedRevision: target.revision, record });
|
|
1859
|
+
target.dirty = false;
|
|
1860
|
+
target.conflict = false; target.resolveConflict.hidden = true;
|
|
1861
|
+
rememberPanel(target);
|
|
1862
|
+
// 保存成功即补读一次,并吸收保存期间到达的待刷新,避免 finally 再读一次。
|
|
1863
|
+
target.syncVersion = panelVersion(target.entry.key); target.syncPending = false;
|
|
1864
|
+
if (embedded && state) target.showHistory(state); else target.pollHistory?.();
|
|
1865
|
+
return true;
|
|
1866
|
+
} catch (error) {
|
|
1867
|
+
target.error.textContent = error.message;
|
|
1868
|
+
if ((error.code === 'REVISION_CONFLICT' || (!error.code && (error.message === '此会话已在其他窗口更新,请重新确认' || error.message === S('conflictDetectedFeedback')))) && target.dirty && !reset) {
|
|
1869
|
+
target.conflict = true;
|
|
1870
|
+
target.resolveConflict.hidden = false;
|
|
1871
|
+
rememberPanel(target);
|
|
1872
|
+
}
|
|
1873
|
+
return false;
|
|
1874
|
+
} finally {
|
|
1875
|
+
target.busy = false;
|
|
1876
|
+
for (const control of target.controls) control.disabled = false;
|
|
1877
|
+
if (target.syncPending && panel === target) syncPanel(target);
|
|
1878
|
+
if (panel === target) { target.analyze.disabled = target.analyzing; refreshPanel(); }
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
async function rebaseDraft(target) {
|
|
1883
|
+
if (target.busy || !target.conflict) return;
|
|
1884
|
+
target.busy = true;
|
|
1885
|
+
for (const control of target.controls) control.disabled = true;
|
|
1886
|
+
try {
|
|
1887
|
+
const state = await target.request('analysis-state', 7000);
|
|
1888
|
+
target.revision = snapshot.records[target.entry.key]?.revision ?? 0;
|
|
1889
|
+
target.conflict = false; target.resolveConflict.hidden = true;
|
|
1890
|
+
target.error.textContent = S('conflictReloadedFeedback');
|
|
1891
|
+
target.showHistory?.(state);
|
|
1892
|
+
rememberPanel(target);
|
|
1893
|
+
} catch (error) {
|
|
1894
|
+
target.error.textContent = error.message;
|
|
1895
|
+
} finally {
|
|
1896
|
+
target.busy = false;
|
|
1897
|
+
for (const control of target.controls) control.disabled = false;
|
|
1898
|
+
if (panel === target) {
|
|
1899
|
+
if (target.syncPending) syncPanel(target);
|
|
1900
|
+
refreshPanel();
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
function cancelRead(requestId, request) {
|
|
1906
|
+
if (!['project-git', 'analysis-state', 'app-update-info'].includes(request.type) || !(embedded || harness?.supportsRequestCancellation)) return;
|
|
1907
|
+
try { send(JSON.stringify({ type: 'cancel-request', requestId: `${requestPrefix}:${++serial}`, cancelRequestId: requestId })); } catch { /* Local cleanup still runs if the host has disconnected. */ }
|
|
1908
|
+
}
|
|
1909
|
+
function closePanel(restoreFocus = true) {
|
|
1910
|
+
if (!panel || panel.busy) return;
|
|
1911
|
+
for (const [id, request] of pending) {
|
|
1912
|
+
if (request.key === panel.entry.key && ['project-git', 'analysis-state', 'app-update-info'].includes(request.type) && (embedded || harness?.supportsRequestCancellation)) {
|
|
1913
|
+
cancelRead(id, request); clearTimeout(request.timer); pending.delete(id);
|
|
1914
|
+
request.reject(Object.assign(new Error(S('cardRequestCancelled')), { code: 'REQUEST_CANCELLED' }));
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
rememberPanel(panel);
|
|
1918
|
+
panelEvent('close', panel.entry);
|
|
1919
|
+
const target = panel; panel = null;
|
|
1920
|
+
clearTimeout(target.pollTimer); cancelAnimationFrame(target.marqueeFrame);
|
|
1921
|
+
clearTimeout(target.updateTimer);
|
|
1922
|
+
target.resizeObserver?.disconnect();
|
|
1923
|
+
target.root.remove(); target.entry.button.setAttribute('aria-expanded', 'false');
|
|
1924
|
+
if (restoreFocus && target.entry.host.isConnected) target.entry.button.focus();
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
function openPanel(entry) {
|
|
1928
|
+
if (panel) return;
|
|
1929
|
+
const root = element('div', null, embedded?.container || document.body);
|
|
1930
|
+
root.setAttribute('data-codex-session-status-panel', '');
|
|
1931
|
+
if (!embedded) root.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483646';
|
|
1932
|
+
const shadow = root.attachShadow({ mode: 'open' });
|
|
1933
|
+
element('style', `
|
|
1934
|
+
:host{--accent:${presentation?.accent.normal || '#0169cc'};--accent-hover:${presentation?.accent.hover || '#005bb3'};--ink:#e6edf3;--secondary:#a0a6ad;--muted:#828c96;--note:#bbc3ca;--track:#ffffff12;--line:#ffffff14;--input-border:#ffffff18;--input-bg:#ffffff03;--hover:#ffffff09;--selected:#ffffff10;--source-bg:#ffffff0a;--number-line:#ffffff25;--thumb:#e6edf3;--thumb-edge:#ffffff30;--danger:#ef7777;--error:#f7ad86;font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:var(--ink);color-scheme:dark}
|
|
1935
|
+
*{box-sizing:border-box;scrollbar-width:none;-ms-overflow-style:none}*::-webkit-scrollbar{display:none;width:0;height:0}button,input,textarea{font:inherit}button{cursor:pointer}button,input,textarea{color:inherit}[hidden]{display:none!important}
|
|
1936
|
+
.shell{position:fixed;pointer-events:auto;width:${presentation?.layout.panelWidth || 340}px;max-width:calc(100vw - 16px);max-height:calc(100vh - 16px);display:flex;flex-direction:column;overflow:hidden;--panel-bg:#0e1318;background:var(--panel-bg);border:1px solid #ffffff1c;border-radius:20px;box-shadow:0 16px 54px #0005;padding:22px 20px 14px}
|
|
1937
|
+
.shell:hover{--panel-bg:#1f242a}.title-heading{display:flex;flex:none;align-items:flex-start;gap:10px;margin-right:24px;border-radius:5px;outline-offset:4px}
|
|
1938
|
+
h2.title{font-size:24px;font-weight:650;line-height:1.3;letter-spacing:-.5px;margin:0;min-width:0;overflow-wrap:anywhere;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden}
|
|
1939
|
+
.title-progress{display:flex;flex:none;width:32px;height:32px;margin-top:1px}.title-progress svg{width:32px;height:32px}.title-progress text{opacity:0}.title-progress text.progress-unknown{opacity:1}.title-heading:hover .progress-pie,.title-heading:focus-visible .progress-pie{opacity:0}.title-heading:hover text,.title-heading:focus-visible text{opacity:1}
|
|
1940
|
+
.close{position:absolute;right:12px;top:7px;border:0;background:none;color:var(--secondary);font-size:0;width:28px;height:28px;padding:0}.close::before,.close::after{content:"";position:absolute;left:7px;top:13px;width:14px;height:1px;background:currentColor;transform:rotate(45deg)}.close::after{transform:rotate(-45deg)}
|
|
1941
|
+
.open-pane{position:absolute;right:44px;top:7px;border:0;background:none;color:var(--secondary);width:28px;height:28px;padding:0;border-radius:6px}.open-pane:hover{color:var(--ink);background:var(--hover)}.open-pane::before{content:"";position:absolute;left:7px;top:8px;width:14px;height:12px;border:1.3px solid currentColor;border-radius:3px;box-sizing:border-box}.open-pane::after{content:"";position:absolute;left:16px;top:8px;width:1.3px;height:12px;background:currentColor}.shell.has-open-pane .title-heading{margin-right:56px}.open-pane-tip{position:absolute;right:0;top:calc(100% + 6px);padding:5px 8px;border-radius:6px;background:var(--panel-bg);color:var(--ink);border:1px solid var(--line);box-shadow:0 4px 14px #0003;font-size:11px;line-height:1.4;white-space:nowrap;pointer-events:none;opacity:0;visibility:hidden;transition:opacity .08s,visibility 0s;z-index:2}.open-pane:is(:hover,:focus-visible) .open-pane-tip{opacity:1;visibility:visible;transition-delay:.15s}
|
|
1942
|
+
.panel-body{overflow:auto;min-height:0;margin-top:23px;scrollbar-width:none;-ms-overflow-style:none}.panel-body::-webkit-scrollbar{display:none;width:0;height:0}.view{padding-bottom:4px}.status-line{display:flex;align-items:center;justify-content:space-between;gap:16px}.status-block{transform:translateY(2px);min-width:0;flex:1}.status-name{display:flex;align-items:center;gap:7px;line-height:18px;min-width:0}.status-name>span:last-child,.timestamp{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.state-dot{width:10px;height:10px;border:1.5px solid;border-radius:50%;flex:none}.timestamp{font-size:11px;line-height:16px;color:var(--secondary);margin-top:2px;margin-left:17px}.score{display:flex;align-items:baseline;line-height:1;font-variant-numeric:tabular-nums;flex:none}.score-number{font-size:39px;font-weight:550;letter-spacing:-1px}.score-unit{font-size:15px;color:var(--secondary);margin-left:3px}
|
|
1943
|
+
.meter{height:4px;background:var(--track);border-radius:3px;margin:14px 0 10px;overflow:hidden}.meter::after{content:"";display:block;height:100%;width:var(--fill);background:var(--mark);border-radius:inherit}.totals-row{display:flex;justify-content:space-between;align-items:center;gap:8px;color:var(--secondary)}.totals,.source-label{font-size:11px;font-weight:400;line-height:16px}.source-label{margin-left:auto;text-align:right;white-space:nowrap}.summary-block{position:relative;margin:16px 0;outline:none}.overview-summary{font-size:13px;line-height:1.65;color:var(--note);display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;white-space:pre-wrap;overflow-wrap:anywhere}.summary-expand{position:absolute;right:0;bottom:0;border:0;background:linear-gradient(to right,transparent,var(--panel-bg) 18px);padding:0 0 0 22px;color:var(--secondary);font-size:12px;line-height:21.45px;white-space:nowrap}.summary-expand:hover{color:inherit}.summary-block.expanded .overview-summary{display:block;-webkit-line-clamp:unset}.summary-block.expanded .summary-expand{position:static;display:block;margin-left:auto;padding-left:0;background:none}
|
|
1944
|
+
.actions{display:flex;align-items:center;gap:14px;margin:18px 0 22px}.primary{border:0;background:var(--accent);color:#fff;border-radius:9px;padding:9px 14px;font-weight:550;min-height:36px;white-space:nowrap}.primary:hover{background:var(--accent-hover);color:#fff}.text-button,.clear,.back{border:0;background:none;padding:0;color:var(--secondary);font-size:12px;white-space:nowrap}.text-button:hover,.back:hover{color:inherit}.actions .clear{margin-left:auto;font-size:11px;color:var(--muted);white-space:nowrap;transition:color .12s}.actions .clear:hover{color:var(--danger)}.actions .clear{position:relative}.clear-tooltip{position:absolute;right:0;bottom:calc(100% + 8px);padding:6px 9px;border-radius:6px;background:var(--panel-bg);color:var(--secondary);border:1px solid var(--line);font-size:11px;white-space:nowrap;pointer-events:none;opacity:0;visibility:hidden;transition:opacity .08s,visibility 0s}.clear:is(:hover,:focus-visible) .clear-tooltip{opacity:1;visibility:visible;transition-delay:.1s}.section-head{border-top:1px solid var(--line);padding-top:16px;display:flex;align-items:center;justify-content:space-between;margin-bottom:5px}.section-head h3{font-size:12px;font-weight:550;margin:0}.remaining-toggle{border:0;background:none;padding:0}.row-detail{font-size:12px;font-weight:400;line-height:18px;color:var(--secondary);white-space:nowrap}
|
|
1945
|
+
.task-row{position:relative;display:flex;gap:9px;align-items:flex-start;padding:9px 0;overflow:hidden;isolation:isolate}.task-dot{width:12px;height:12px;border:1.3px solid #c89b38;border-radius:50%;margin-top:4px;flex:none}.task-row[data-status=done] .task-dot{border-color:#548eea;background:#548eea22}.task-content{min-width:0;flex:1}.task-title{width:100%;overflow:hidden;mask-image:linear-gradient(to right,#000 calc(100% - 12px),transparent)}.task-track{display:flex;width:max-content;transform:translateX(0);transition:transform .22s ease-out}.task-copy{white-space:nowrap;flex:none}.task-row:is(:hover,:focus-within) .task-title.overflowing .task-track{transform:translateX(calc(-1 * var(--travel)));transition-duration:var(--duration,4s);transition-timing-function:linear;will-change:transform}.task-meta{font-size:10px;color:var(--secondary);margin-top:3px}.task-source{position:absolute;right:0;top:0;bottom:0;display:flex;align-items:center;justify-content:flex-end;padding-left:28px;background:linear-gradient(to right,transparent,var(--panel-bg) 25px);opacity:0;pointer-events:none;transform:translateX(4px);transition:opacity .13s,transform .13s}.task-source button{border:0;border-radius:6px;background:var(--source-bg);color:inherit;padding:5px 7px;font-size:11px;white-space:nowrap}.task-row:hover .task-source,.task-row:focus-within .task-source{opacity:1;pointer-events:auto;transform:none}.task-row:focus-visible{outline:1px solid var(--accent);outline-offset:1px}
|
|
1946
|
+
@media(prefers-reduced-motion:reduce){.task-row .task-title.overflowing .task-track{transform:none;transition:none}.task-title{overflow:auto}}
|
|
1947
|
+
@media(hover:none){.task-source{opacity:1;pointer-events:auto;transform:none}}
|
|
1948
|
+
.empty{font-size:12px;color:var(--secondary);padding:13px 0}.quiet-row{border:0;border-top:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;width:100%;background:none;color:inherit;padding:15px 0;text-align:left;font-size:12px}.quiet-row span:last-child{color:var(--secondary)}.overview-bottom{margin-top:13px}.view-heading{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px}.view-heading h3{font-size:14px;font-weight:550;margin:0}.choice{display:flex;align-items:center;gap:10px;width:100%;padding:8px 9px;border:0;border-radius:7px;background:none;color:inherit;text-align:left}.choice:hover{background:var(--hover)}.choice[aria-pressed=true]{background:var(--selected)}.dot{width:12px;height:12px;border:1.6px solid var(--mark);border-radius:50%;flex:none}.choice[aria-pressed=true] .dot{background:var(--mark);box-shadow:inset 0 0 0 2px var(--panel-bg)}
|
|
1949
|
+
.progress-section{margin-top:20px}.progress-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.label{font-size:11px;color:var(--secondary)}.number-wrap{display:flex;align-items:center;gap:5px;color:var(--secondary)}.progress-number{appearance:textfield;color:var(--ink);width:65px;padding:2px 3px 4px;background:none;border:0;border-bottom:1px solid var(--number-line);font-size:27px;font-weight:550;text-align:right;font-variant-numeric:tabular-nums}.progress-number::-webkit-inner-spin-button{appearance:none}.range{position:relative;height:51px;margin-top:2px;--mark:#c89b38}.range-track{position:absolute;left:7px;right:7px;top:10px;height:4px;border-radius:3px;background:linear-gradient(to right,var(--range-fill,var(--mark)) var(--fill),var(--track) var(--fill));pointer-events:none}.range-input{position:relative;appearance:none;width:100%;height:24px;background:transparent;margin:0;display:block;padding:0;cursor:pointer}.range-input::-webkit-slider-runnable-track{height:4px;background:transparent}.range-input::-webkit-slider-thumb{appearance:none;width:14px;height:14px;margin-top:-5px;background:var(--thumb);border:2px solid var(--panel-bg);border-radius:50%;box-shadow:0 0 0 1px var(--thumb-edge)}.range-nodes{position:absolute;left:7px;right:7px;top:0;pointer-events:none}.range-node{position:absolute;left:var(--at);top:8px;width:0;font-size:10px;color:var(--secondary);font-variant-numeric:tabular-nums}.range-node::before{content:"";display:block;width:7px;height:7px;transform:translateX(-50%);border-radius:50%;background:var(--panel-bg);border:1px solid var(--secondary);box-shadow:0 0 0 1px var(--panel-bg)}.range-node-label{position:absolute;top:19px;left:0;transform:translateX(-50%)}.range-node:first-child .range-node-label{transform:none}.range-node:last-child .range-node-label{transform:translateX(-100%)}.unknown-row{display:flex;justify-content:flex-end;margin:2px 0 18px}.unknown{font-size:11px}
|
|
1950
|
+
.note-label{display:block;font-size:11px;color:var(--secondary);margin-bottom:8px}textarea{display:block;width:100%;resize:vertical;min-height:66px;max-height:140px;background:var(--input-bg);color:inherit;border:1px solid var(--input-border);border-radius:8px;padding:9px;line-height:1.6;font-size:12px;scrollbar-width:none;-ms-overflow-style:none}textarea::-webkit-scrollbar{display:none;width:0;height:0}textarea::placeholder{color:var(--muted)}.edit-actions{display:flex;justify-content:flex-end;gap:18px;align-items:center;padding:21px 0 16px}.git{font-size:11px;color:var(--secondary)}.analysis-message{font-size:11px;color:var(--secondary);margin:0 0 13px}.analysis-message:empty,.error:empty,.git:empty{display:none}.error{flex:none;font-size:12px;color:var(--error);padding-top:10px;white-space:pre-wrap}button:disabled,input:disabled,textarea:disabled{opacity:.55;cursor:wait}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
1951
|
+
.shell textarea:focus-visible{outline:none}
|
|
1952
|
+
.app-update{margin-top:3px;padding:10px 11px;background:var(--hover);border:1px solid var(--line);border-radius:10px}.app-update-row{display:flex;align-items:center;justify-content:space-between;gap:10px}.app-update-label{font-size:12px;line-height:18px;color:var(--ink);min-width:0;overflow-wrap:anywhere}.app-update-button{flex:none;padding:5px 10px;min-height:28px;border-radius:7px;font-size:11px}.app-update-detail{margin-top:7px;font-size:11px;line-height:1.6;color:var(--secondary);white-space:pre-wrap;overflow-wrap:anywhere;user-select:text}.app-update[data-failed=true] .app-update-detail{color:var(--error)}
|
|
1953
|
+
:host([data-color-mode=light]){--ink:#22272e;--secondary:#576374;--muted:#667383;--note:#46515f;--track:#c3ccd6;--line:#dfe4ea;--input-border:#c7d0da;--input-bg:#f7f9fb;--hover:#f0f3f6;--selected:#e9edf2;--source-bg:#e9eef4;--number-line:#b6c1ce;--thumb:var(--accent);--thumb-edge:var(--accent);--danger:#bf2f3a;--error:#b13a2d;color:var(--ink);color-scheme:light}
|
|
1954
|
+
:host([data-color-mode=light]) .shell{--panel-bg:#fff;border-color:#dfe4ea;box-shadow:0 14px 45px #26344520}
|
|
1955
|
+
:host([data-color-mode=light]) .shell:hover{--panel-bg:#f5f6f7}
|
|
1956
|
+
:host([data-color-mode=light]) .range{--range-fill:color-mix(in srgb,var(--mark) 85%,#000)}
|
|
1957
|
+
:host([data-color-mode=light]) .meter::after{background:color-mix(in srgb,var(--mark) 85%,#000)}
|
|
1958
|
+
`, shadow);
|
|
1959
|
+
if (embedded) element('style', '.shell{position:relative;max-width:100%;max-height:none}.shell,:host([data-color-mode=light]) .shell{box-shadow:none}.panel-body{overflow:visible}', shadow);
|
|
1960
|
+
const shell = element('div', null, shadow, 'shell');
|
|
1961
|
+
shell.setAttribute('role', embedded ? 'region' : 'dialog'); shell.setAttribute('aria-label', S('panelAriaPattern', { title: entry.title }));
|
|
1962
|
+
const close = embedded ? null : element('button', '×', shell, 'close'); close?.setAttribute('aria-label', S('close'));
|
|
1963
|
+
// 宿主支持时,在关闭按钮左侧提供「在侧栏打开」:把卡片交给宿主的常驻侧栏面板。
|
|
1964
|
+
const openPane = harness?.openPane ? element('button', null, shell, 'open-pane') : null;
|
|
1965
|
+
let openPaneTip = null;
|
|
1966
|
+
if (openPane) {
|
|
1967
|
+
shell.classList.add('has-open-pane'); openPane.setAttribute('aria-label', S('openInSidebar'));
|
|
1968
|
+
openPaneTip = element('span', S('openInSidebar'), openPane, 'open-pane-tip');
|
|
1969
|
+
openPaneTip.setAttribute('role', 'tooltip');
|
|
1970
|
+
}
|
|
1971
|
+
const heading = element('div', null, shell, 'title-heading'); heading.tabIndex = 0;
|
|
1972
|
+
const titleProgress = element('span', null, heading, 'title-progress');
|
|
1973
|
+
element('h2', entry.title, heading, 'title');
|
|
1974
|
+
const body = element('div', null, shell, 'panel-body');
|
|
1975
|
+
const overview = element('div', null, body, 'view overview');
|
|
1976
|
+
const statusLine = element('div', null, overview, 'status-line');
|
|
1977
|
+
const statusBlock = element('div', null, statusLine, 'status-block');
|
|
1978
|
+
const statusName = element('div', null, statusBlock, 'status-name');
|
|
1979
|
+
const statusDot = element('span', null, statusName, 'state-dot');
|
|
1980
|
+
const statusLabel = element('span', null, statusName);
|
|
1981
|
+
const timestamp = element('div', null, statusBlock, 'timestamp');
|
|
1982
|
+
const score = element('div', null, statusLine, 'score');
|
|
1983
|
+
const scoreNumber = element('span', null, score, 'score-number');
|
|
1984
|
+
const scoreUnit = element('span', '%', score, 'score-unit');
|
|
1985
|
+
const meter = element('div', null, overview, 'meter');
|
|
1986
|
+
const totalsRow = element('div', null, overview, 'totals-row');
|
|
1987
|
+
const totals = element('span', S('totalsEmpty'), totalsRow, 'totals');
|
|
1988
|
+
const sourceLabel = element('span', null, totalsRow, 'source-label');
|
|
1989
|
+
const summaryBlock = element('div', null, overview, 'summary-block'); summaryBlock.tabIndex = 0;
|
|
1990
|
+
const overviewSummary = element('div', null, summaryBlock, 'overview-summary');
|
|
1991
|
+
const summaryExpand = element('button', S('expandAll'), summaryBlock, 'summary-expand');
|
|
1992
|
+
summaryExpand.hidden = true; summaryExpand.setAttribute('aria-expanded', 'false');
|
|
1993
|
+
const actions = element('div', null, overview, 'actions');
|
|
1994
|
+
const analyze = element('button', S('btnUpdate'), actions, 'primary analyze');
|
|
1995
|
+
const editOpen = element('button', S('btnAdjust'), actions, 'text-button edit-open');
|
|
1996
|
+
const clear = element('button', S('btnClear'), actions, 'clear');
|
|
1997
|
+
clear.setAttribute('aria-label', S('btnClear'));
|
|
1998
|
+
const clearTip = element('span', S('clearTooltip'), clear, 'clear-tooltip');
|
|
1999
|
+
clearTip.setAttribute('role', 'tooltip');
|
|
2000
|
+
const sectionHead = element('div', null, overview, 'section-head');
|
|
2001
|
+
const tasksHeading = element('h3', S('remainingHeadingPattern', { count: 0 }), sectionHead);
|
|
2002
|
+
const remainingToggle = element('button', null, sectionHead, 'remaining-toggle row-detail');
|
|
2003
|
+
remainingToggle.hidden = true; remainingToggle.setAttribute('aria-expanded', 'false');
|
|
2004
|
+
const currentTasks = element('div', null, overview, 'current-tasks');
|
|
2005
|
+
const bottom = element('div', null, overview, 'overview-bottom');
|
|
2006
|
+
const historyOpen = element('button', null, bottom, 'quiet-row history-open'); const historyRowTitle = element('span', S('completedHeading'), historyOpen);
|
|
2007
|
+
const historyCount = element('span', S('countArrowPattern', { count: 0 }), historyOpen, 'row-detail');
|
|
2008
|
+
const noteRow = element('button', null, bottom, 'quiet-row note-open'); const noteRowTitle = element('span', S('notesLabel'), noteRow);
|
|
2009
|
+
const noteOpen = element('span', S('addLabel'), noteRow);
|
|
2010
|
+
const timelineOpen = embedded ? element('button', S('timelineLink'), bottom, 'quiet-row timeline-open') : null;
|
|
2011
|
+
const appUpdate = element('div', null, bottom, 'app-update'); appUpdate.hidden = true;
|
|
2012
|
+
const appUpdateRow = element('div', null, appUpdate, 'app-update-row');
|
|
2013
|
+
const appUpdateLabel = element('span', null, appUpdateRow, 'app-update-label'); appUpdateLabel.setAttribute('role', 'status');
|
|
2014
|
+
const appUpdateButton = element('button', S('upgradeBtn'), appUpdateRow, 'primary app-update-button');
|
|
2015
|
+
const appUpdateDetail = element('div', null, appUpdate, 'app-update-detail'); appUpdateDetail.hidden = true;
|
|
2016
|
+
const edit = element('div', null, body, 'view edit-view'); edit.hidden = true;
|
|
2017
|
+
const editHeading = element('div', null, edit, 'view-heading'); const editHeadingTitle = element('h3', S('editHeading'), editHeading);
|
|
2018
|
+
const choices = new Map(), choiceLabels = new Map(), controls = [];
|
|
2019
|
+
for (const [state, label] of Object.entries(labels)) {
|
|
2020
|
+
const button = element('button', null, edit, 'choice'); button.style.setProperty('--mark', colors[state]);
|
|
2021
|
+
element('span', null, button, 'dot'); choiceLabels.set(state, element('span', label, button)); button.setAttribute('aria-pressed', 'false');
|
|
2022
|
+
choices.set(state, button); controls.push(button); if (state === 'pushed') button.hidden = true;
|
|
2023
|
+
button.onclick = () => updateDraft(target, { state, progress: state === 'unstarted' ? 0 : state === 'unfinished'
|
|
2024
|
+
? target.draft.state === 'unfinished' ? target.draft.progress : null : 100 });
|
|
2025
|
+
button.onkeydown = event => {
|
|
2026
|
+
if (!['ArrowUp', 'ArrowDown'].includes(event.key)) return;
|
|
2027
|
+
event.preventDefault(); const buttons = [...choices.values()].filter(item => !item.hidden);
|
|
2028
|
+
buttons[(buttons.indexOf(button) + (event.key === 'ArrowDown' ? 1 : buttons.length - 1)) % buttons.length].focus();
|
|
2029
|
+
};
|
|
2030
|
+
}
|
|
2031
|
+
const progressSection = element('div', null, edit, 'progress-section');
|
|
2032
|
+
const progressHead = element('div', null, progressSection, 'progress-head'); const progressHeadLabel = element('label', S('progressLabel'), progressHead, 'label');
|
|
2033
|
+
const numberWrap = element('div', null, progressHead, 'number-wrap');
|
|
2034
|
+
const progress = element('input', null, numberWrap, 'progress-number'); progress.type = 'number'; progress.min = '0'; progress.max = '100'; progress.step = '1'; progress.placeholder = '—'; progress.setAttribute('aria-label', S('progressLabel')); element('span', '%', numberWrap);
|
|
2035
|
+
const range = element('div', null, progressSection, 'range'); element('div', null, range, 'range-track');
|
|
2036
|
+
const nodes = element('div', null, range, 'range-nodes'); nodes.setAttribute('aria-hidden', 'true');
|
|
2037
|
+
for (const value of [0, 25, 50, 75, 100]) { const node = element('span', null, nodes, 'range-node'); node.style.setProperty('--at', `${value}%`); element('span', String(value), node, 'range-node-label'); }
|
|
2038
|
+
const slider = element('input', null, range, 'range-input'); slider.type = 'range'; slider.min = '0'; slider.max = '100'; slider.step = '1'; slider.setAttribute('aria-label', S('sliderAriaLabel'));
|
|
2039
|
+
const unknownRow = element('div', null, progressSection, 'unknown-row'); const unknown = element('button', S('clearValueBtn'), unknownRow, 'text-button unknown');
|
|
2040
|
+
const noteLabel = element('label', S('notesLabel'), edit, 'note-label');
|
|
2041
|
+
const note = element('textarea', null, edit); note.maxLength = 4000; note.placeholder = S('notePlaceholder'); note.setAttribute('aria-label', S('noteAriaLabel'));
|
|
2042
|
+
noteLabel.htmlFor = note.id = `session-status-note-${serial}`;
|
|
2043
|
+
const git = element('div', null, edit, 'git');
|
|
2044
|
+
const editActions = element('div', null, edit, 'edit-actions');
|
|
2045
|
+
const cancel = element('button', S('cancelBtn'), editActions, 'text-button cancel');
|
|
2046
|
+
const submit = element('button', S('saveBtn'), editActions, 'primary save-record');
|
|
2047
|
+
const history = element('div', null, body, 'view history-view'); history.hidden = true;
|
|
2048
|
+
const historyHeading = element('div', null, history, 'view-heading'); const historyHeadingTitle = element('h3', S('completedHeading'), historyHeading);
|
|
2049
|
+
const back = element('button', S('backLabel'), historyHeading, 'back');
|
|
2050
|
+
const historyList = element('div', null, history, 'history-list');
|
|
2051
|
+
const timelineView = embedded ? element('div', null, body, 'view history-view') : null;
|
|
2052
|
+
let timelineList, timelineHeadingTitle, timelineBackBtn;
|
|
2053
|
+
if (timelineView) {
|
|
2054
|
+
timelineView.hidden = true;
|
|
2055
|
+
const title = element('div', null, timelineView, 'view-heading'); timelineHeadingTitle = element('h3', S('timelineHeading'), title);
|
|
2056
|
+
timelineBackBtn = element('button', S('backLabel'), title, 'back');
|
|
2057
|
+
timelineBackBtn.onclick = () => target.setView('overview');
|
|
2058
|
+
timelineList = element('div', null, timelineView, 'history-list');
|
|
2059
|
+
}
|
|
2060
|
+
const analysisMessage = element('div', null, body, 'analysis-message'); analysisMessage.setAttribute('role', 'status');
|
|
2061
|
+
const error = element('div', null, shell, 'error'); error.setAttribute('role', 'status');
|
|
2062
|
+
const resolveConflict = element('button', S('resolveConflictBtn'), shell, 'text-button'); resolveConflict.hidden = true;
|
|
2063
|
+
controls.push(note, progress, slider, unknown, cancel, submit, clear, analyze, editOpen, resolveConflict);
|
|
2064
|
+
panel = { entry, root, shell, body, heading, titleProgress, choices, note, progress, slider, range, git, error, resolveConflict, controls,
|
|
2065
|
+
statusLabel, statusDot, timestamp, scoreNumber, scoreUnit, meter, sourceLabel, overviewSummary, summaryBlock, noteOpen,
|
|
2066
|
+
totals, analyze, historyList, dirty: false, busy: false, analyzing: false, revision: 0, mode: 'overview' };
|
|
2067
|
+
const target = panel;
|
|
2068
|
+
target.applyLocale = () => {
|
|
2069
|
+
shell.setAttribute('aria-label', S('panelAriaPattern', { title: entry.title }));
|
|
2070
|
+
close?.setAttribute('aria-label', S('close'));
|
|
2071
|
+
if (openPane) {
|
|
2072
|
+
openPane.setAttribute('aria-label', S('openInSidebar'));
|
|
2073
|
+
if (openPaneTip) openPaneTip.textContent = S('openInSidebar');
|
|
2074
|
+
}
|
|
2075
|
+
summaryExpand.textContent = target.summaryExpanded ? S('collapse') : S('expandAll');
|
|
2076
|
+
analyze.textContent = target.analyzing ? S('btnUpdating') : S('btnUpdate');
|
|
2077
|
+
editOpen.textContent = S('btnAdjust');
|
|
2078
|
+
clear.textContent = S('btnClear');
|
|
2079
|
+
clear.setAttribute('aria-label', S('btnClear'));
|
|
2080
|
+
clearTip.textContent = S('clearTooltip');
|
|
2081
|
+
historyRowTitle.textContent = S('completedHeading');
|
|
2082
|
+
noteRowTitle.textContent = S('notesLabel');
|
|
2083
|
+
if (timelineOpen) timelineOpen.textContent = S('timelineLink');
|
|
2084
|
+
editHeadingTitle.textContent = S('editHeading');
|
|
2085
|
+
for (const [state, labelEl] of choiceLabels) labelEl.textContent = labels[state];
|
|
2086
|
+
progressHeadLabel.textContent = S('progressLabel');
|
|
2087
|
+
progress.setAttribute('aria-label', S('progressLabel'));
|
|
2088
|
+
slider.setAttribute('aria-label', S('sliderAriaLabel'));
|
|
2089
|
+
unknown.textContent = S('clearValueBtn');
|
|
2090
|
+
noteLabel.textContent = S('notesLabel');
|
|
2091
|
+
note.placeholder = S('notePlaceholder');
|
|
2092
|
+
note.setAttribute('aria-label', S('noteAriaLabel'));
|
|
2093
|
+
cancel.textContent = S('cancelBtn');
|
|
2094
|
+
submit.textContent = S('saveBtn');
|
|
2095
|
+
historyHeadingTitle.textContent = S('completedHeading');
|
|
2096
|
+
back.textContent = S('backLabel');
|
|
2097
|
+
if (timelineHeadingTitle) timelineHeadingTitle.textContent = S('timelineHeading');
|
|
2098
|
+
if (timelineBackBtn) timelineBackBtn.textContent = S('backLabel');
|
|
2099
|
+
resolveConflict.textContent = S('resolveConflictBtn');
|
|
2100
|
+
target.tasksKey = null; target.completedKey = null; target.timelineRevision = null;
|
|
2101
|
+
};
|
|
2102
|
+
target.capabilities = embedded?.session?.capabilities || null;
|
|
2103
|
+
panelEvent('open', entry);
|
|
2104
|
+
target.request = (type, timeout, extra = {}) => new Promise((resolve, reject) => {
|
|
2105
|
+
const requestId = `${requestPrefix}:${++serial}`;
|
|
2106
|
+
const timer = setTimeout(() => { cancelRead(requestId, { type }); pending.delete(requestId); const error = new Error(S('cardRequestTimeout')); error.code = 'STATUS_REQUEST_TIMEOUT'; reject(error); }, timeout);
|
|
2107
|
+
pending.set(requestId, { resolve, reject, timer, type, key: entry.key });
|
|
2108
|
+
try { send(JSON.stringify({ type, requestId, key: entry.key, ...extra })); }
|
|
2109
|
+
catch { clearTimeout(timer); pending.delete(requestId); const error = new Error(S('cardStatusDisconnected')); error.code = 'STATUS_SEND_FAILED'; reject(error); }
|
|
2110
|
+
});
|
|
2111
|
+
resolveConflict.onclick = () => rebaseDraft(target);
|
|
2112
|
+
const showAppUpdate = info => {
|
|
2113
|
+
target.updateInfo = info;
|
|
2114
|
+
const update = info?.update;
|
|
2115
|
+
const stage = update?.stage;
|
|
2116
|
+
const stages = strings.updateStages || { queued: '正在准备升级', checking: '正在检查版本', downloading: '正在下载新版本', waiting: '等待当前分析结束', installing: '正在升级' };
|
|
2117
|
+
const active = Boolean(stages[stage]) || target.upgradeStarting;
|
|
2118
|
+
const completed = stage === 'completed' && Date.now() - Date.parse(update.updatedAt) < 60000;
|
|
2119
|
+
const failed = stage === 'failed';
|
|
2120
|
+
appUpdate.hidden = !info?.available && !active && !failed && !completed;
|
|
2121
|
+
appUpdate.setAttribute('data-failed', String(failed));
|
|
2122
|
+
appUpdateLabel.textContent = active ? stages[stage] || stages.queued : failed ? S('updateFailedLabel') : completed
|
|
2123
|
+
? S('upgradedToPattern', { version: update.currentVersion }) : S('updateAvailablePattern', { version: info?.latestVersion });
|
|
2124
|
+
appUpdateButton.textContent = active ? S('pleaseWait') : completed ? S('completedShort') : failed ? S('retryBtn') : S('upgradeBtn');
|
|
2125
|
+
appUpdateButton.disabled = active || completed;
|
|
2126
|
+
const command = info?.command || 'npx agent-things@latest';
|
|
2127
|
+
appUpdateDetail.textContent = target.updateConnectionError ? `${S('reconnectHint')}\n${S('terminalUpgradePrefix')}${command}`
|
|
2128
|
+
: failed ? `${update.error}\n${S('terminalUpgradePrefix')}${command}` : completed && update.reconnectMcp ? S('reconnectMcpHint') : '';
|
|
2129
|
+
appUpdateDetail.hidden = !appUpdateDetail.textContent;
|
|
2130
|
+
refreshPanel();
|
|
2131
|
+
return active;
|
|
2132
|
+
};
|
|
2133
|
+
const pollAppUpdate = async () => {
|
|
2134
|
+
clearTimeout(target.updateTimer);
|
|
2135
|
+
try {
|
|
2136
|
+
const info = await target.request('app-update-info', 12000);
|
|
2137
|
+
if (panel !== target) return;
|
|
2138
|
+
target.updateConnectionError = null;
|
|
2139
|
+
const active = showAppUpdate(info);
|
|
2140
|
+
target.updateTimer = setTimeout(pollAppUpdate, active ? 2000 : 60000);
|
|
2141
|
+
} catch (error) {
|
|
2142
|
+
if (panel !== target) return;
|
|
2143
|
+
target.updateConnectionError = error.message;
|
|
2144
|
+
if (target.updateInfo) showAppUpdate(target.updateInfo);
|
|
2145
|
+
target.updateTimer = setTimeout(pollAppUpdate, 2000);
|
|
2146
|
+
}
|
|
2147
|
+
};
|
|
2148
|
+
appUpdateButton.onclick = async () => {
|
|
2149
|
+
if (appUpdateButton.disabled) return;
|
|
2150
|
+
clearTimeout(target.updateTimer);
|
|
2151
|
+
target.upgradeStarting = true;
|
|
2152
|
+
showAppUpdate(target.updateInfo);
|
|
2153
|
+
try {
|
|
2154
|
+
const info = await target.request('app-update-start', 12000);
|
|
2155
|
+
if (panel !== target) return;
|
|
2156
|
+
target.updateConnectionError = null;
|
|
2157
|
+
target.upgradeStarting = false;
|
|
2158
|
+
showAppUpdate(info);
|
|
2159
|
+
} catch (error) {
|
|
2160
|
+
if (panel !== target) return;
|
|
2161
|
+
target.upgradeStarting = false;
|
|
2162
|
+
target.updateConnectionError = error.message;
|
|
2163
|
+
showAppUpdate(target.updateInfo);
|
|
2164
|
+
}
|
|
2165
|
+
if (panel === target) target.updateTimer = setTimeout(pollAppUpdate, 1000);
|
|
2166
|
+
};
|
|
2167
|
+
target.scheduleMarquees = () => {
|
|
2168
|
+
cancelAnimationFrame(target.marqueeFrame);
|
|
2169
|
+
target.marqueeFrame = requestAnimationFrame(() => {
|
|
2170
|
+
if (panel !== target) return;
|
|
2171
|
+
if (target.mode === 'overview' && !target.summaryExpanded) summaryExpand.hidden = overviewSummary.scrollHeight <= overviewSummary.clientHeight + 1;
|
|
2172
|
+
for (const title of shadow.querySelectorAll('.task-title')) {
|
|
2173
|
+
if (!title.clientWidth) continue;
|
|
2174
|
+
const width = title.firstElementChild.firstElementChild.getBoundingClientRect().width;
|
|
2175
|
+
const maskWidth = title.closest('.task-row').querySelector('.task-source')?.offsetWidth || 0;
|
|
2176
|
+
const distance = Math.max(0, width - title.clientWidth + maskWidth + 8);
|
|
2177
|
+
title.classList.toggle('overflowing', distance > 1);
|
|
2178
|
+
title.style.setProperty('--travel', `${distance}px`);
|
|
2179
|
+
title.style.setProperty('--duration', `${Math.max(1, distance / 26)}s`);
|
|
2180
|
+
}
|
|
2181
|
+
});
|
|
2182
|
+
};
|
|
2183
|
+
target.setSummaryExpanded = expanded => {
|
|
2184
|
+
target.summaryExpanded = expanded;
|
|
2185
|
+
summaryBlock.classList.toggle('expanded', expanded);
|
|
2186
|
+
summaryExpand.textContent = expanded ? S('collapse') : S('expandAll');
|
|
2187
|
+
summaryExpand.setAttribute('aria-expanded', String(expanded));
|
|
2188
|
+
positionPanel(); target.scheduleMarquees();
|
|
2189
|
+
};
|
|
2190
|
+
summaryExpand.onclick = () => { summaryExpand.focus({ preventScroll: true }); target.setSummaryExpanded(!target.summaryExpanded); };
|
|
2191
|
+
summaryBlock.addEventListener('focusout', event => { if (!summaryBlock.contains(event.relatedTarget)) target.setSummaryExpanded(false); });
|
|
2192
|
+
target.resizeObserver = new ResizeObserver(target.scheduleMarquees); target.resizeObserver.observe(body);
|
|
2193
|
+
target.setView = mode => {
|
|
2194
|
+
target.mode = mode; overview.hidden = mode !== 'overview'; edit.hidden = mode !== 'edit'; history.hidden = mode !== 'history';
|
|
2195
|
+
if (timelineView) timelineView.hidden = mode !== 'timeline';
|
|
2196
|
+
body.scrollTop = 0; target.error.textContent = '';
|
|
2197
|
+
if (mode !== 'edit') { target.conflict = false; resolveConflict.hidden = true; }
|
|
2198
|
+
refreshPanel();
|
|
2199
|
+
rememberPanel(target);
|
|
2200
|
+
};
|
|
2201
|
+
const cancelEdit = () => { target.dirty = false; target.setView('overview'); editOpen.focus(); };
|
|
2202
|
+
target.cancelEdit = cancelEdit;
|
|
2203
|
+
editOpen.onclick = () => { target.setView('edit'); (choices.get(target.draft.state) || choices.values().next().value).focus(); };
|
|
2204
|
+
noteRow.onclick = () => { target.setView('edit'); note.focus(); };
|
|
2205
|
+
historyOpen.onclick = () => target.setView('history'); back.onclick = () => target.setView('overview'); cancel.onclick = cancelEdit;
|
|
2206
|
+
if (timelineOpen) timelineOpen.onclick = () => target.setView('timeline');
|
|
2207
|
+
remainingToggle.onclick = () => { target.remainingExpanded = !target.remainingExpanded; refreshPanel(); };
|
|
2208
|
+
const locate = async source => {
|
|
2209
|
+
if (target.capabilities?.locate === false) { analysisMessage.textContent = S('locateHostDisconnected'); return; }
|
|
2210
|
+
if (embedded) {
|
|
2211
|
+
if (!source?.turnId || !source?.itemId) { analysisMessage.textContent = S('locateNoSource'); return; }
|
|
2212
|
+
analysisMessage.textContent = S('locatingMessage');
|
|
2213
|
+
try {
|
|
2214
|
+
const result = await target.request('locate-source', 14000, { source: { turnId: source.turnId, itemId: source.itemId } });
|
|
2215
|
+
analysisMessage.textContent = result?.message || S('locatedMessage');
|
|
2216
|
+
} catch (error) { analysisMessage.textContent = error.message; }
|
|
2217
|
+
return;
|
|
2218
|
+
}
|
|
2219
|
+
if (!source?.turnId || !source?.itemId) { analysisMessage.textContent = S('locateNoSource'); return; }
|
|
2220
|
+
const harness = window.__sessionStatusHarness;
|
|
2221
|
+
if (harness?.locate) {
|
|
2222
|
+
try { await harness.locate({ entry, source, analysisMessage, request: target.request }); }
|
|
2223
|
+
catch (error) { analysisMessage.textContent = error.message; }
|
|
2224
|
+
return;
|
|
2225
|
+
}
|
|
2226
|
+
const row = entry.row;
|
|
2227
|
+
if (row.getAttribute('data-app-action-sidebar-thread-selected') !== 'true') {
|
|
2228
|
+
const trigger = row.querySelector('[data-thread-title-trigger]');
|
|
2229
|
+
if (!trigger) { analysisMessage.textContent = S('locateOpenFailed'); return; } trigger.click();
|
|
2230
|
+
}
|
|
2231
|
+
const deadline = Date.now() + 4000;
|
|
2232
|
+
while (Date.now() < deadline) {
|
|
2233
|
+
if (row.getAttribute('data-app-action-sidebar-thread-selected') === 'true') {
|
|
2234
|
+
const message = [...document.querySelectorAll('[data-content-search-unit-key]')].find(node => node.getAttribute('data-content-search-unit-key') === `${source.turnId}:${source.itemId}`);
|
|
2235
|
+
if (message) { message.scrollIntoView({ block: 'center', behavior: 'smooth' }); const previous = message.style.outline; message.style.outline = '2px solid #0169cc'; setTimeout(() => { if (message.style.outline === '2px solid rgb(1, 105, 204)') message.style.outline = previous; }, 3000); analysisMessage.textContent = S('locatedMessage'); return; }
|
|
2236
|
+
}
|
|
2237
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
2238
|
+
}
|
|
2239
|
+
try { await target.request('locate-source', 30000, { source }); analysisMessage.textContent = S('locatedMessage'); }
|
|
2240
|
+
catch (error) { analysisMessage.textContent = error.message; }
|
|
2241
|
+
};
|
|
2242
|
+
const renderTask = (task, sources, parent) => {
|
|
2243
|
+
const row = element('div', null, parent, 'task-row'); row.dataset.status = task.status; row.tabIndex = 0;
|
|
2244
|
+
element('span', null, row, 'task-dot'); const content = element('div', null, row, 'task-content');
|
|
2245
|
+
const title = element('div', null, content, 'task-title'); title.title = task.title;
|
|
2246
|
+
const track = element('div', null, title, 'task-track');
|
|
2247
|
+
const text = task.summary || task.title;
|
|
2248
|
+
element('span', text, track, 'task-copy');
|
|
2249
|
+
element('div', taskLabels[task.status] || S('taskUnknown'), content, 'task-meta');
|
|
2250
|
+
const ref = task.evidenceRefs?.find(value => sources?.[value]?.turnId);
|
|
2251
|
+
if (ref) { const mask = element('div', null, row, 'task-source'); const link = element('button', S('viewSource'), mask); link.setAttribute('aria-label', `${S('viewSourceAriaPrefix')}${task.title}`); link.onclick = () => locate(sources[ref]); }
|
|
2252
|
+
};
|
|
2253
|
+
target.renderHistory = () => {
|
|
2254
|
+
const state = target.analysisState; if (!state) return;
|
|
2255
|
+
if (timelineList && target.timelineRevision !== state.revision) {
|
|
2256
|
+
target.timelineRevision = state.revision;
|
|
2257
|
+
timelineList.replaceChildren();
|
|
2258
|
+
for (const item of [...(state.timeline || [])].reverse()) {
|
|
2259
|
+
const date = new Date(item.requestedAt).toLocaleString(activeLang === 'en' ? 'en-US' : 'zh-CN');
|
|
2260
|
+
const progress = item.record?.progress ?? item.progress;
|
|
2261
|
+
const label = item.source === 'analysis' ? S('timelineAnalysis') : S('timelineManual');
|
|
2262
|
+
const value = item.status === 'failed' ? S('analysisFailedWord') : item.status === 'pending' ? S('analyzingWord') : progress == null ? S('unrecordedShort') : `${progress}%`;
|
|
2263
|
+
element('div', `${date} · ${label} · ${value}`, timelineList, 'quiet-row');
|
|
2264
|
+
}
|
|
2265
|
+
if (!timelineList.childElementCount) element('div', S('emptyTimeline'), timelineList, 'empty');
|
|
2266
|
+
}
|
|
2267
|
+
const ledger = state.analysis?.ledger; const tasks = ledger?.tasks || [];
|
|
2268
|
+
const remaining = tasks.filter(task => ['todo', 'in_progress', 'blocked', 'needs_verification'].includes(task.status));
|
|
2269
|
+
const completed = tasks.filter(task => task.status === 'done');
|
|
2270
|
+
totals.textContent = tasks.length ? S('totalsPattern', { done: completed.length, total: tasks.length }) : S('totalsEmpty');
|
|
2271
|
+
tasksHeading.textContent = S('remainingHeadingPattern', { count: remaining.length });
|
|
2272
|
+
remainingToggle.hidden = remaining.length <= 3;
|
|
2273
|
+
remainingToggle.textContent = target.remainingExpanded ? S('collapseArrow') : S('showAllCountPattern', { count: remaining.length });
|
|
2274
|
+
remainingToggle.setAttribute('aria-expanded', String(Boolean(target.remainingExpanded)));
|
|
2275
|
+
const tasksKey = JSON.stringify([remaining, state.analysis?.sources, Boolean(target.remainingExpanded), activeLang]);
|
|
2276
|
+
if (target.tasksKey !== tasksKey) {
|
|
2277
|
+
target.tasksKey = tasksKey; currentTasks.replaceChildren();
|
|
2278
|
+
if (!tasks.length) element('div', S('emptyNoTasks'), currentTasks, 'empty');
|
|
2279
|
+
else if (!remaining.length) element('div', S('emptyNoRemaining'), currentTasks, 'empty');
|
|
2280
|
+
for (const task of target.remainingExpanded ? remaining : remaining.slice(0, 3)) renderTask(task, state.analysis?.sources, currentTasks);
|
|
2281
|
+
}
|
|
2282
|
+
historyCount.textContent = S('countArrowPattern', { count: completed.length });
|
|
2283
|
+
const completedKey = JSON.stringify([completed, state.analysis?.sources, activeLang]);
|
|
2284
|
+
if (target.completedKey === completedKey) return;
|
|
2285
|
+
target.completedKey = completedKey; historyList.replaceChildren();
|
|
2286
|
+
for (const task of completed) renderTask(task, state.analysis?.sources, historyList);
|
|
2287
|
+
if (!completed.length) element('div', S('emptyCompleted'), historyList, 'empty');
|
|
2288
|
+
};
|
|
2289
|
+
|
|
2290
|
+
const pollHistory = () => {
|
|
2291
|
+
if (panel !== target) return;
|
|
2292
|
+
target.request('analysis-state', 7000).then(showHistory).catch(() => {
|
|
2293
|
+
if (panel !== target) return;
|
|
2294
|
+
analysisMessage.textContent = S('retryingStatus');
|
|
2295
|
+
clearTimeout(target.pollTimer); target.pollTimer = setTimeout(pollHistory, 2000);
|
|
2296
|
+
});
|
|
2297
|
+
};
|
|
2298
|
+
target.pollHistory = pollHistory;
|
|
2299
|
+
const showHistory = state => {
|
|
2300
|
+
if (panel !== target || !state || (target.historyRevision ?? -1) > state.revision) return;
|
|
2301
|
+
target.historyRevision = state.revision; target.analysisState = state;
|
|
2302
|
+
const active = (state.timeline || []).find(item => item.source === 'analysis' && item.status === 'pending');
|
|
2303
|
+
target.analyzing = Boolean(active); analyze.disabled = target.analyzing;
|
|
2304
|
+
const stages = strings.analysisStages || { starting: '正在启动分析', reading: '正在读取会话', retrying: '正在重新连接', analyzing: '正在分析任务' };
|
|
2305
|
+
target.stageMessage = active ? (stages[active.stage] || stages.analyzing) : '';
|
|
2306
|
+
const latest = state.timeline?.at(-1);
|
|
2307
|
+
analysisMessage.textContent = target.stageMessage || (latest?.status === 'failed' ? `${S('analysisFailedPrefix')}${latest.error || S('analysisFailedRetry')}` : ''); analyze.textContent = active ? S('btnUpdating') : S('btnUpdate');
|
|
2308
|
+
clearTimeout(target.pollTimer); if (active && !embedded?.streamConnected) target.pollTimer = setTimeout(pollHistory, 2000);
|
|
2309
|
+
refreshPanel();
|
|
2310
|
+
};
|
|
2311
|
+
target.showHistory = showHistory;
|
|
2312
|
+
analyze.onclick = async () => {
|
|
2313
|
+
analyze.disabled = true; analysisMessage.textContent = S('startingAnalysisFeedback');
|
|
2314
|
+
try { showHistory(await target.request('analyze', 7000)); }
|
|
2315
|
+
catch (error) {
|
|
2316
|
+
if (panel !== target) return;
|
|
2317
|
+
if (['STATUS_REQUEST_TIMEOUT', 'STATUS_SEND_FAILED'].includes(error.code)) {
|
|
2318
|
+
analysisMessage.textContent = S('retryingStatus'); clearTimeout(target.pollTimer); target.pollTimer = setTimeout(pollHistory, 2000);
|
|
2319
|
+
} else { analysisMessage.textContent = error.message; analyze.disabled = false; }
|
|
2320
|
+
}
|
|
2321
|
+
};
|
|
2322
|
+
const setProgress = value => {
|
|
2323
|
+
const state = presentation ? presentation.progressState(target.draft.state, value) : value === 100 ? target.draft.state === 'pushed' ? 'pushed' : 'completed'
|
|
2324
|
+
: value === 0 && target.draft.state === 'unstarted' ? 'unstarted' : 'unfinished';
|
|
2325
|
+
updateDraft(target, { progress: value, state });
|
|
2326
|
+
};
|
|
2327
|
+
let dragging = false;
|
|
2328
|
+
slider.onpointerdown = () => { dragging = true; };
|
|
2329
|
+
const endDrag = () => { dragging = false; }; slider.onpointerup = endDrag; slider.onpointercancel = endDrag; slider.onlostpointercapture = endDrag;
|
|
2330
|
+
slider.oninput = () => { const value = Number(slider.value), nearest = Math.round(value / 25) * 25; setProgress(presentation ? presentation.progressValue(value, dragging) : dragging && Math.abs(value - nearest) <= 2 ? nearest : value); };
|
|
2331
|
+
progress.oninput = () => { const raw = progress.value.trim(); if (!raw) setProgress(null); else if (Number.isInteger(Number(raw)) && Number(raw) >= 0 && Number(raw) <= 100) setProgress(Number(raw)); else target.dirty = true; };
|
|
2332
|
+
unknown.onclick = () => setProgress(null);
|
|
2333
|
+
note.oninput = () => { target.draft.note = note.value; target.dirty = true; rememberPanel(target); };
|
|
2334
|
+
submit.onclick = async () => { if (await save({}, false, target)) target.setView('overview'); };
|
|
2335
|
+
progress.onkeydown = event => { if (event.key === 'Enter') submit.click(); };
|
|
2336
|
+
clear.onclick = async () => { if (await save({}, true, target)) target.setView('overview'); };
|
|
2337
|
+
if (close) close.onclick = () => closePanel();
|
|
2338
|
+
if (openPane) openPane.onclick = async () => {
|
|
2339
|
+
openPane.disabled = true; analysisMessage.textContent = '';
|
|
2340
|
+
try { await harness.openPane({ entry, request: target.request }); if (panel === target) closePanel(); }
|
|
2341
|
+
catch (error) { if (panel === target) { openPane.disabled = false; analysisMessage.textContent = error.message; } }
|
|
2342
|
+
};
|
|
2343
|
+
// 首次历史读取前以当前快照为基线:读取期间到达的新版快照会触发补读。
|
|
2344
|
+
target.syncVersion = panelVersion(entry.key);
|
|
2345
|
+
if (embedded?.analysisState) showHistory(embedded.analysisState); else pollHistory();
|
|
2346
|
+
pollAppUpdate();
|
|
2347
|
+
target.request('project-git', 14000).then(info => { if (panel === target) { target.projectGit = info; refreshPanel(); } }).catch(() => {
|
|
2348
|
+
if (panel === target) { target.projectGit = { status: 'unknown', hasRemote: false }; refreshPanel(); }
|
|
2349
|
+
});
|
|
2350
|
+
entry.button?.setAttribute('aria-expanded', 'true'); refreshPanel();
|
|
2351
|
+
const remembered = rememberedPanel(entry.key);
|
|
2352
|
+
if (remembered) restorePanel(target, remembered); else if (!embedded) editOpen.focus();
|
|
2353
|
+
}
|
|
2354
|
+
|
|
2355
|
+
function receive(next) {
|
|
2356
|
+
if (!next || (next.revision < snapshot.revision && (!next.lang || next.lang === activeLang))) return;
|
|
2357
|
+
const langChanged = next.lang ? setLang(next.lang) : false;
|
|
2358
|
+
snapshot = next;
|
|
2359
|
+
if (langChanged && panel) panel.applyLocale?.();
|
|
2360
|
+
for (const entry of mounted.values()) paint(entry);
|
|
2361
|
+
refreshPanel();
|
|
2362
|
+
// 其他入口改了这个会话(保存、清除、分析、任务来源):按单会话数据版本补读;弹窗忙时记下,空闲后补读一次。乱序回复由 historyRevision 丢弃。
|
|
2363
|
+
if (panel?.pollHistory) syncPanel(panel);
|
|
2364
|
+
}
|
|
2365
|
+
|
|
2366
|
+
function panelVersion(key) {
|
|
2367
|
+
if (snapshot.keyVersions) return snapshot.keyVersions[key] ?? snapshot.keyVersionBase ?? 0;
|
|
2368
|
+
return JSON.stringify([snapshot.records?.[key] || null, (snapshot.analyzingKeys || []).includes(key)]);
|
|
2369
|
+
}
|
|
2370
|
+
|
|
2371
|
+
function syncPanel(target) {
|
|
2372
|
+
const version = panelVersion(target.entry.key);
|
|
2373
|
+
if (target.syncVersion === undefined) { target.syncVersion = version; return; }
|
|
2374
|
+
if (target.syncVersion === version && !target.syncPending) return;
|
|
2375
|
+
if (target.busy) { target.syncPending = true; return; }
|
|
2376
|
+
target.syncVersion = version; target.syncPending = false; target.pollHistory();
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2379
|
+
function onOutside(event) {
|
|
2380
|
+
if (!panel || event.composedPath().includes(panel.root) || event.composedPath().includes(panel.entry.host)) return;
|
|
2381
|
+
if (event.composedPath().some(node => node.hasAttribute?.('data-codex-session-status'))) return;
|
|
2382
|
+
closePanel(false);
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
function onKey(event) {
|
|
2386
|
+
if (!panel || event.key !== 'Escape') return;
|
|
2387
|
+
event.preventDefault(); event.stopPropagation();
|
|
2388
|
+
closePanel();
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
function onScroll() {
|
|
2392
|
+
if (!panel) return;
|
|
2393
|
+
if (!visible(panel.entry.host)) closePanel(false);
|
|
2394
|
+
else positionPanel();
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
const observer = new MutationObserver(records => {
|
|
2398
|
+
if (records.every(r => r.target.closest?.('[data-codex-session-status], [data-codex-session-status-panel]'))) return;
|
|
2399
|
+
schedule();
|
|
2400
|
+
});
|
|
2401
|
+
const filter = harness?.attributeFilter || ['data-app-action-sidebar-thread-selected', 'data-app-action-sidebar-thread-id', 'data-app-action-sidebar-thread-host-id', 'data-app-action-sidebar-thread-title', 'hidden', 'aria-expanded', 'style', 'class', 'data-theme'];
|
|
2402
|
+
if (!embedded) {
|
|
2403
|
+
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: filter });
|
|
2404
|
+
document.addEventListener('pointerdown', onOutside, true);
|
|
2405
|
+
document.addEventListener('keydown', onKey, true);
|
|
2406
|
+
document.addEventListener('scroll', onScroll, true);
|
|
2407
|
+
}
|
|
2408
|
+
window.addEventListener('resize', positionPanel);
|
|
2409
|
+
const api = {
|
|
2410
|
+
receive(next) { receive(next); localCards?.receive(next); },
|
|
2411
|
+
receiveCardEvent({ snapshot: next, analysisState, session }) {
|
|
2412
|
+
if (!embedded) return;
|
|
2413
|
+
embedded.streamConnected = true;
|
|
2414
|
+
if (!next || next.revision < snapshot.revision) return;
|
|
2415
|
+
if (panel && session?.key === panel.entry.key) panel.capabilities = session.capabilities;
|
|
2416
|
+
receive(next);
|
|
2417
|
+
panel?.showHistory(analysisState);
|
|
2418
|
+
},
|
|
2419
|
+
disconnectCardEvents() {
|
|
2420
|
+
if (!embedded?.streamConnected) return;
|
|
2421
|
+
embedded.streamConnected = false;
|
|
2422
|
+
if (panel?.analyzing) panel.pollHistory();
|
|
2423
|
+
},
|
|
2424
|
+
setTheme(theme) { if (embedded && embedded.theme !== theme && ['light', 'dark'].includes(theme)) { embedded.theme = theme; positionPanel(); } },
|
|
2425
|
+
reply(message) {
|
|
2426
|
+
localCards?.reply(message);
|
|
2427
|
+
const { requestId, error, errorInfo, session, snapshot: next, analysisState, projectGit, updateInfo, navigation, pane } = message;
|
|
2428
|
+
if (panel && session?.key === panel.entry.key) panel.capabilities = session.capabilities;
|
|
2429
|
+
receive(next);
|
|
2430
|
+
const request = pending.get(requestId);
|
|
2431
|
+
if (!request) return;
|
|
2432
|
+
clearTimeout(request.timer); pending.delete(requestId);
|
|
2433
|
+
if (error) request.reject(Object.assign(new Error(error), errorInfo || {})); else request.resolve(navigation || updateInfo || projectGit || analysisState || pane);
|
|
2434
|
+
},
|
|
2435
|
+
status: () => ({ mounted: mounted.size, panelOpen: Boolean(panel), revision: snapshot.revision, version, startup: { ...startup } }),
|
|
2436
|
+
exportForReload({ allowPending = false } = {}) {
|
|
2437
|
+
if (!allowPending && (panel?.busy || pending.size)) return { busy: true };
|
|
2438
|
+
const active = panel ? rememberPanel(panel) : null;
|
|
2439
|
+
return { snapshot, panel: active, panelStates: [...panelStates], localCards: localCards?.exportState() };
|
|
2440
|
+
},
|
|
2441
|
+
destroy() {
|
|
2442
|
+
destroyed = true; localCards?.destroy(); harness?.dispose?.(); observer.disconnect(); cancelAnimationFrame(frame);
|
|
2443
|
+
if (panel) { rememberPanel(panel); panelEvent('dispose', panel.entry); clearTimeout(panel.pollTimer); clearTimeout(panel.updateTimer); cancelAnimationFrame(panel.marqueeFrame); panel.resizeObserver?.disconnect(); panel.root.remove(); panel.entry.button?.setAttribute('aria-expanded', 'false'); panel = null; }
|
|
2444
|
+
for (const entry of [...mounted.values()]) unmount(entry);
|
|
2445
|
+
document.removeEventListener('pointerdown', onOutside, true); document.removeEventListener('keydown', onKey, true);
|
|
2446
|
+
document.removeEventListener('scroll', onScroll, true); window.removeEventListener('resize', positionPanel);
|
|
2447
|
+
for (const request of pending.values()) { clearTimeout(request.timer); request.reject(new Error(S('cardDaemonDisconnected'))); }
|
|
2448
|
+
pending.clear(); if (!embedded?.independent) delete window.__codexSessionStatus;
|
|
2449
|
+
if (harness?.globalName && window[harness.globalName]) delete window[harness.globalName];
|
|
2450
|
+
}
|
|
2451
|
+
};
|
|
2452
|
+
if (!embedded?.independent) window.__codexSessionStatus = api;
|
|
2453
|
+
if (harness?.globalName) window[harness.globalName] = api;
|
|
2454
|
+
if (embedded) {
|
|
2455
|
+
receive(embedded.snapshot);
|
|
2456
|
+
openPanel({ key: embedded.key, title: embedded.title });
|
|
2457
|
+
if (restored?.panel) restorePanel(panel, restored.panel);
|
|
2458
|
+
return api;
|
|
2459
|
+
}
|
|
2460
|
+
localCards = harness?.createLocalCards?.({
|
|
2461
|
+
mount: (options, state) => installCodexSessionStatus(version, state, options),
|
|
2462
|
+
send: payload => send(payload), snapshot: () => snapshot, restored: restored?.localCards,
|
|
2463
|
+
});
|
|
2464
|
+
reconcile();
|
|
2465
|
+
if (restored) {
|
|
2466
|
+
receive(restored.snapshot);
|
|
2467
|
+
const saved = restored.panel;
|
|
2468
|
+
const entry = saved && [...mounted.values()].find(item => item.key === saved.key);
|
|
2469
|
+
if (entry) {
|
|
2470
|
+
panelStates.set(saved.key, saved);
|
|
2471
|
+
openPanel(entry);
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
|