agent-things 0.0.0-stage → 1.2.2

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.
Files changed (124) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +5 -0
  3. package/README.md +221 -2
  4. package/bin/agent-things.cjs +8 -0
  5. package/bin/antigravity-session-status.cjs +96 -0
  6. package/bin/claude-session-status.cjs +55 -0
  7. package/bin/codex-session-status.cjs +287 -0
  8. package/mods/agent-things-ui/.claude-plugin/plugin.json +12 -0
  9. package/mods/agent-things-ui/SKILL.md +10 -0
  10. package/mods/agent-things-ui/hooks/controls.js +112 -0
  11. package/mods/agent-things-ui/hooks/foundation.js +431 -0
  12. package/mods/agent-things-ui/hooks/hooks.json +1 -0
  13. package/mods/agent-things-ui/hooks/presentation.js +223 -0
  14. package/mods/agent-things-ui/hooks/progress.js +1 -0
  15. package/mods/agent-things-ui/hooks/register.js +382 -0
  16. package/native/bin/bridge +0 -0
  17. package/native/bin/bridge.json +20 -0
  18. package/native/session-status-bridge.swift +280 -0
  19. package/outputs/antigravity-session-status.js +2476 -0
  20. package/outputs/codex-session-status.js +1761 -0
  21. package/package.json +75 -4
  22. package/scripts/build-antigravity-bundle.cjs +35 -0
  23. package/scripts/build-codex-bundle.cjs +31 -0
  24. package/scripts/build-native-bridge.cjs +55 -0
  25. package/scripts/build-shared-ui.cjs +16 -0
  26. package/scripts/setup-antigravity-service.cjs +71 -0
  27. package/scripts/setup-claude-service.cjs +21 -0
  28. package/skills/agent-things/SKILL.en.md +95 -0
  29. package/skills/agent-things/SKILL.md +99 -0
  30. package/skills/codex/things/SKILL.en.md +10 -0
  31. package/skills/codex/things/SKILL.md +10 -0
  32. package/skills/things/SKILL.en.md +10 -0
  33. package/skills/things/SKILL.md +10 -0
  34. package/skills/things/checklist.en.md +91 -0
  35. package/skills/things/checklist.md +95 -0
  36. package/src/analysis-app-server.cjs +74 -0
  37. package/src/analysis-assets/output.en.schema.json +93 -0
  38. package/src/analysis-assets/output.schema.json +93 -0
  39. package/src/analysis-assets/prompt.en.txt +17 -0
  40. package/src/analysis-assets/prompt.zh-CN.txt +18 -0
  41. package/src/analysis-budget.cjs +105 -0
  42. package/src/analysis-git.cjs +38 -0
  43. package/src/analysis-history.cjs +150 -0
  44. package/src/analysis-ledger.cjs +82 -0
  45. package/src/analysis-log.cjs +62 -0
  46. package/src/analysis-runner.cjs +203 -0
  47. package/src/analysis-service.cjs +197 -0
  48. package/src/analysis-source.cjs +72 -0
  49. package/src/antigravity-card.cjs +2063 -0
  50. package/src/antigravity-hook.cjs +138 -0
  51. package/src/antigravity-mcp-config.cjs +36 -0
  52. package/src/app-server.cjs +96 -0
  53. package/src/cdp.cjs +115 -0
  54. package/src/claude-inline-install.cjs +38 -0
  55. package/src/claude-mcp-config.cjs +29 -0
  56. package/src/cli/arguments.cjs +30 -0
  57. package/src/cli/environment-probe.cjs +130 -0
  58. package/src/cli/integration-state.cjs +15 -0
  59. package/src/cli/interactive-cli.cjs +236 -0
  60. package/src/cli/prompt-tui.cjs +420 -0
  61. package/src/cli/setup-orchestrator.cjs +449 -0
  62. package/src/codex-mcp-config.cjs +67 -0
  63. package/src/harnesses/antigravity/analysis-profile.cjs +41 -0
  64. package/src/harnesses/antigravity/antigravity-git.cjs +89 -0
  65. package/src/harnesses/antigravity/antigravity-harness.js +1477 -0
  66. package/src/harnesses/antigravity/antigravity-injector.cjs +104 -0
  67. package/src/harnesses/antigravity/antigravity-migration.cjs +235 -0
  68. package/src/harnesses/antigravity/antigravity-service.cjs +357 -0
  69. package/src/harnesses/antigravity/antigravity-title.cjs +155 -0
  70. package/src/harnesses/antigravity/gemini-runner.cjs +304 -0
  71. package/src/harnesses/antigravity/transcript-cleaner.cjs +129 -0
  72. package/src/harnesses/antigravity/transcript-source.cjs +100 -0
  73. package/src/harnesses/claude/claude-harness.js +93 -0
  74. package/src/harnesses/claude/claude-host-helper.cjs +176 -0
  75. package/src/harnesses/claude/claude-injector.cjs +95 -0
  76. package/src/harnesses/claude/claude-local-source.cjs +106 -0
  77. package/src/harnesses/claude/claude-navigation.cjs +99 -0
  78. package/src/harnesses/claude/claude-runner.cjs +74 -0
  79. package/src/harnesses/claude/claude-service.cjs +313 -0
  80. package/src/harnesses/claude/claude-source.cjs +70 -0
  81. package/src/harnesses/codex/codex-analysis.cjs +10 -0
  82. package/src/harnesses/codex/codex-card-bridge.js +123 -0
  83. package/src/harnesses/codex/codex-card-events.cjs +76 -0
  84. package/src/harnesses/codex/codex-card.cjs +169 -0
  85. package/src/harnesses/codex/codex-git.cjs +24 -0
  86. package/src/harnesses/codex/codex-harness.js +229 -0
  87. package/src/harnesses/codex/codex-local-card.js +97 -0
  88. package/src/harnesses/codex/codex-progress-context.cjs +84 -0
  89. package/src/harnesses/codex/codex-service.cjs +502 -0
  90. package/src/i18n.cjs +174 -0
  91. package/src/launchd.cjs +105 -0
  92. package/src/lifecycle-lock.cjs +13 -0
  93. package/src/local-progress-http.cjs +267 -0
  94. package/src/manual-status-agent.cjs +12 -0
  95. package/src/manual-status-startup.cjs +66 -0
  96. package/src/manual-status-store.cjs +466 -0
  97. package/src/mcp-stdio.cjs +67 -0
  98. package/src/model-router.cjs +63 -0
  99. package/src/native-bridge.cjs +17 -0
  100. package/src/npm-updates.cjs +228 -0
  101. package/src/plugins/things/assets/logo.svg +13 -0
  102. package/src/plugins/things/plugin.json +6 -0
  103. package/src/plugins/things/sidecars/things_board/app.js +447 -0
  104. package/src/plugins/things/sidecars/things_board/index.html +2141 -0
  105. package/src/plugins/things/sidecars/things_board/main.mjs +652 -0
  106. package/src/plugins/things/sidecars/things_board/package.json +6 -0
  107. package/src/plugins/things/sidecars/things_board/sidecar.json +21 -0
  108. package/src/plugins/things/sidecars/things_board/styles.css +560 -0
  109. package/src/plugins/things/sidecars/things_board/ui-i18n.mjs +434 -0
  110. package/src/progress-error.cjs +54 -0
  111. package/src/progress-tools.cjs +145 -0
  112. package/src/project-path.cjs +15 -0
  113. package/src/renderer-resource.cjs +17 -0
  114. package/src/request-budget.cjs +24 -0
  115. package/src/resolve.cjs +51 -0
  116. package/src/runtime-install.cjs +635 -0
  117. package/src/session-status-filter.cjs +136 -0
  118. package/src/session-status.js +992 -0
  119. package/src/session-view.cjs +34 -0
  120. package/src/startup/controller.cjs +354 -0
  121. package/src/startup/watch.cjs +126 -0
  122. package/src/state-file-lock.cjs +31 -0
  123. package/src/task-provenance.cjs +42 -0
  124. package/src/ui-foundation.cjs +435 -0
@@ -0,0 +1,1761 @@
1
+ // Agent Things Codex Bundle (Auto-generated)
2
+ // Things 3 task manager and session progress overlay for Codex
3
+
4
+ 'use strict';
5
+ // Local conversation surface; its lifetime is owned by the Codex adapter.
6
+ function createCodexLocalCards({ mount, send, snapshot, restored }) {
7
+ const getFallbackTitle = () => {
8
+ const p = window.__agentThingsPresentation;
9
+ const lang = snapshot()?.lang || window.__agentThingsLang || p?.lang || 'zh';
10
+ const ui = p?.forLang ? p.forLang(lang) : null;
11
+ return ui?.strings?.fallbackShortTitle ?? p?.strings?.fallbackShortTitle ?? '会话进度';
12
+ };
13
+ const states = new Map(restored || []);
14
+ let active = null, stopped = false, reconciling = false;
15
+ const visible = node => node?.isConnected && node.getClientRects().length > 0;
16
+ function theme(row) {
17
+ for (let node = row; node; node = node.parentElement) {
18
+ const rgba = getComputedStyle(node).backgroundColor.match(/[\d.]+/g)?.map(Number);
19
+ if (rgba && (rgba[3] ?? 1) >= .95) return rgba[0] * .2126 + rgba[1] * .7152 + rgba[2] * .0722 < 150 ? 'dark' : 'light';
20
+ }
21
+ return matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
22
+ }
23
+ function current() {
24
+ const composers = [...document.querySelectorAll('[data-codex-composer-root]')].filter(visible);
25
+ const rows = [...document.querySelectorAll('[data-app-action-sidebar-thread-row][data-app-action-sidebar-thread-selected="true"]')];
26
+ const contents = [...document.querySelectorAll('[data-thread-find-target="conversation"]')].filter(visible);
27
+ if (composers.length !== 1 || rows.length !== 1 || contents.length !== 1) return null;
28
+ const row = rows[0], kind = row.getAttribute('data-app-action-sidebar-thread-kind');
29
+ if (!['local', 'remote'].includes(kind)) return null;
30
+ const id = row.getAttribute('data-app-action-sidebar-thread-id');
31
+ if (!id) return null;
32
+ return { composer: composers[0], content: contents[0], theme: theme(row), key: JSON.stringify([row.getAttribute('data-app-action-sidebar-thread-host-id') || (kind === 'remote' ? 'cloud' : 'local'), id]),
33
+ title: row.getAttribute('data-app-action-sidebar-thread-title') || getFallbackTitle() };
34
+ }
35
+ function retain() {
36
+ if (!active) return;
37
+ states.set(active.key, { title: active.title, saved: active.api.exportForReload({ allowPending: true }) });
38
+ active.api.destroy(); active.container.remove(); active = null;
39
+ }
40
+ function open(entry) {
41
+ if (active?.key === entry.key && active.container.isConnected) return active;
42
+ retain();
43
+ const container = document.createElement('section');
44
+ container.setAttribute('data-agent-things-local-card', entry.key);
45
+ container.setAttribute('aria-label', getFallbackTitle());
46
+ container.style.cssText = 'width:340px;max-width:100%;margin:12px 0;flex:none';
47
+ entry.content.append(container);
48
+ try {
49
+ const api = mount({ container, key: entry.key, title: entry.title, snapshot: snapshot(), send,
50
+ independent: true, theme: entry.theme }, states.get(entry.key)?.saved);
51
+ active = { ...entry, container, api };
52
+ states.set(entry.key, { title: entry.title, saved: null });
53
+ return active;
54
+ } catch (error) { container.remove(); throw error; }
55
+ }
56
+ function reconcile() {
57
+ if (stopped || reconciling) return;
58
+ reconciling = true;
59
+ try {
60
+ const entry = current();
61
+ if (!entry) { retain(); return; }
62
+ if (active && (active.key !== entry.key || !active.container.isConnected || active.composer !== entry.composer || active.content !== entry.content)) retain();
63
+ if (!active && states.has(entry.key)) open(entry);
64
+ active?.api.setTheme(entry.theme);
65
+ } finally { reconciling = false; }
66
+ }
67
+ function consume(event) {
68
+ const keyboard = event.type === 'keydown';
69
+ if (keyboard && (event.key !== 'Enter' || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || event.isComposing)) return;
70
+ if (!keyboard && !/^(发送|Send)(提示|消息| prompt| message)?$/i.test(event.target.closest?.('button')?.getAttribute('aria-label') || '')) return;
71
+ const entry = current();
72
+ if (!entry || !entry.composer.contains(event.target)) return;
73
+ const editor = entry.composer.querySelector('[contenteditable="true"]');
74
+ if (!editor || editor.textContent.trim() !== '/things') return;
75
+ // Rich mentions/attachments remain host submissions.
76
+ if (editor.querySelector('[contenteditable="false"]')) return;
77
+ try { open(entry); } catch { return; }
78
+ event.preventDefault(); event.stopImmediatePropagation();
79
+ editor.focus();
80
+ const selection = document.getSelection(), range = document.createRange();
81
+ range.selectNodeContents(editor); selection.removeAllRanges(); selection.addRange(range);
82
+ document.execCommand('delete');
83
+ active?.container.scrollIntoView({ block: 'start', behavior: 'instant' });
84
+ }
85
+ document.addEventListener('keydown', consume, true);
86
+ document.addEventListener('click', consume, true);
87
+ const observer = new MutationObserver(reconcile);
88
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true,
89
+ attributeFilter: ['data-app-action-sidebar-thread-selected', 'data-app-action-sidebar-thread-id', 'hidden', 'class', 'data-theme', 'data-color-mode'] });
90
+ reconcile();
91
+ return {
92
+ receive(value) { active?.api.receive(value); },
93
+ reply(value) { active?.api.reply(value); },
94
+ exportState() {
95
+ if (active) states.set(active.key, { title: active.title, saved: active.api.exportForReload({ allowPending: true }) });
96
+ return [...states];
97
+ },
98
+ destroy() { stopped = true; observer.disconnect(); document.removeEventListener('keydown', consume, true); document.removeEventListener('click', consume, true); retain(); },
99
+ };
100
+ }
101
+
102
+ (() => { const module = { exports: {} }; 'use strict';
103
+
104
+ // Pure presentation rules. Browser and Mods adapters are built from this same factory.
105
+ function createPresentation(lang) {
106
+ const normalizeLang = value => (value === 'en' ? 'en' : 'zh');
107
+ const currentLang = normalizeLang(lang ?? (typeof globalThis !== 'undefined' ? globalThis.__agentThingsLang : undefined));
108
+ const colors = { unstarted: '#9098a2', unfinished: '#c89b38', completed: '#548eea', pushed: '#a17be3' };
109
+ const layout = { contentWidth: 300, panelWidth: 340, progressNodes: [0, 25, 50, 75, 100] };
110
+ const accent = { normal: '#0169CC', hover: '#005bb3', pressed: '#004f9c' };
111
+
112
+ const locales = {
113
+ zh: {
114
+ appTitle: 'Agent Things',
115
+ docTitleSuffix: '任务进展',
116
+ defaultDocTitle: 'Agent Things 会话任务进度',
117
+ defaultSessionTitle: '当前会话',
118
+ fallbackShortTitle: '会话进度',
119
+ fallbackThreadTitle: '会话',
120
+ labels: {
121
+ unstarted: '尚未开始',
122
+ unfinished: '有遗留事项',
123
+ completed: '全部完成',
124
+ pushed: '全部完成并已推送',
125
+ },
126
+ taskLabels: {
127
+ todo: '待开始',
128
+ in_progress: '进行中',
129
+ blocked: '受阻',
130
+ needs_verification: '待验收',
131
+ done: '已完成',
132
+ unknown: '状态未知',
133
+ },
134
+ unrecordedSummary: '尚未记录进展',
135
+ unorganized: '未整理',
136
+ progressUnrecorded: '进度未记录',
137
+ sidebarUpdating: '正在更新进度',
138
+ sidebarTooltipPattern: '{title}:{status},点击记录任务进展',
139
+ noTasksYet: '暂无任务统计',
140
+ totalsPattern: '已完成 {done} / {total} 项任务',
141
+ basisPattern: '已完成 {done}/{total} 项任务,剩余 {remaining} 项({remainingPercent}%)',
142
+ basisEmpty: '暂无任务',
143
+ sourceAuto: '自动分析',
144
+ sourceManual: '手动调整',
145
+ sourceManualRecord: '手动记录',
146
+ btnUpdate: '更新进度',
147
+ btnUpdating: '正在分析…',
148
+ btnAdjust: '手动调整',
149
+ btnClear: '清除进度',
150
+ clearTooltip: '立即清除进度与任务记录',
151
+ clearConfirm: '确定要清除本会话的任务进度和记录吗?',
152
+ clearingFeedback: '正在清除…',
153
+ clearedFeedback: '✓ 已清空进度',
154
+ clearFailedPrefix: '清除失败: ',
155
+ openInSidebar: '在侧栏打开',
156
+ openPaneFailedPrefix: '打开侧栏失败: ',
157
+ close: '关闭',
158
+ expandAll: '查看全部',
159
+ collapse: '收起',
160
+ remainingHeadingPattern: '剩余任务 {count}',
161
+ showAllCountPattern: '查看全部 {count} 条 ›',
162
+ collapseArrow: '收起 ›',
163
+ emptyNoTasks: '点击更新进度,整理这次会话的任务',
164
+ emptyNoRemaining: '暂无未完成任务',
165
+ completedHeading: '已完成任务',
166
+ countArrowPattern: '{count} 条 ›',
167
+ notesLabel: '备注',
168
+ addLabel: '添加',
169
+ editLabel: '编辑',
170
+ untitledTask: '未命名事项',
171
+ completedTaskFallback: '已完成事项',
172
+ viewSource: '查看来源',
173
+ viewSourceAriaPrefix: '查看来源:',
174
+ backLabel: '‹ 返回',
175
+ backPlain: '返回',
176
+ emptyCompleted: '暂无已完成任务',
177
+ emptySourceText: '此记录没有可显示的原文',
178
+ editHeading: '手动记录会话状态',
179
+ progressLabel: '进度',
180
+ progressAltPattern: '进度 {value}%',
181
+ progressUnrecordedWord: '未记录',
182
+ currentProgressAlt: '当前进度',
183
+ clearValueBtn: '清空进度',
184
+ notePlaceholder: '记下下一步要做的事…',
185
+ noteAriaLabel: '事项备注',
186
+ sliderAriaLabel: '拖动调整进度',
187
+ cancelBtn: '取消',
188
+ saveBtn: '保存记录',
189
+ savingBtn: '正在保存…',
190
+ savingFeedback: '正在保存…',
191
+ savedFeedback: '✓ 保存成功',
192
+ saveFailedPrefix: '保存失败: ',
193
+ conflictBanner: '保存冲突:内容已被其他入口修改。当前草稿已保留。',
194
+ conflictShortToast: '保存冲突,已保留当前草稿',
195
+ conflictDetectedFeedback: '保存失败:检测到版本冲突',
196
+ resolveConflictBtn: '读取最新版本并保留草稿',
197
+ conflictRebasedFeedback: '基准版本已对齐最新状态,再次点击保存即可提交当前草稿。',
198
+ conflictReloadedFeedback: '已读取最新版本,草稿已保留。再次保存即可提交。',
199
+ timelineHeading: '进展记录',
200
+ timelineLink: '进展记录 ›',
201
+ emptyTimeline: '暂无进展记录',
202
+ dividerAlt: '分隔线',
203
+ loadingTitle: '正在读取会话进度…',
204
+ loadingAlt: '加载中',
205
+ loadingTasksAlt: '正在加载任务列表',
206
+ loadingSubtitle: '正在同步当前会话任务,完成后将自动更新…',
207
+ notLoadedTitle: '尚未读取到会话进度',
208
+ notLoadedAlt: '未读取',
209
+ retryLoadBtn: '重试读取',
210
+ processing: '正在处理…',
211
+ retryingStatus: '状态查询暂时失败,正在重试…',
212
+ locatingMessage: '正在定位消息…',
213
+ locatingShort: '定位中...',
214
+ locatingSourceMessage: '正在定位来源消息…',
215
+ locatedMessage: '已定位来源',
216
+ locatedJumpMessage: '已跳转并定位到会话来源',
217
+ locateSent: '已发送定位请求',
218
+ locateFailedPrefix: '定位失败:',
219
+ locateHostUnavailable: '未能连接宿主定位接口',
220
+ locateNotFound: '未找到对应会话消息',
221
+ locateUnsupported: '当前环境不支持跳转来源',
222
+ locateTimeout: '定位来源超时,请在原会话中确认历史消息',
223
+ locateNoSource: '此记录没有可定位的消息',
224
+ locateHostDisconnected: '当前宿主未连接,暂时无法定位来源消息',
225
+ locateOpenFailed: '无法打开来源会话',
226
+ locateUnavailable: '暂时无法定位来源消息',
227
+ locateCommandErrorPrefix: '跳转失败:',
228
+ startingAnalysisFeedback: '正在开始分析…',
229
+ updateFailedPrefix: '更新失败: ',
230
+ analysisNotDonePrefix: '分析未完成: ',
231
+ analysisFailedPrefix: '分析失败:',
232
+ analysisFailedWord: '分析失败',
233
+ analyzingWord: '分析中',
234
+ analysisFailedRetry: '请重试',
235
+ analysisAbnormal: '执行异常',
236
+ analysisStages: {
237
+ starting: '正在启动分析…',
238
+ reading: '正在读取会话…',
239
+ analyzing: '正在分析任务…',
240
+ retrying: '正在重新连接…',
241
+ },
242
+ invalidProgressError: '请输入 0–100 的整数,或留空',
243
+ unknownActionError: '未知错误',
244
+ gitCheckUnavailable: '暂时无法检测 Git 信息',
245
+ sidebarHintText: '如需启用侧边栏插件,请打开「开发者 → Enable Main Process Debugger」。',
246
+ dismissHint: '不再提醒',
247
+ updateStages: {
248
+ queued: '正在准备升级',
249
+ checking: '正在检查版本',
250
+ downloading: '正在下载新版本',
251
+ waiting: '等待当前分析结束',
252
+ installing: '正在升级',
253
+ },
254
+ updateAvailablePattern: '发现新版本 v{version}',
255
+ upgradedToPattern: '已升级至 v{version}',
256
+ updateFailedLabel: '升级失败',
257
+ upgradeBtn: '立即升级',
258
+ upgradingShort: '正在升级…',
259
+ pleaseWait: '请稍候',
260
+ completedShort: '已完成',
261
+ retryBtn: '重试',
262
+ terminalUpgradePrefix: '终端升级:',
263
+ reconnectHint: '正在重新连接后台,升级状态将在连接后恢复',
264
+ reconnectMcpHint: '请在客户端重新连接 MCP 服务',
265
+ cardCommandDescription: '打开会话任务进度卡片',
266
+ cardCommandReply: 'Agent Things · 会话任务进度',
267
+ cardMissingSession: '卡片缺少当前会话信息',
268
+ cardAuthUnavailable: '卡片授权不可用,请重新打开会话进度卡片',
269
+ cardSyncUnavailable: '卡片同步暂不可用',
270
+ cardTimeout: '卡片连接超时',
271
+ cardClosed: '卡片已关闭',
272
+ cardOpFailed: '卡片操作失败',
273
+ cardRequestCancelled: '请求已取消',
274
+ cardRequestTimeout: '请求超时,请重试',
275
+ cardStatusDisconnected: '状态连接暂不可用',
276
+ cardDaemonDisconnected: '本地进程已断开',
277
+ claudeInlineOffline: '本地后台连接失败',
278
+ mdProgressHeading: '当前会话任务进度',
279
+ mdStateDone: '全部完成 (100%)',
280
+ mdStateUnstarted: '未开始',
281
+ mdTasksOverview: '任务总览',
282
+ mdTasksEmpty: '暂无任务清单',
283
+ mdNotesLabel: '会话备注',
284
+ mdQuickActionsLabel: '快捷交互',
285
+ mdQuickActionsText: '可在卡片中点击“手动调整”滑动调整进度或修改备注,或点击“更新进度”开始自动分析。',
286
+ hookPresentedMessage: '已呈现当前会话任务进度卡片',
287
+ noSessionBadge: '无会话',
288
+ offlineBadge: '离线',
289
+ },
290
+ en: {
291
+ appTitle: 'Agent Things',
292
+ docTitleSuffix: 'Progress',
293
+ defaultDocTitle: 'Agent Things Progress',
294
+ defaultSessionTitle: 'Current session',
295
+ fallbackShortTitle: 'Session progress',
296
+ fallbackThreadTitle: 'Session',
297
+ labels: {
298
+ unstarted: 'Not started',
299
+ unfinished: 'Remaining items',
300
+ completed: 'Completed',
301
+ pushed: 'Completed & pushed',
302
+ },
303
+ taskLabels: {
304
+ todo: 'To do',
305
+ in_progress: 'In progress',
306
+ blocked: 'Blocked',
307
+ needs_verification: 'Needs verification',
308
+ done: 'Done',
309
+ unknown: 'Unknown status',
310
+ },
311
+ unrecordedSummary: 'No progress recorded',
312
+ unorganized: 'Not organized',
313
+ progressUnrecorded: 'Progress not recorded',
314
+ sidebarUpdating: 'Updating progress',
315
+ sidebarTooltipPattern: '{title}: {status} · Click to track progress',
316
+ noTasksYet: 'No task stats yet',
317
+ totalsPattern: '{done} of {total} tasks done',
318
+ basisPattern: 'Completed {done}/{total} tasks, {remaining} remaining ({remainingPercent}%)',
319
+ basisEmpty: 'No tasks yet',
320
+ sourceAuto: 'Auto-analyzed',
321
+ sourceManual: 'Manual',
322
+ sourceManualRecord: 'Manual',
323
+ btnUpdate: 'Update progress',
324
+ btnUpdating: 'Analyzing...',
325
+ btnAdjust: 'Adjust',
326
+ btnClear: 'Clear',
327
+ clearTooltip: 'Clear progress and task records now',
328
+ clearConfirm: 'Clear progress and task records for this session?',
329
+ clearingFeedback: 'Clearing...',
330
+ clearedFeedback: '✓ Cleared',
331
+ clearFailedPrefix: 'Clear failed: ',
332
+ openInSidebar: 'Open in sidebar',
333
+ openPaneFailedPrefix: 'Open sidebar failed: ',
334
+ close: 'Close',
335
+ expandAll: 'Show all',
336
+ collapse: 'Collapse',
337
+ remainingHeadingPattern: 'Remaining tasks ({count})',
338
+ showAllCountPattern: 'Show all {count} ›',
339
+ collapseArrow: 'Collapse ›',
340
+ emptyNoTasks: 'Click Update progress to organize tasks for this session',
341
+ emptyNoRemaining: 'No remaining tasks',
342
+ completedHeading: 'Completed tasks',
343
+ countArrowPattern: '{count} ›',
344
+ notesLabel: 'Notes',
345
+ addLabel: 'Add',
346
+ editLabel: 'Edit',
347
+ untitledTask: 'Untitled task',
348
+ completedTaskFallback: 'Completed task',
349
+ viewSource: 'View source',
350
+ viewSourceAriaPrefix: 'View source: ',
351
+ backLabel: '‹ Back',
352
+ backPlain: 'Back',
353
+ emptyCompleted: 'No completed tasks',
354
+ emptySourceText: 'No original message text available for this record',
355
+ editHeading: 'Set session status',
356
+ progressLabel: 'Progress',
357
+ progressAltPattern: 'Progress {value}%',
358
+ progressUnrecordedWord: 'unrecorded',
359
+ currentProgressAlt: 'Current progress',
360
+ clearValueBtn: 'Clear value',
361
+ notePlaceholder: 'Add next steps or notes...',
362
+ noteAriaLabel: 'Session notes',
363
+ sliderAriaLabel: 'Drag to adjust progress',
364
+ cancelBtn: 'Cancel',
365
+ saveBtn: 'Save',
366
+ savingBtn: 'Saving...',
367
+ savingFeedback: 'Saving...',
368
+ savedFeedback: '✓ Saved',
369
+ saveFailedPrefix: 'Save failed: ',
370
+ conflictBanner: 'Save conflict: updated elsewhere. Your draft has been kept.',
371
+ conflictShortToast: 'Save conflict, draft kept',
372
+ conflictDetectedFeedback: 'Save failed: revision conflict detected',
373
+ resolveConflictBtn: 'Load latest & keep draft',
374
+ conflictRebasedFeedback: 'Synced to latest version. Click Save again to submit your draft.',
375
+ conflictReloadedFeedback: 'Loaded latest version with draft preserved. Save again to submit.',
376
+ timelineHeading: 'Timeline',
377
+ timelineLink: 'Timeline ›',
378
+ emptyTimeline: 'No activity yet',
379
+ dividerAlt: 'Divider',
380
+ loadingTitle: 'Loading session progress...',
381
+ loadingAlt: 'Loading',
382
+ loadingTasksAlt: 'Loading task list',
383
+ loadingSubtitle: 'Syncing session tasks, will update automatically...',
384
+ notLoadedTitle: 'Session progress not loaded yet',
385
+ notLoadedAlt: 'Not loaded',
386
+ retryLoadBtn: 'Retry',
387
+ processing: 'Processing...',
388
+ retryingStatus: 'Status check failed, retrying...',
389
+ locatingMessage: 'Locating message...',
390
+ locatingShort: 'Locating...',
391
+ locatingSourceMessage: 'Locating source message...',
392
+ locatedMessage: 'Source located',
393
+ locatedJumpMessage: 'Jumped to source message',
394
+ locateSent: 'Locate request sent',
395
+ locateFailedPrefix: 'Locate failed: ',
396
+ locateHostUnavailable: 'Unable to reach host locate API',
397
+ locateNotFound: 'Source message not found',
398
+ locateUnsupported: 'Jumping to source is not supported here',
399
+ locateTimeout: 'Locate timed out. Please check conversation history.',
400
+ locateNoSource: 'No locatable source message for this item',
401
+ locateHostDisconnected: 'Host is disconnected, unable to locate source message',
402
+ locateOpenFailed: 'Unable to open source session',
403
+ locateUnavailable: 'Unable to locate source message right now',
404
+ locateCommandErrorPrefix: 'Jump failed: ',
405
+ startingAnalysisFeedback: 'Starting analysis...',
406
+ updateFailedPrefix: 'Update failed: ',
407
+ analysisNotDonePrefix: 'Analysis incomplete: ',
408
+ analysisFailedPrefix: 'Analysis failed: ',
409
+ analysisFailedWord: 'Analysis failed',
410
+ analyzingWord: 'Analyzing',
411
+ analysisFailedRetry: 'please retry',
412
+ analysisAbnormal: 'execution error',
413
+ analysisStages: {
414
+ starting: 'Starting analysis...',
415
+ reading: 'Reading session...',
416
+ analyzing: 'Analyzing tasks...',
417
+ retrying: 'Reconnecting...',
418
+ },
419
+ invalidProgressError: 'Enter an integer 0–100, or leave blank',
420
+ unknownActionError: 'Unknown error',
421
+ gitCheckUnavailable: 'Git status unavailable right now',
422
+ sidebarHintText: 'To enable the sidebar pane, open Developer → Enable Main Process Debugger.',
423
+ dismissHint: 'Dismiss',
424
+ updateStages: {
425
+ queued: 'Preparing upgrade',
426
+ checking: 'Checking version',
427
+ downloading: 'Downloading update',
428
+ waiting: 'Waiting for analysis to finish',
429
+ installing: 'Upgrading',
430
+ },
431
+ updateAvailablePattern: 'Update available v{version}',
432
+ upgradedToPattern: 'Upgraded to v{version}',
433
+ updateFailedLabel: 'Upgrade failed',
434
+ upgradeBtn: 'Upgrade',
435
+ upgradingShort: 'Upgrading...',
436
+ pleaseWait: 'Please wait',
437
+ completedShort: 'Done',
438
+ retryBtn: 'Retry',
439
+ terminalUpgradePrefix: 'Terminal upgrade: ',
440
+ reconnectHint: 'Reconnecting to background service; upgrade status will resume shortly',
441
+ reconnectMcpHint: 'Please reconnect the MCP server in your client',
442
+ cardCommandDescription: 'Open session task progress card',
443
+ cardCommandReply: 'Agent Things · Session Progress',
444
+ cardMissingSession: 'Card is missing current session info',
445
+ cardAuthUnavailable: 'Card authorization unavailable; please reopen the card',
446
+ cardSyncUnavailable: 'Card sync unavailable',
447
+ cardTimeout: 'Card connection timed out',
448
+ cardClosed: 'Card closed',
449
+ cardOpFailed: 'Card action failed',
450
+ cardRequestCancelled: 'Request cancelled',
451
+ cardRequestTimeout: 'Request timed out, please retry',
452
+ cardStatusDisconnected: 'Status connection unavailable',
453
+ cardDaemonDisconnected: 'Local service disconnected',
454
+ claudeInlineOffline: 'Local service connection failed',
455
+ mdProgressHeading: 'Session task progress',
456
+ mdStateDone: 'Completed (100%)',
457
+ mdStateUnstarted: 'Not started',
458
+ mdTasksOverview: 'Overview',
459
+ mdTasksEmpty: 'No task checklist yet',
460
+ mdNotesLabel: 'Session notes',
461
+ mdQuickActionsLabel: 'Quick actions',
462
+ mdQuickActionsText: 'Click "Adjust" on the card to set progress/notes manually, or click "Update progress" to auto-analyze.',
463
+ hookPresentedMessage: 'Session task progress card presented',
464
+ noSessionBadge: 'No session',
465
+ offlineBadge: 'Offline',
466
+ },
467
+ };
468
+
469
+ function format(template, vars = {}) {
470
+ return String(template || '').replace(/\{(\w+)\}/g, (_, k) => (vars[k] !== undefined ? String(vars[k]) : ''));
471
+ }
472
+
473
+ function forLang(targetLang) {
474
+ const code = normalizeLang(targetLang);
475
+ const dict = locales[code];
476
+ return {
477
+ lang: code,
478
+ strings: dict,
479
+ labels: dict.labels,
480
+ taskLabels: dict.taskLabels,
481
+ t(key, vars) {
482
+ return format(dict[key] ?? locales.zh[key] ?? key, vars);
483
+ },
484
+ formatDate(value) {
485
+ if (!value) return '';
486
+ const d = new Date(value);
487
+ if (Number.isNaN(d.getTime())) return '';
488
+ return `${d.getMonth() + 1}/${d.getDate()} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
489
+ },
490
+ };
491
+ }
492
+
493
+ function progressValue(value, dragging = false) {
494
+ value = Math.max(0, Math.min(100, Math.round(value)));
495
+ const nearest = Math.round(value / 25) * 25;
496
+ return dragging && Math.abs(value - nearest) <= 2 ? nearest : value;
497
+ }
498
+ function progressState(state, value) {
499
+ return value === 100 ? state === 'pushed' ? 'pushed' : 'completed'
500
+ : value === 0 && state === 'unstarted' ? 'unstarted' : 'unfinished';
501
+ }
502
+ function draftTransition(current, event) {
503
+ if (event.type === 'begin') return { draft: { state: event.record?.state || 'unfinished', progress: event.record?.progress ?? null, note: event.record?.note || '' }, baseRevision: event.revision ?? event.record?.revision ?? 0, conflict: false };
504
+ if (event.type === 'patch') return { ...current, draft: { ...current.draft, ...event.patch } };
505
+ if (event.type === 'conflict') return { ...current, conflict: true };
506
+ if (event.type === 'rebase') return { ...current, baseRevision: event.revision, conflict: false };
507
+ if (event.type === 'saved' || event.type === 'cleared') return { draft: null, baseRevision: event.revision, conflict: false };
508
+ return current;
509
+ }
510
+ function analysisDisabled(busy, analyzing, upgradeStage) {
511
+ return Boolean(busy || analyzing || ['waiting', 'installing'].includes(upgradeStage));
512
+ }
513
+
514
+ const active = forLang(currentLang);
515
+ return {
516
+ lang: active.lang,
517
+ labels: active.labels,
518
+ colors,
519
+ taskLabels: active.taskLabels,
520
+ strings: active.strings,
521
+ locales,
522
+ layout,
523
+ accent,
524
+ t: active.t,
525
+ format,
526
+ forLang,
527
+ formatDate: active.formatDate,
528
+ progressValue,
529
+ progressState,
530
+ draftTransition,
531
+ analysisDisabled,
532
+ };
533
+ }
534
+
535
+ const browserSource = `globalThis.__agentThingsPresentation = (${createPresentation.toString()})(globalThis.__agentThingsLang);`;
536
+ module.exports = { createPresentation, browserSource };
537
+
538
+ globalThis.__agentThingsPresentation = module.exports.createPresentation(globalThis.__agentThingsLang); })();
539
+ 'use strict';
540
+ (function () {
541
+ const getUiText = (key, fallback) => {
542
+ const p = window.__agentThingsPresentation;
543
+ const lang = window.__agentThingsLang || p?.lang || 'zh';
544
+ const ui = p?.forLang ? p.forLang(lang) : null;
545
+ return ui?.strings?.[key] ?? p?.strings?.[key] ?? fallback;
546
+ };
547
+ const codexHarness = {
548
+ globalName: '__codexSessionStatus',
549
+ createLocalCards: options => createCodexLocalCards(options),
550
+ supportsRequestCancellation: true,
551
+ attributeFilter: [
552
+ 'data-app-action-sidebar-thread-selected',
553
+ 'data-app-action-sidebar-thread-id',
554
+ 'data-app-action-sidebar-thread-host-id',
555
+ 'data-app-action-sidebar-thread-title',
556
+ 'data-app-action-sidebar-thread-kind',
557
+ 'hidden',
558
+ 'aria-expanded',
559
+ 'style',
560
+ 'class',
561
+ 'data-theme'
562
+ ],
563
+
564
+ send(payload) {
565
+ if (typeof window.__codexSessionStatusSend === 'function') {
566
+ window.__codexSessionStatusSend(payload);
567
+ }
568
+ },
569
+
570
+ isRowSelected(row) {
571
+ if (!row) return false;
572
+ return row.getAttribute('data-app-action-sidebar-thread-selected') === 'true';
573
+ },
574
+
575
+ reconcile({ mounted, unmount, attachHost, paint, paintVisibility, openPanel, closePanel, isPanelBusy, isPanelEntry }) {
576
+ for (const entry of mounted.values()) {
577
+ if (!entry.row.isConnected ||
578
+ !entry.host.isConnected ||
579
+ entry.row.getAttribute('data-app-action-sidebar-thread-id') !== entry.threadId ||
580
+ entry.row.getAttribute('data-app-action-sidebar-thread-host-id') !== entry.rawHost) {
581
+ if (entry.slot?.classList.contains('status-slot-injected')) {
582
+ entry.slot.remove();
583
+ }
584
+ unmount(entry);
585
+ }
586
+ }
587
+
588
+ // 支持匹配全部侧边栏会话项(包括项目列表项与近期普通会话项)
589
+ const rows = document.querySelectorAll('[data-app-action-sidebar-thread-row]');
590
+ for (const row of rows) {
591
+ const kind = row.getAttribute('data-app-action-sidebar-thread-kind');
592
+ if (kind !== 'local' && kind !== 'remote') continue;
593
+ const threadId = row.getAttribute('data-app-action-sidebar-thread-id');
594
+ if (!threadId) continue;
595
+
596
+ const titleNode = row.querySelector('[data-thread-title]');
597
+ const title = row.getAttribute('data-app-action-sidebar-thread-title') || titleNode?.textContent?.trim() || getUiText('fallbackThreadTitle', '会话');
598
+ const existing = mounted.get(row);
599
+ if (existing) {
600
+ if (existing.title !== title) { existing.title = title; paint(existing); }
601
+ paintVisibility(existing);
602
+ continue;
603
+ }
604
+
605
+ // 识别或挂载插槽(仅在原生前置槽位完全空置时复用;若已被原生图标占用或不存在,则插入独立防溢出插槽)
606
+ const trigger = titleNode?.closest('[data-thread-title-trigger]') || row.querySelector('button') || row.firstElementChild;
607
+ let slot = trigger?.previousElementSibling;
608
+ let emptyWrapper = false;
609
+ let placeholder = null;
610
+
611
+ if (slot && slot.classList.contains('status-slot-injected')) {
612
+ // 已存在的独立注入槽
613
+ emptyWrapper = false;
614
+ } else if (slot && slot.classList.contains('w-4')) {
615
+ placeholder = slot.firstElementChild;
616
+ emptyWrapper = slot.childElementCount === 1 && placeholder?.tagName === 'DIV' &&
617
+ placeholder.childElementCount === 0 && !placeholder.textContent.trim();
618
+ }
619
+
620
+ // 若前置槽不存在、或者虽有 w-4 但里面有原生真实图标占用,则创建并插入独立插槽
621
+ if (!slot || (!slot.classList.contains('status-slot-injected') && !emptyWrapper)) {
622
+ slot = row.querySelector('.status-slot-injected');
623
+ if (!slot) {
624
+ slot = document.createElement('div');
625
+ slot.className = 'status-slot-injected w-4';
626
+ slot.style.cssText = 'width:24px;min-width:24px;display:flex;align-items:center;justify-content:center;flex-shrink:0';
627
+ if (trigger?.parentElement) {
628
+ trigger.parentElement.insertBefore(slot, trigger);
629
+ } else {
630
+ row.prepend(slot);
631
+ }
632
+ }
633
+ emptyWrapper = false;
634
+ placeholder = null;
635
+ }
636
+
637
+ const rawHost = row.getAttribute('data-app-action-sidebar-thread-host-id');
638
+ const key = JSON.stringify([rawHost || (kind === 'remote' ? 'cloud' : 'local'), threadId]);
639
+ const { host, button, original } = attachHost(slot, emptyWrapper, placeholder);
640
+ const entry = { row, key, threadId, rawHost, title, slot, host, button, original, hovered: row.matches(':hover') };
641
+
642
+ entry.onEnter = () => { entry.hovered = true; paintVisibility(entry); };
643
+ entry.onLeave = () => { entry.hovered = false; paintVisibility(entry); };
644
+ row.addEventListener('pointerenter', entry.onEnter);
645
+ row.addEventListener('pointerleave', entry.onLeave);
646
+
647
+ mounted.set(row, entry);
648
+ paint(entry);
649
+
650
+ button.onclick = event => {
651
+ event.stopPropagation();
652
+ if (isPanelBusy()) return;
653
+ if (isPanelEntry(entry)) closePanel(true);
654
+ else { closePanel(); openPanel(entry); }
655
+ };
656
+ }
657
+ },
658
+
659
+ async locate({ entry, source, analysisMessage }) {
660
+ if (!source?.turnId || !source?.itemId) {
661
+ analysisMessage.status = 'not_found';
662
+ analysisMessage.textContent = getUiText('locateNoSource', '此记录没有可定位的消息');
663
+ return;
664
+ }
665
+
666
+ const row = entry.row;
667
+ const targetThreadId = source.threadId ? (source.threadId.startsWith('local:') ? source.threadId : 'local:' + source.threadId) : entry.threadId;
668
+
669
+ // 1. 若当前会话未激活,先自动切换打开来源会话
670
+ if (row.getAttribute('data-app-action-sidebar-thread-selected') !== 'true') {
671
+ const trigger = row.querySelector('[data-thread-title-trigger]') || row.querySelector('button') || row;
672
+ trigger.click();
673
+ }
674
+
675
+ const deadline = Date.now() + 4500;
676
+ let isCurrent = false;
677
+ while (Date.now() < deadline) {
678
+ isCurrent = row.getAttribute('data-app-action-sidebar-thread-selected') === 'true' ||
679
+ [...document.querySelectorAll('[data-app-action-sidebar-thread-row]')].some(r =>
680
+ r.getAttribute('data-app-action-sidebar-thread-selected') === 'true' &&
681
+ r.getAttribute('data-app-action-sidebar-thread-id') === targetThreadId);
682
+ if (isCurrent) break;
683
+ await new Promise(resolve => setTimeout(resolve, 80));
684
+ }
685
+ if (!isCurrent) {
686
+ analysisMessage.status = 'not_found';
687
+ analysisMessage.textContent = getUiText('locateOpenFailed', '未能打开来源会话,请重试');
688
+ return;
689
+ }
690
+
691
+ const unitKey = `${source.turnId}:${source.itemId}`;
692
+ const escapedKey = CSS.escape(unitKey);
693
+ const escapedTurn = CSS.escape(source.turnId);
694
+
695
+ // 2. 策略 1:检查目标节点是否已在当前 DOM 中挂载
696
+ let targetNode = document.querySelector(`[data-content-search-unit-key="${escapedKey}"]`) ||
697
+ document.querySelector(`[data-turn-key="history-content:turn:${escapedTurn}"]`);
698
+
699
+ // 策略 2:若当前不在 DOM 中(虚拟列表卸载),利用 Codex 官方右侧常驻 Navigation Rail 原生直达
700
+ if (!targetNode) {
701
+ const navBtn = document.querySelector(`[data-thread-user-message-navigation-item-id="${escapedKey}"]`) ||
702
+ document.querySelector(`[data-thread-user-message-navigation-item-id^="${escapedTurn}:"]`) ||
703
+ document.querySelector(`[data-thread-user-message-navigation-item-id="${escapedTurn}"]`);
704
+ if (navBtn) {
705
+ analysisMessage.textContent = getUiText('locatingMessage', '正在定位消息…');
706
+ navBtn.click();
707
+ // 等待官方虚拟列表挂载目标回合
708
+ const deadline = Date.now() + 1500;
709
+ while (Date.now() < deadline) {
710
+ targetNode = document.querySelector(`[data-content-search-unit-key="${escapedKey}"]`) ||
711
+ document.querySelector(`[data-turn-key="history-content:turn:${escapedTurn}"]`);
712
+ if (targetNode) break;
713
+ await new Promise(r => setTimeout(r, 60));
714
+ }
715
+ }
716
+ }
717
+
718
+ // 策略 3:如果包含 locator 文本,尝试在已渲染的气泡或全文中进行文本比对兜底
719
+ if (!targetNode && source.locator) {
720
+ const bubbles = [...document.querySelectorAll('[data-content-search-unit-key], [data-user-message-bubble]')];
721
+ const quote = source.locator.replace(/\s+/g, ' ').trim();
722
+ const matches = [...new Set(bubbles.filter(b => (b.textContent || '').replace(/\s+/g, ' ').includes(quote)).map(b => b.closest('[data-content-search-unit-key]') || b))];
723
+ const match = matches.length === 1 ? matches[0] : null;
724
+ if (match) targetNode = match.closest('[data-content-search-unit-key]') || match.closest('[data-turn-key]') || match;
725
+ }
726
+
727
+ // 3. 执行平滑视口居中与呼吸发光动画
728
+ if (targetNode) {
729
+ targetNode.scrollIntoView({ block: 'center', behavior: 'smooth' });
730
+
731
+ const bubble = targetNode.querySelector('[data-user-message-bubble]') || targetNode;
732
+ try {
733
+ bubble.animate?.(
734
+ [
735
+ { backgroundColor: 'color-mix(in srgb, var(--color-text, #fff) 22%, transparent)' },
736
+ { backgroundColor: 'color-mix(in srgb, var(--color-text, #fff) 22%, transparent)', offset: 0.35 },
737
+ { backgroundColor: 'transparent' }
738
+ ],
739
+ { duration: 2000, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' }
740
+ );
741
+ } catch { /* ignore */ }
742
+
743
+ const previousOutline = bubble.style.outline;
744
+ const previousBoxShadow = bubble.style.boxShadow;
745
+ bubble.style.outline = '2px solid #548eea';
746
+ bubble.style.boxShadow = '0 0 14px rgba(84, 142, 234, 0.5)';
747
+ setTimeout(() => {
748
+ if (bubble.style.outline === '2px solid rgb(84, 142, 234)') {
749
+ bubble.style.outline = previousOutline;
750
+ bubble.style.boxShadow = previousBoxShadow;
751
+ }
752
+ }, 3000);
753
+
754
+ analysisMessage.status = 'located';
755
+ analysisMessage.textContent = getUiText('locatedMessage', '已定位来源');
756
+ } else {
757
+ analysisMessage.status = 'not_found';
758
+ analysisMessage.textContent = getUiText('locateNotFound', '未找到原始消息,可能已被清理');
759
+ }
760
+ }
761
+ };
762
+
763
+ window.__sessionStatusHarness = codexHarness;
764
+ if (typeof module !== 'undefined' && module.exports) {
765
+ module.exports = { codexHarness };
766
+ }
767
+ })();
768
+
769
+ /* Manual session marks. Loaded in a dedicated CDP isolated world. */
770
+ function installCodexSessionStatus(version, restored, embedded) {
771
+ if (window.__codexSessionStatus && !embedded?.independent) return;
772
+ const harness = embedded?.independent ? null : window.__sessionStatusHarness || null;
773
+ let localCards = null;
774
+ const send = payload => {
775
+ if (embedded) embedded.send(payload);
776
+ else if (harness?.send) harness.send(payload);
777
+ else window.__codexSessionStatusSend(payload);
778
+ };
779
+ const presentation = window.__agentThingsPresentation;
780
+ let activeLang = embedded?.lang || embedded?.snapshot?.lang || window.__agentThingsConnection?.lang || window.__agentThingsLang || presentation?.lang || 'zh';
781
+ let ui = presentation?.forLang ? presentation.forLang(activeLang) : null;
782
+ let strings = ui?.strings || presentation?.strings || {};
783
+ let labels = ui?.labels || presentation?.labels || {
784
+ unstarted: '尚未开始', unfinished: '有遗留事项', completed: '全部完成', pushed: '全部完成并已推送',
785
+ };
786
+ let taskLabels = ui?.taskLabels || presentation?.taskLabels || {
787
+ todo: '待开始', in_progress: '进行中', blocked: '受阻', needs_verification: '待验收', done: '已完成',
788
+ };
789
+ const S = (key, vars) => (ui?.t ? ui.t(key, vars) : (strings[key] || key));
790
+ const setLang = nextLang => {
791
+ const resolved = nextLang === 'en' ? 'en' : nextLang === 'zh' ? 'zh' : activeLang;
792
+ if (!presentation?.forLang || (resolved === activeLang && ui)) return false;
793
+ activeLang = resolved;
794
+ ui = presentation.forLang(activeLang);
795
+ strings = ui.strings;
796
+ labels = ui.labels;
797
+ taskLabels = ui.taskLabels;
798
+ return true;
799
+ };
800
+ const colors = presentation?.colors || { unstarted: '#9098a2', unfinished: '#c89b38', completed: '#548eea', pushed: '#a17be3' };
801
+ let snapshot = { revision: 0, records: {} };
802
+ const mounted = new Map();
803
+ const pending = new Map();
804
+ const panelStates = new Map(restored?.panelStates || []);
805
+ let panel = null;
806
+ let serial = 0;
807
+ const requestPrefix = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
808
+ let frame = 0;
809
+ let destroyed = false;
810
+ const startup = { installedAt: Date.now(), sidebarReadyAt: null, badgesReadyAt: null };
811
+ function measureStartup() {
812
+ if (startup.badgesReadyAt !== null) return;
813
+ const rows = harness?.startupRows ? harness.startupRows().filter(visible)
814
+ : [...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));
815
+ if (!rows.length) return;
816
+ startup.sidebarReadyAt ??= Date.now();
817
+ if (rows.every(row => row.querySelector('[data-codex-session-status]'))) startup.badgesReadyAt = Date.now();
818
+ }
819
+
820
+ function rememberPanel(target) {
821
+ const active = target.root.shadowRoot.activeElement;
822
+ const state = { key: target.entry.key, mode: target.mode, dirty: target.dirty, revision: target.revision,
823
+ note: target.note.value, progress: target.progress.value, draft: { ...target.draft },
824
+ remainingExpanded: target.remainingExpanded, scrollTop: target.body.scrollTop,
825
+ noteScrollTop: target.note.scrollTop, selectionStart: target.note.selectionStart, selectionEnd: target.note.selectionEnd,
826
+ focus: active === target.note ? 'note' : active === target.progress ? 'progress' : null,
827
+ error: target.error.textContent, conflict: target.conflict };
828
+ panelStates.set(target.entry.key, state);
829
+ try { sessionStorage.setItem(`codex-session-status-panel:v1:${target.entry.key}`, JSON.stringify(state)); } catch { /* Keep the in-memory copy when storage is unavailable. */ }
830
+ return state;
831
+ }
832
+
833
+ function rememberedPanel(key) {
834
+ if (panelStates.has(key)) return panelStates.get(key);
835
+ try {
836
+ const state = JSON.parse(sessionStorage.getItem(`codex-session-status-panel:v1:${key}`));
837
+ if (state && ['overview', 'edit', 'history'].includes(state.mode)) { panelStates.set(key, state); return state; }
838
+ } catch { /* Start from the current saved record if a browser cache cannot be read. */ }
839
+ return null;
840
+ }
841
+
842
+ function restorePanel(target, state) {
843
+ target.remainingExpanded = state.remainingExpanded;
844
+ if (state.dirty) {
845
+ target.dirty = true; target.revision = state.revision;
846
+ target.draft = state.draft || { state: recordFor(state.key)?.state || 'unfinished',
847
+ progress: state.progress === '' ? null : Number(state.progress), note: state.note || '' };
848
+ target.note.value = state.note; updateDraft(target, target.draft); target.progress.value = state.progress;
849
+ }
850
+ target.restoreScroll = state.scrollTop || 0;
851
+ target.setView(state.mode || (state.dirty ? 'edit' : 'overview'));
852
+ target.error.textContent = state.error || '';
853
+ target.conflict = Boolean(state.dirty && state.conflict);
854
+ target.resolveConflict.hidden = !target.conflict;
855
+ if (target.mode === 'edit') {
856
+ if (state.focus === 'note') {
857
+ target.note.focus({ preventScroll: true });
858
+ target.note.setSelectionRange(state.selectionStart ?? target.note.value.length, state.selectionEnd ?? target.note.value.length);
859
+ } else if (state.focus === 'progress') target.progress.focus({ preventScroll: true });
860
+ target.note.scrollTop = state.noteScrollTop || 0;
861
+ }
862
+ }
863
+
864
+ function panelEvent(action, entry) {
865
+ try { send(JSON.stringify({ type: 'panel-event', action,
866
+ requestId: `${requestPrefix}:${++serial}`, key: entry.key })); } catch { /* Diagnostic only. */ }
867
+ }
868
+
869
+ function element(tag, text, parent, className) {
870
+ const node = document.createElement(tag);
871
+ if (text != null) node.textContent = text;
872
+ if (className) node.className = className;
873
+ parent?.append(node);
874
+ return node;
875
+ }
876
+
877
+ function recordFor(key) {
878
+ const record = snapshot.records[key];
879
+ return record?.state ? record : null;
880
+ }
881
+
882
+ function summary(key) {
883
+ const record = recordFor(key);
884
+ if (!record) return S('badgeNotOrganized');
885
+ return `${labels[record.state]}${record.progress === null ? S('badgeProgressUnrecordedSuffix') : ` · ${record.progress}%`}`;
886
+ }
887
+
888
+ function makeRing(button, record, pie = false, loading = false) {
889
+ button.replaceChildren();
890
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
891
+ svg.setAttribute('viewBox', '0 0 24 24');
892
+ svg.setAttribute('width', '24'); svg.setAttribute('height', '24');
893
+ svg.setAttribute('aria-hidden', 'true');
894
+ if (loading) {
895
+ svg.setAttribute('class', 'loading');
896
+ const circle = document.createElementNS(svg.namespaceURI, 'circle');
897
+ 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);
898
+ svg.append(circle); button.append(svg); return;
899
+ }
900
+ const color = record ? colors[record.state] : '#858991';
901
+ for (const progress of pie ? [null] : [null, record?.progress]) {
902
+ if (progress === undefined || progress === null && svg.childElementCount) continue;
903
+ const circle = document.createElementNS(svg.namespaceURI, 'circle');
904
+ for (const [name, value] of Object.entries({ cx: 12, cy: 12, r: 10, fill: 'none', stroke: color, 'stroke-width': 1.6 })) {
905
+ circle.setAttribute(name, value);
906
+ }
907
+ if (progress === null) circle.setAttribute('opacity', pie ? '1' : record?.progress != null ? '.25' : '.85');
908
+ else {
909
+ circle.setAttribute('stroke-dasharray', `${62.832 * progress / 100} 62.832`);
910
+ circle.setAttribute('transform', 'rotate(-90 12 12)');
911
+ circle.setAttribute('stroke-linecap', 'round');
912
+ }
913
+ svg.append(circle);
914
+ }
915
+ if (pie && record?.progress > 0) {
916
+ const sector = document.createElementNS(svg.namespaceURI, 'path');
917
+ const angle = record.progress / 100 * Math.PI * 2;
918
+ const x = 12 + 7.4 * Math.sin(angle);
919
+ const y = 12 - 7.4 * Math.cos(angle);
920
+ sector.setAttribute('d', record.progress === 100
921
+ ? 'M12 4.6a7.4 7.4 0 1 1 0 14.8a7.4 7.4 0 1 1 0-14.8'
922
+ : `M12 12L12 4.6A7.4 7.4 0 ${record.progress > 50 ? 1 : 0} 1 ${x} ${y}Z`);
923
+ sector.setAttribute('fill', color); sector.setAttribute('class', 'progress-pie');
924
+ svg.append(sector);
925
+ }
926
+ if (pie || record) {
927
+ const text = document.createElementNS(svg.namespaceURI, 'text');
928
+ text.setAttribute('x', '12'); text.setAttribute('y', '12.4');
929
+ text.setAttribute('text-anchor', 'middle'); text.setAttribute('dominant-baseline', 'middle');
930
+ text.setAttribute('fill', color);
931
+ text.setAttribute('style', `font:600 ${pie ? 6.4 : 8}px -apple-system,BlinkMacSystemFont,sans-serif;font-variant-numeric:tabular-nums`);
932
+ text.textContent = record?.progress == null ? '—' : pie ? `${record.progress}%` : String(record.progress);
933
+ if (record?.progress == null) text.setAttribute('class', 'progress-unknown');
934
+ svg.append(text);
935
+ }
936
+ button.append(svg);
937
+ }
938
+
939
+ function paintVisibility(entry) {
940
+ const selected = harness?.isRowSelected ? harness.isRowSelected(entry.row) : entry.row.getAttribute('data-app-action-sidebar-thread-selected') === 'true';
941
+ entry.host.toggleAttribute('data-visible', Boolean(recordFor(entry.key) || snapshot.analyzingKeys?.includes(entry.key) || entry.hovered || selected));
942
+ }
943
+
944
+ function paint(entry) {
945
+ const record = recordFor(entry.key);
946
+ const loading = snapshot.analyzingKeys?.includes(entry.key) || false;
947
+ const ringKey = JSON.stringify([record?.state, record?.progress, loading]);
948
+ if (entry.ringKey !== ringKey) { makeRing(entry.button, record, false, loading); entry.ringKey = ringKey; }
949
+ paintVisibility(entry);
950
+ entry.button.setAttribute('aria-busy', String(loading));
951
+ const description = S('ringAriaPattern', { title: entry.title, summary: loading ? S('ringUpdating') : summary(entry.key) });
952
+ entry.button.setAttribute('aria-label', description);
953
+ entry.button.title = description;
954
+ }
955
+
956
+ function unmount(entry) {
957
+ harness?.unmount?.(entry);
958
+ entry.row.removeEventListener('pointerenter', entry.onEnter); entry.row.removeEventListener('pointerleave', entry.onLeave);
959
+ entry.host.remove();
960
+ for (const [name, previous] of Object.entries(entry.original)) {
961
+ if (previous.value) entry.slot.style.setProperty(name, previous.value, previous.priority);
962
+ else entry.slot.style.removeProperty(name);
963
+ }
964
+ if (entry.slot.classList.contains('status-slot-injected')) entry.slot.remove();
965
+ mounted.delete(entry.row);
966
+ }
967
+
968
+ function attachHost(slot, emptyWrapper, placeholder) {
969
+ const original = Object.fromEntries(['width', 'min-width', 'flex-basis'].map(name => [name, {
970
+ value: slot.style.getPropertyValue(name), priority: slot.style.getPropertyPriority(name)
971
+ }]));
972
+ for (const name of Object.keys(original)) slot.style.setProperty(name, '24px');
973
+ const target = emptyWrapper ? placeholder : slot;
974
+ for (const existing of target.querySelectorAll('span[data-codex-session-status]')) {
975
+ existing.remove();
976
+ }
977
+ const host = element('span', null, target);
978
+ host.setAttribute('data-codex-session-status', '');
979
+ host.style.cssText = 'display:flex;width:24px;height:28px;flex:none;align-items:center;justify-content:center';
980
+ const shadow = host.attachShadow({ mode: 'open' });
981
+ 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);
982
+ const button = element('button', null, shadow);
983
+ button.type = 'button'; button.setAttribute('aria-haspopup', 'dialog'); button.setAttribute('aria-expanded', 'false');
984
+ return { host, button, original };
985
+ }
986
+
987
+ function reconcile() {
988
+ frame = 0;
989
+ if (destroyed) return;
990
+ measureStartup();
991
+ if (harness?.reconcile) {
992
+ harness.reconcile({ mounted, unmount, attachHost, paint, paintVisibility, openPanel, closePanel, isPanelBusy: () => panel?.busy, isPanelEntry: e => panel?.entry === e });
993
+ measureStartup();
994
+ if (panel && (!panel.entry.host.isConnected || !visible(panel.entry.host))) closePanel(false);
995
+ else positionPanel();
996
+ return;
997
+ }
998
+ for (const entry of mounted.values()) {
999
+ if (!entry.row.isConnected || !entry.host.isConnected || !entry.row.closest('[data-app-action-sidebar-project-list-id]') ||
1000
+ !['local', 'remote'].includes(entry.row.getAttribute('data-app-action-sidebar-thread-kind')) ||
1001
+ entry.row.getAttribute('data-app-action-sidebar-thread-id') !== entry.threadId ||
1002
+ entry.row.getAttribute('data-app-action-sidebar-thread-host-id') !== entry.rawHost) unmount(entry);
1003
+ }
1004
+ const rows = document.querySelectorAll('[data-app-action-sidebar-project-list-id] [data-app-action-sidebar-thread-row]');
1005
+ for (const row of rows) {
1006
+ const kind = row.getAttribute('data-app-action-sidebar-thread-kind');
1007
+ if (kind !== 'local' && kind !== 'remote') continue;
1008
+ const threadId = row.getAttribute('data-app-action-sidebar-thread-id');
1009
+ if (!threadId) continue;
1010
+ const titleNode = row.querySelector('[data-thread-title]');
1011
+ const title = row.getAttribute('data-app-action-sidebar-thread-title') || titleNode?.textContent || S('sessionFallbackTitle');
1012
+ const existing = mounted.get(row);
1013
+ if (existing) {
1014
+ if (existing.title !== title) { existing.title = title; paint(existing); }
1015
+ paintVisibility(existing);
1016
+ continue;
1017
+ }
1018
+ // Target the existing reserved leading slot; leave occupied native icons intact.
1019
+ const trigger = titleNode?.closest('[data-thread-title-trigger]');
1020
+ const slot = trigger?.previousElementSibling;
1021
+ if (!slot || !slot.classList.contains('w-4')) continue;
1022
+ // Native rows keep an empty relative wrapper inside the leading slot.
1023
+ const placeholder = slot.firstElementChild;
1024
+ const emptyWrapper = slot.childElementCount === 1 && placeholder.tagName === 'DIV' &&
1025
+ placeholder.childElementCount === 0 && !placeholder.textContent.trim();
1026
+ if (slot.childElementCount !== 0 && !emptyWrapper) continue;
1027
+ const rawHost = row.getAttribute('data-app-action-sidebar-thread-host-id');
1028
+ const key = JSON.stringify([rawHost || (kind === 'remote' ? 'cloud' : 'local'), threadId]);
1029
+ const { host, button, original } = attachHost(slot, emptyWrapper, placeholder);
1030
+ const entry = { row, key, threadId, rawHost, title, slot, host, button, original, hovered: row.matches(':hover') };
1031
+ entry.onEnter = () => { entry.hovered = true; paintVisibility(entry); };
1032
+ entry.onLeave = () => { entry.hovered = false; paintVisibility(entry); };
1033
+ row.addEventListener('pointerenter', entry.onEnter); row.addEventListener('pointerleave', entry.onLeave);
1034
+ for (const type of ['pointerdown', 'dblclick']) host.addEventListener(type, e => e.stopPropagation());
1035
+ button.addEventListener('click', async e => {
1036
+ e.preventDefault(); e.stopPropagation();
1037
+ if (panel?.busy) return;
1038
+ if (panel?.entry === entry) closePanel();
1039
+ else { closePanel(); openPanel(entry); }
1040
+ });
1041
+ mounted.set(row, entry); paint(entry);
1042
+ }
1043
+ if (panel && (!panel.entry.host.isConnected || !visible(panel.entry.host))) closePanel(false);
1044
+ else positionPanel();
1045
+ }
1046
+
1047
+ function schedule() {
1048
+ if (!frame && !destroyed) frame = requestAnimationFrame(reconcile);
1049
+ }
1050
+
1051
+ function visible(node) {
1052
+ const r = node.getBoundingClientRect();
1053
+ return r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight;
1054
+ }
1055
+
1056
+ function positionPanel() {
1057
+ if (!panel) return;
1058
+ if (embedded) {
1059
+ panel.root.setAttribute('data-color-mode', embedded.theme || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'));
1060
+ return;
1061
+ }
1062
+ // Foreground colors change when the host window becomes inactive.
1063
+ // Read the painted page background, whose luminance represents its theme.
1064
+ let mode = null;
1065
+ for (let node = panel.entry.row; node; node = node.parentElement) {
1066
+ const rgba = getComputedStyle(node).backgroundColor.match(/[\d.]+/g)?.map(Number);
1067
+ if (!rgba || (rgba[3] ?? 1) < .95) continue;
1068
+ mode = rgba[0] * .2126 + rgba[1] * .7152 + rgba[2] * .0722 < 150 ? 'dark' : 'light';
1069
+ break;
1070
+ }
1071
+ mode ||= panel.root.getAttribute('data-color-mode') || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
1072
+ if (panel.root.getAttribute('data-color-mode') !== mode) panel.root.setAttribute('data-color-mode', mode);
1073
+ const anchor = panel.entry.host.getBoundingClientRect();
1074
+ const rect = panel.shell.getBoundingClientRect();
1075
+ const left = Math.max(8, Math.min(anchor.right + 10, innerWidth - rect.width - 8));
1076
+ const top = Math.max(8, Math.min(anchor.top - 12, innerHeight - rect.height - 8));
1077
+ panel.shell.style.left = `${left}px`; panel.shell.style.top = `${top}px`;
1078
+ }
1079
+
1080
+ function updateDraft(target, patch) {
1081
+ target.draft = presentation ? presentation.draftTransition({ draft: target.draft, baseRevision: target.revision }, { type: 'patch', patch }).draft : { ...target.draft, ...patch };
1082
+ target.dirty = true;
1083
+ const draft = target.draft;
1084
+ target.progress.value = draft.progress ?? '';
1085
+ target.slider.value = draft.progress ?? 0;
1086
+ target.range.style.setProperty('--fill', `${draft.progress ?? 0}%`);
1087
+ target.range.style.setProperty('--mark', colors[draft.state] || colors.unfinished);
1088
+ for (const [state, button] of target.choices) button.setAttribute('aria-pressed', String(draft.state === state));
1089
+ rememberPanel(target);
1090
+ }
1091
+
1092
+ function refreshPanel() {
1093
+ if (!panel) return;
1094
+ const target = panel, record = recordFor(target.entry.key);
1095
+ target.choices.get('pushed').hidden = target.projectGit?.hasRemote !== true;
1096
+ target.git.textContent = target.projectGit?.status === 'unknown' ? S('gitCheckUnavailable') : '';
1097
+ if (!target.busy && !target.dirty) {
1098
+ target.revision = snapshot.records[target.entry.key]?.revision ?? 0;
1099
+ target.draft = presentation ? presentation.draftTransition({}, { type: 'begin', record, revision: target.revision }).draft : { state: record?.state || 'unfinished', progress: record?.progress ?? null, note: record?.note || '' };
1100
+ target.note.value = target.draft.note;
1101
+ target.progress.value = target.draft.progress ?? '';
1102
+ target.slider.value = target.draft.progress ?? 0;
1103
+ target.range.style.setProperty('--fill', `${target.draft.progress ?? 0}%`);
1104
+ target.range.style.setProperty('--mark', colors[target.draft.state]);
1105
+ for (const [state, button] of target.choices) button.setAttribute('aria-pressed', String(target.draft.state === state));
1106
+ }
1107
+ makeRing(target.titleProgress, record, true);
1108
+ target.heading.setAttribute('aria-label', `${target.entry.title}, ${summary(target.entry.key)}`);
1109
+ target.statusLabel.textContent = record ? labels[record.state] : S('statusUnrecorded');
1110
+ target.statusDot.style.borderColor = record ? colors[record.state] : colors.unstarted;
1111
+ 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' })) : '';
1112
+ target.scoreNumber.textContent = record?.progress ?? '—';
1113
+ target.scoreUnit.hidden = record?.progress == null;
1114
+ target.meter.style.setProperty('--fill', `${record?.progress ?? 0}%`);
1115
+ target.meter.style.setProperty('--mark', record ? colors[record.state] : colors.unstarted);
1116
+ target.sourceLabel.textContent = record ? (record.source === 'analysis' ? S('sourceAuto') : S('sourceManual')) : '';
1117
+ const summaryText = record?.note || '';
1118
+ if (target.overviewSummary.textContent !== summaryText) {
1119
+ target.overviewSummary.textContent = summaryText;
1120
+ target.setSummaryExpanded(false);
1121
+ }
1122
+ target.summaryBlock.hidden = !summaryText;
1123
+ target.noteOpen.textContent = record?.note ? S('editLabel') : S('addLabel');
1124
+ 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);
1125
+ target.renderHistory?.();
1126
+ positionPanel();
1127
+ target.scheduleMarquees?.();
1128
+ if (target.restoreScroll != null && (target.mode === 'edit' || target.analysisState)) {
1129
+ target.body.scrollTop = target.restoreScroll; target.restoreScroll = null;
1130
+ }
1131
+ }
1132
+
1133
+ async function save(patch = {}, reset = false, target = panel) {
1134
+ if (!target || target.busy) return false;
1135
+ const raw = target.progress.value.trim();
1136
+ const progress = raw === '' ? null : Number(raw);
1137
+ if (!reset && progress !== null && (!Number.isInteger(progress) || progress < 0 || progress > 100)) {
1138
+ target.error.textContent = S('invalidProgressError'); return false;
1139
+ }
1140
+ const record = reset ? null : { ...target.draft, progress, note: target.note.value, ...patch };
1141
+ target.busy = true; target.error.textContent = '';
1142
+ for (const control of target.controls) control.disabled = true;
1143
+ try {
1144
+ const state = await target.request('update', 7000, { expectedRevision: target.revision, record });
1145
+ target.dirty = false;
1146
+ target.conflict = false; target.resolveConflict.hidden = true;
1147
+ rememberPanel(target);
1148
+ // 保存成功即补读一次,并吸收保存期间到达的待刷新,避免 finally 再读一次。
1149
+ target.syncVersion = panelVersion(target.entry.key); target.syncPending = false;
1150
+ if (embedded && state) target.showHistory(state); else target.pollHistory?.();
1151
+ return true;
1152
+ } catch (error) {
1153
+ target.error.textContent = error.message;
1154
+ if ((error.code === 'REVISION_CONFLICT' || (!error.code && (error.message === '此会话已在其他窗口更新,请重新确认' || error.message === S('conflictDetectedFeedback')))) && target.dirty && !reset) {
1155
+ target.conflict = true;
1156
+ target.resolveConflict.hidden = false;
1157
+ rememberPanel(target);
1158
+ }
1159
+ return false;
1160
+ } finally {
1161
+ target.busy = false;
1162
+ for (const control of target.controls) control.disabled = false;
1163
+ if (target.syncPending && panel === target) syncPanel(target);
1164
+ if (panel === target) { target.analyze.disabled = target.analyzing; refreshPanel(); }
1165
+ }
1166
+ }
1167
+
1168
+ async function rebaseDraft(target) {
1169
+ if (target.busy || !target.conflict) return;
1170
+ target.busy = true;
1171
+ for (const control of target.controls) control.disabled = true;
1172
+ try {
1173
+ const state = await target.request('analysis-state', 7000);
1174
+ target.revision = snapshot.records[target.entry.key]?.revision ?? 0;
1175
+ target.conflict = false; target.resolveConflict.hidden = true;
1176
+ target.error.textContent = S('conflictReloadedFeedback');
1177
+ target.showHistory?.(state);
1178
+ rememberPanel(target);
1179
+ } catch (error) {
1180
+ target.error.textContent = error.message;
1181
+ } finally {
1182
+ target.busy = false;
1183
+ for (const control of target.controls) control.disabled = false;
1184
+ if (panel === target) {
1185
+ if (target.syncPending) syncPanel(target);
1186
+ refreshPanel();
1187
+ }
1188
+ }
1189
+ }
1190
+
1191
+ function cancelRead(requestId, request) {
1192
+ if (!['project-git', 'analysis-state', 'app-update-info'].includes(request.type) || !(embedded || harness?.supportsRequestCancellation)) return;
1193
+ try { send(JSON.stringify({ type: 'cancel-request', requestId: `${requestPrefix}:${++serial}`, cancelRequestId: requestId })); } catch { /* Local cleanup still runs if the host has disconnected. */ }
1194
+ }
1195
+ function closePanel(restoreFocus = true) {
1196
+ if (!panel || panel.busy) return;
1197
+ for (const [id, request] of pending) {
1198
+ if (request.key === panel.entry.key && ['project-git', 'analysis-state', 'app-update-info'].includes(request.type) && (embedded || harness?.supportsRequestCancellation)) {
1199
+ cancelRead(id, request); clearTimeout(request.timer); pending.delete(id);
1200
+ request.reject(Object.assign(new Error(S('cardRequestCancelled')), { code: 'REQUEST_CANCELLED' }));
1201
+ }
1202
+ }
1203
+ rememberPanel(panel);
1204
+ panelEvent('close', panel.entry);
1205
+ const target = panel; panel = null;
1206
+ clearTimeout(target.pollTimer); cancelAnimationFrame(target.marqueeFrame);
1207
+ clearTimeout(target.updateTimer);
1208
+ target.resizeObserver?.disconnect();
1209
+ target.root.remove(); target.entry.button.setAttribute('aria-expanded', 'false');
1210
+ if (restoreFocus && target.entry.host.isConnected) target.entry.button.focus();
1211
+ }
1212
+
1213
+ function openPanel(entry) {
1214
+ if (panel) return;
1215
+ const root = element('div', null, embedded?.container || document.body);
1216
+ root.setAttribute('data-codex-session-status-panel', '');
1217
+ if (!embedded) root.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483646';
1218
+ const shadow = root.attachShadow({ mode: 'open' });
1219
+ element('style', `
1220
+ :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}
1221
+ *{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}
1222
+ .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}
1223
+ .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}
1224
+ 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}
1225
+ .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}
1226
+ .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)}
1227
+ .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}
1228
+ .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}
1229
+ .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}
1230
+ .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}
1231
+ .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}
1232
+ @media(prefers-reduced-motion:reduce){.task-row .task-title.overflowing .task-track{transform:none;transition:none}.task-title{overflow:auto}}
1233
+ @media(hover:none){.task-source{opacity:1;pointer-events:auto;transform:none}}
1234
+ .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)}
1235
+ .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}
1236
+ .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}
1237
+ .shell textarea:focus-visible{outline:none}
1238
+ .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)}
1239
+ :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}
1240
+ :host([data-color-mode=light]) .shell{--panel-bg:#fff;border-color:#dfe4ea;box-shadow:0 14px 45px #26344520}
1241
+ :host([data-color-mode=light]) .shell:hover{--panel-bg:#f5f6f7}
1242
+ :host([data-color-mode=light]) .range{--range-fill:color-mix(in srgb,var(--mark) 85%,#000)}
1243
+ :host([data-color-mode=light]) .meter::after{background:color-mix(in srgb,var(--mark) 85%,#000)}
1244
+ `, shadow);
1245
+ 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);
1246
+ const shell = element('div', null, shadow, 'shell');
1247
+ shell.setAttribute('role', embedded ? 'region' : 'dialog'); shell.setAttribute('aria-label', S('panelAriaPattern', { title: entry.title }));
1248
+ const close = embedded ? null : element('button', '×', shell, 'close'); close?.setAttribute('aria-label', S('close'));
1249
+ // 宿主支持时,在关闭按钮左侧提供「在侧栏打开」:把卡片交给宿主的常驻侧栏面板。
1250
+ const openPane = harness?.openPane ? element('button', null, shell, 'open-pane') : null;
1251
+ let openPaneTip = null;
1252
+ if (openPane) {
1253
+ shell.classList.add('has-open-pane'); openPane.setAttribute('aria-label', S('openInSidebar'));
1254
+ openPaneTip = element('span', S('openInSidebar'), openPane, 'open-pane-tip');
1255
+ openPaneTip.setAttribute('role', 'tooltip');
1256
+ }
1257
+ const heading = element('div', null, shell, 'title-heading'); heading.tabIndex = 0;
1258
+ const titleProgress = element('span', null, heading, 'title-progress');
1259
+ element('h2', entry.title, heading, 'title');
1260
+ const body = element('div', null, shell, 'panel-body');
1261
+ const overview = element('div', null, body, 'view overview');
1262
+ const statusLine = element('div', null, overview, 'status-line');
1263
+ const statusBlock = element('div', null, statusLine, 'status-block');
1264
+ const statusName = element('div', null, statusBlock, 'status-name');
1265
+ const statusDot = element('span', null, statusName, 'state-dot');
1266
+ const statusLabel = element('span', null, statusName);
1267
+ const timestamp = element('div', null, statusBlock, 'timestamp');
1268
+ const score = element('div', null, statusLine, 'score');
1269
+ const scoreNumber = element('span', null, score, 'score-number');
1270
+ const scoreUnit = element('span', '%', score, 'score-unit');
1271
+ const meter = element('div', null, overview, 'meter');
1272
+ const totalsRow = element('div', null, overview, 'totals-row');
1273
+ const totals = element('span', S('totalsEmpty'), totalsRow, 'totals');
1274
+ const sourceLabel = element('span', null, totalsRow, 'source-label');
1275
+ const summaryBlock = element('div', null, overview, 'summary-block'); summaryBlock.tabIndex = 0;
1276
+ const overviewSummary = element('div', null, summaryBlock, 'overview-summary');
1277
+ const summaryExpand = element('button', S('expandAll'), summaryBlock, 'summary-expand');
1278
+ summaryExpand.hidden = true; summaryExpand.setAttribute('aria-expanded', 'false');
1279
+ const actions = element('div', null, overview, 'actions');
1280
+ const analyze = element('button', S('btnUpdate'), actions, 'primary analyze');
1281
+ const editOpen = element('button', S('btnAdjust'), actions, 'text-button edit-open');
1282
+ const clear = element('button', S('btnClear'), actions, 'clear');
1283
+ clear.setAttribute('aria-label', S('btnClear'));
1284
+ const clearTip = element('span', S('clearTooltip'), clear, 'clear-tooltip');
1285
+ clearTip.setAttribute('role', 'tooltip');
1286
+ const sectionHead = element('div', null, overview, 'section-head');
1287
+ const tasksHeading = element('h3', S('remainingHeadingPattern', { count: 0 }), sectionHead);
1288
+ const remainingToggle = element('button', null, sectionHead, 'remaining-toggle row-detail');
1289
+ remainingToggle.hidden = true; remainingToggle.setAttribute('aria-expanded', 'false');
1290
+ const currentTasks = element('div', null, overview, 'current-tasks');
1291
+ const bottom = element('div', null, overview, 'overview-bottom');
1292
+ const historyOpen = element('button', null, bottom, 'quiet-row history-open'); const historyRowTitle = element('span', S('completedHeading'), historyOpen);
1293
+ const historyCount = element('span', S('countArrowPattern', { count: 0 }), historyOpen, 'row-detail');
1294
+ const noteRow = element('button', null, bottom, 'quiet-row note-open'); const noteRowTitle = element('span', S('notesLabel'), noteRow);
1295
+ const noteOpen = element('span', S('addLabel'), noteRow);
1296
+ const timelineOpen = embedded ? element('button', S('timelineLink'), bottom, 'quiet-row timeline-open') : null;
1297
+ const appUpdate = element('div', null, bottom, 'app-update'); appUpdate.hidden = true;
1298
+ const appUpdateRow = element('div', null, appUpdate, 'app-update-row');
1299
+ const appUpdateLabel = element('span', null, appUpdateRow, 'app-update-label'); appUpdateLabel.setAttribute('role', 'status');
1300
+ const appUpdateButton = element('button', S('upgradeBtn'), appUpdateRow, 'primary app-update-button');
1301
+ const appUpdateDetail = element('div', null, appUpdate, 'app-update-detail'); appUpdateDetail.hidden = true;
1302
+ const edit = element('div', null, body, 'view edit-view'); edit.hidden = true;
1303
+ const editHeading = element('div', null, edit, 'view-heading'); const editHeadingTitle = element('h3', S('editHeading'), editHeading);
1304
+ const choices = new Map(), choiceLabels = new Map(), controls = [];
1305
+ for (const [state, label] of Object.entries(labels)) {
1306
+ const button = element('button', null, edit, 'choice'); button.style.setProperty('--mark', colors[state]);
1307
+ element('span', null, button, 'dot'); choiceLabels.set(state, element('span', label, button)); button.setAttribute('aria-pressed', 'false');
1308
+ choices.set(state, button); controls.push(button); if (state === 'pushed') button.hidden = true;
1309
+ button.onclick = () => updateDraft(target, { state, progress: state === 'unstarted' ? 0 : state === 'unfinished'
1310
+ ? target.draft.state === 'unfinished' ? target.draft.progress : null : 100 });
1311
+ button.onkeydown = event => {
1312
+ if (!['ArrowUp', 'ArrowDown'].includes(event.key)) return;
1313
+ event.preventDefault(); const buttons = [...choices.values()].filter(item => !item.hidden);
1314
+ buttons[(buttons.indexOf(button) + (event.key === 'ArrowDown' ? 1 : buttons.length - 1)) % buttons.length].focus();
1315
+ };
1316
+ }
1317
+ const progressSection = element('div', null, edit, 'progress-section');
1318
+ const progressHead = element('div', null, progressSection, 'progress-head'); const progressHeadLabel = element('label', S('progressLabel'), progressHead, 'label');
1319
+ const numberWrap = element('div', null, progressHead, 'number-wrap');
1320
+ 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);
1321
+ const range = element('div', null, progressSection, 'range'); element('div', null, range, 'range-track');
1322
+ const nodes = element('div', null, range, 'range-nodes'); nodes.setAttribute('aria-hidden', 'true');
1323
+ 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'); }
1324
+ 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'));
1325
+ const unknownRow = element('div', null, progressSection, 'unknown-row'); const unknown = element('button', S('clearValueBtn'), unknownRow, 'text-button unknown');
1326
+ const noteLabel = element('label', S('notesLabel'), edit, 'note-label');
1327
+ const note = element('textarea', null, edit); note.maxLength = 4000; note.placeholder = S('notePlaceholder'); note.setAttribute('aria-label', S('noteAriaLabel'));
1328
+ noteLabel.htmlFor = note.id = `session-status-note-${serial}`;
1329
+ const git = element('div', null, edit, 'git');
1330
+ const editActions = element('div', null, edit, 'edit-actions');
1331
+ const cancel = element('button', S('cancelBtn'), editActions, 'text-button cancel');
1332
+ const submit = element('button', S('saveBtn'), editActions, 'primary save-record');
1333
+ const history = element('div', null, body, 'view history-view'); history.hidden = true;
1334
+ const historyHeading = element('div', null, history, 'view-heading'); const historyHeadingTitle = element('h3', S('completedHeading'), historyHeading);
1335
+ const back = element('button', S('backLabel'), historyHeading, 'back');
1336
+ const historyList = element('div', null, history, 'history-list');
1337
+ const timelineView = embedded ? element('div', null, body, 'view history-view') : null;
1338
+ let timelineList, timelineHeadingTitle, timelineBackBtn;
1339
+ if (timelineView) {
1340
+ timelineView.hidden = true;
1341
+ const title = element('div', null, timelineView, 'view-heading'); timelineHeadingTitle = element('h3', S('timelineHeading'), title);
1342
+ timelineBackBtn = element('button', S('backLabel'), title, 'back');
1343
+ timelineBackBtn.onclick = () => target.setView('overview');
1344
+ timelineList = element('div', null, timelineView, 'history-list');
1345
+ }
1346
+ const analysisMessage = element('div', null, body, 'analysis-message'); analysisMessage.setAttribute('role', 'status');
1347
+ const error = element('div', null, shell, 'error'); error.setAttribute('role', 'status');
1348
+ const resolveConflict = element('button', S('resolveConflictBtn'), shell, 'text-button'); resolveConflict.hidden = true;
1349
+ controls.push(note, progress, slider, unknown, cancel, submit, clear, analyze, editOpen, resolveConflict);
1350
+ panel = { entry, root, shell, body, heading, titleProgress, choices, note, progress, slider, range, git, error, resolveConflict, controls,
1351
+ statusLabel, statusDot, timestamp, scoreNumber, scoreUnit, meter, sourceLabel, overviewSummary, summaryBlock, noteOpen,
1352
+ totals, analyze, historyList, dirty: false, busy: false, analyzing: false, revision: 0, mode: 'overview' };
1353
+ const target = panel;
1354
+ target.applyLocale = () => {
1355
+ shell.setAttribute('aria-label', S('panelAriaPattern', { title: entry.title }));
1356
+ close?.setAttribute('aria-label', S('close'));
1357
+ if (openPane) {
1358
+ openPane.setAttribute('aria-label', S('openInSidebar'));
1359
+ if (openPaneTip) openPaneTip.textContent = S('openInSidebar');
1360
+ }
1361
+ summaryExpand.textContent = target.summaryExpanded ? S('collapse') : S('expandAll');
1362
+ analyze.textContent = target.analyzing ? S('btnUpdating') : S('btnUpdate');
1363
+ editOpen.textContent = S('btnAdjust');
1364
+ clear.textContent = S('btnClear');
1365
+ clear.setAttribute('aria-label', S('btnClear'));
1366
+ clearTip.textContent = S('clearTooltip');
1367
+ historyRowTitle.textContent = S('completedHeading');
1368
+ noteRowTitle.textContent = S('notesLabel');
1369
+ if (timelineOpen) timelineOpen.textContent = S('timelineLink');
1370
+ editHeadingTitle.textContent = S('editHeading');
1371
+ for (const [state, labelEl] of choiceLabels) labelEl.textContent = labels[state];
1372
+ progressHeadLabel.textContent = S('progressLabel');
1373
+ progress.setAttribute('aria-label', S('progressLabel'));
1374
+ slider.setAttribute('aria-label', S('sliderAriaLabel'));
1375
+ unknown.textContent = S('clearValueBtn');
1376
+ noteLabel.textContent = S('notesLabel');
1377
+ note.placeholder = S('notePlaceholder');
1378
+ note.setAttribute('aria-label', S('noteAriaLabel'));
1379
+ cancel.textContent = S('cancelBtn');
1380
+ submit.textContent = S('saveBtn');
1381
+ historyHeadingTitle.textContent = S('completedHeading');
1382
+ back.textContent = S('backLabel');
1383
+ if (timelineHeadingTitle) timelineHeadingTitle.textContent = S('timelineHeading');
1384
+ if (timelineBackBtn) timelineBackBtn.textContent = S('backLabel');
1385
+ resolveConflict.textContent = S('resolveConflictBtn');
1386
+ target.tasksKey = null; target.completedKey = null; target.timelineRevision = null;
1387
+ };
1388
+ target.capabilities = embedded?.session?.capabilities || null;
1389
+ panelEvent('open', entry);
1390
+ target.request = (type, timeout, extra = {}) => new Promise((resolve, reject) => {
1391
+ const requestId = `${requestPrefix}:${++serial}`;
1392
+ const timer = setTimeout(() => { cancelRead(requestId, { type }); pending.delete(requestId); const error = new Error(S('cardRequestTimeout')); error.code = 'STATUS_REQUEST_TIMEOUT'; reject(error); }, timeout);
1393
+ pending.set(requestId, { resolve, reject, timer, type, key: entry.key });
1394
+ try { send(JSON.stringify({ type, requestId, key: entry.key, ...extra })); }
1395
+ catch { clearTimeout(timer); pending.delete(requestId); const error = new Error(S('cardStatusDisconnected')); error.code = 'STATUS_SEND_FAILED'; reject(error); }
1396
+ });
1397
+ resolveConflict.onclick = () => rebaseDraft(target);
1398
+ const showAppUpdate = info => {
1399
+ target.updateInfo = info;
1400
+ const update = info?.update;
1401
+ const stage = update?.stage;
1402
+ const stages = strings.updateStages || { queued: '正在准备升级', checking: '正在检查版本', downloading: '正在下载新版本', waiting: '等待当前分析结束', installing: '正在升级' };
1403
+ const active = Boolean(stages[stage]) || target.upgradeStarting;
1404
+ const completed = stage === 'completed' && Date.now() - Date.parse(update.updatedAt) < 60000;
1405
+ const failed = stage === 'failed';
1406
+ appUpdate.hidden = !info?.available && !active && !failed && !completed;
1407
+ appUpdate.setAttribute('data-failed', String(failed));
1408
+ appUpdateLabel.textContent = active ? stages[stage] || stages.queued : failed ? S('updateFailedLabel') : completed
1409
+ ? S('upgradedToPattern', { version: update.currentVersion }) : S('updateAvailablePattern', { version: info?.latestVersion });
1410
+ appUpdateButton.textContent = active ? S('pleaseWait') : completed ? S('completedShort') : failed ? S('retryBtn') : S('upgradeBtn');
1411
+ appUpdateButton.disabled = active || completed;
1412
+ const command = info?.command || 'npx agent-things@latest';
1413
+ appUpdateDetail.textContent = target.updateConnectionError ? `${S('reconnectHint')}\n${S('terminalUpgradePrefix')}${command}`
1414
+ : failed ? `${update.error}\n${S('terminalUpgradePrefix')}${command}` : completed && update.reconnectMcp ? S('reconnectMcpHint') : '';
1415
+ appUpdateDetail.hidden = !appUpdateDetail.textContent;
1416
+ refreshPanel();
1417
+ return active;
1418
+ };
1419
+ const pollAppUpdate = async () => {
1420
+ clearTimeout(target.updateTimer);
1421
+ try {
1422
+ const info = await target.request('app-update-info', 12000);
1423
+ if (panel !== target) return;
1424
+ target.updateConnectionError = null;
1425
+ const active = showAppUpdate(info);
1426
+ target.updateTimer = setTimeout(pollAppUpdate, active ? 2000 : 60000);
1427
+ } catch (error) {
1428
+ if (panel !== target) return;
1429
+ target.updateConnectionError = error.message;
1430
+ if (target.updateInfo) showAppUpdate(target.updateInfo);
1431
+ target.updateTimer = setTimeout(pollAppUpdate, 2000);
1432
+ }
1433
+ };
1434
+ appUpdateButton.onclick = async () => {
1435
+ if (appUpdateButton.disabled) return;
1436
+ clearTimeout(target.updateTimer);
1437
+ target.upgradeStarting = true;
1438
+ showAppUpdate(target.updateInfo);
1439
+ try {
1440
+ const info = await target.request('app-update-start', 12000);
1441
+ if (panel !== target) return;
1442
+ target.updateConnectionError = null;
1443
+ target.upgradeStarting = false;
1444
+ showAppUpdate(info);
1445
+ } catch (error) {
1446
+ if (panel !== target) return;
1447
+ target.upgradeStarting = false;
1448
+ target.updateConnectionError = error.message;
1449
+ showAppUpdate(target.updateInfo);
1450
+ }
1451
+ if (panel === target) target.updateTimer = setTimeout(pollAppUpdate, 1000);
1452
+ };
1453
+ target.scheduleMarquees = () => {
1454
+ cancelAnimationFrame(target.marqueeFrame);
1455
+ target.marqueeFrame = requestAnimationFrame(() => {
1456
+ if (panel !== target) return;
1457
+ if (target.mode === 'overview' && !target.summaryExpanded) summaryExpand.hidden = overviewSummary.scrollHeight <= overviewSummary.clientHeight + 1;
1458
+ for (const title of shadow.querySelectorAll('.task-title')) {
1459
+ if (!title.clientWidth) continue;
1460
+ const width = title.firstElementChild.firstElementChild.getBoundingClientRect().width;
1461
+ const maskWidth = title.closest('.task-row').querySelector('.task-source')?.offsetWidth || 0;
1462
+ const distance = Math.max(0, width - title.clientWidth + maskWidth + 8);
1463
+ title.classList.toggle('overflowing', distance > 1);
1464
+ title.style.setProperty('--travel', `${distance}px`);
1465
+ title.style.setProperty('--duration', `${Math.max(1, distance / 26)}s`);
1466
+ }
1467
+ });
1468
+ };
1469
+ target.setSummaryExpanded = expanded => {
1470
+ target.summaryExpanded = expanded;
1471
+ summaryBlock.classList.toggle('expanded', expanded);
1472
+ summaryExpand.textContent = expanded ? S('collapse') : S('expandAll');
1473
+ summaryExpand.setAttribute('aria-expanded', String(expanded));
1474
+ positionPanel(); target.scheduleMarquees();
1475
+ };
1476
+ summaryExpand.onclick = () => { summaryExpand.focus({ preventScroll: true }); target.setSummaryExpanded(!target.summaryExpanded); };
1477
+ summaryBlock.addEventListener('focusout', event => { if (!summaryBlock.contains(event.relatedTarget)) target.setSummaryExpanded(false); });
1478
+ target.resizeObserver = new ResizeObserver(target.scheduleMarquees); target.resizeObserver.observe(body);
1479
+ target.setView = mode => {
1480
+ target.mode = mode; overview.hidden = mode !== 'overview'; edit.hidden = mode !== 'edit'; history.hidden = mode !== 'history';
1481
+ if (timelineView) timelineView.hidden = mode !== 'timeline';
1482
+ body.scrollTop = 0; target.error.textContent = '';
1483
+ if (mode !== 'edit') { target.conflict = false; resolveConflict.hidden = true; }
1484
+ refreshPanel();
1485
+ rememberPanel(target);
1486
+ };
1487
+ const cancelEdit = () => { target.dirty = false; target.setView('overview'); editOpen.focus(); };
1488
+ target.cancelEdit = cancelEdit;
1489
+ editOpen.onclick = () => { target.setView('edit'); (choices.get(target.draft.state) || choices.values().next().value).focus(); };
1490
+ noteRow.onclick = () => { target.setView('edit'); note.focus(); };
1491
+ historyOpen.onclick = () => target.setView('history'); back.onclick = () => target.setView('overview'); cancel.onclick = cancelEdit;
1492
+ if (timelineOpen) timelineOpen.onclick = () => target.setView('timeline');
1493
+ remainingToggle.onclick = () => { target.remainingExpanded = !target.remainingExpanded; refreshPanel(); };
1494
+ const locate = async source => {
1495
+ if (target.capabilities?.locate === false) { analysisMessage.textContent = S('locateHostDisconnected'); return; }
1496
+ if (embedded) {
1497
+ if (!source?.turnId || !source?.itemId) { analysisMessage.textContent = S('locateNoSource'); return; }
1498
+ analysisMessage.textContent = S('locatingMessage');
1499
+ try {
1500
+ const result = await target.request('locate-source', 14000, { source: { turnId: source.turnId, itemId: source.itemId } });
1501
+ analysisMessage.textContent = result?.message || S('locatedMessage');
1502
+ } catch (error) { analysisMessage.textContent = error.message; }
1503
+ return;
1504
+ }
1505
+ if (!source?.turnId || !source?.itemId) { analysisMessage.textContent = S('locateNoSource'); return; }
1506
+ const harness = window.__sessionStatusHarness;
1507
+ if (harness?.locate) {
1508
+ try { await harness.locate({ entry, source, analysisMessage, request: target.request }); }
1509
+ catch (error) { analysisMessage.textContent = error.message; }
1510
+ return;
1511
+ }
1512
+ const row = entry.row;
1513
+ if (row.getAttribute('data-app-action-sidebar-thread-selected') !== 'true') {
1514
+ const trigger = row.querySelector('[data-thread-title-trigger]');
1515
+ if (!trigger) { analysisMessage.textContent = S('locateOpenFailed'); return; } trigger.click();
1516
+ }
1517
+ const deadline = Date.now() + 4000;
1518
+ while (Date.now() < deadline) {
1519
+ if (row.getAttribute('data-app-action-sidebar-thread-selected') === 'true') {
1520
+ const message = [...document.querySelectorAll('[data-content-search-unit-key]')].find(node => node.getAttribute('data-content-search-unit-key') === `${source.turnId}:${source.itemId}`);
1521
+ 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; }
1522
+ }
1523
+ await new Promise(resolve => setTimeout(resolve, 100));
1524
+ }
1525
+ try { await target.request('locate-source', 30000, { source }); analysisMessage.textContent = S('locatedMessage'); }
1526
+ catch (error) { analysisMessage.textContent = error.message; }
1527
+ };
1528
+ const renderTask = (task, sources, parent) => {
1529
+ const row = element('div', null, parent, 'task-row'); row.dataset.status = task.status; row.tabIndex = 0;
1530
+ element('span', null, row, 'task-dot'); const content = element('div', null, row, 'task-content');
1531
+ const title = element('div', null, content, 'task-title'); title.title = task.title;
1532
+ const track = element('div', null, title, 'task-track');
1533
+ const text = task.summary || task.title;
1534
+ element('span', text, track, 'task-copy');
1535
+ element('div', taskLabels[task.status] || S('taskUnknown'), content, 'task-meta');
1536
+ const ref = task.evidenceRefs?.find(value => sources?.[value]?.turnId);
1537
+ 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]); }
1538
+ };
1539
+ target.renderHistory = () => {
1540
+ const state = target.analysisState; if (!state) return;
1541
+ if (timelineList && target.timelineRevision !== state.revision) {
1542
+ target.timelineRevision = state.revision;
1543
+ timelineList.replaceChildren();
1544
+ for (const item of [...(state.timeline || [])].reverse()) {
1545
+ const date = new Date(item.requestedAt).toLocaleString(activeLang === 'en' ? 'en-US' : 'zh-CN');
1546
+ const progress = item.record?.progress ?? item.progress;
1547
+ const label = item.source === 'analysis' ? S('timelineAnalysis') : S('timelineManual');
1548
+ const value = item.status === 'failed' ? S('analysisFailedWord') : item.status === 'pending' ? S('analyzingWord') : progress == null ? S('unrecordedShort') : `${progress}%`;
1549
+ element('div', `${date} · ${label} · ${value}`, timelineList, 'quiet-row');
1550
+ }
1551
+ if (!timelineList.childElementCount) element('div', S('emptyTimeline'), timelineList, 'empty');
1552
+ }
1553
+ const ledger = state.analysis?.ledger; const tasks = ledger?.tasks || [];
1554
+ const remaining = tasks.filter(task => ['todo', 'in_progress', 'blocked', 'needs_verification'].includes(task.status));
1555
+ const completed = tasks.filter(task => task.status === 'done');
1556
+ totals.textContent = tasks.length ? S('totalsPattern', { done: completed.length, total: tasks.length }) : S('totalsEmpty');
1557
+ tasksHeading.textContent = S('remainingHeadingPattern', { count: remaining.length });
1558
+ remainingToggle.hidden = remaining.length <= 3;
1559
+ remainingToggle.textContent = target.remainingExpanded ? S('collapseArrow') : S('showAllCountPattern', { count: remaining.length });
1560
+ remainingToggle.setAttribute('aria-expanded', String(Boolean(target.remainingExpanded)));
1561
+ const tasksKey = JSON.stringify([remaining, state.analysis?.sources, Boolean(target.remainingExpanded), activeLang]);
1562
+ if (target.tasksKey !== tasksKey) {
1563
+ target.tasksKey = tasksKey; currentTasks.replaceChildren();
1564
+ if (!tasks.length) element('div', S('emptyNoTasks'), currentTasks, 'empty');
1565
+ else if (!remaining.length) element('div', S('emptyNoRemaining'), currentTasks, 'empty');
1566
+ for (const task of target.remainingExpanded ? remaining : remaining.slice(0, 3)) renderTask(task, state.analysis?.sources, currentTasks);
1567
+ }
1568
+ historyCount.textContent = S('countArrowPattern', { count: completed.length });
1569
+ const completedKey = JSON.stringify([completed, state.analysis?.sources, activeLang]);
1570
+ if (target.completedKey === completedKey) return;
1571
+ target.completedKey = completedKey; historyList.replaceChildren();
1572
+ for (const task of completed) renderTask(task, state.analysis?.sources, historyList);
1573
+ if (!completed.length) element('div', S('emptyCompleted'), historyList, 'empty');
1574
+ };
1575
+
1576
+ const pollHistory = () => {
1577
+ if (panel !== target) return;
1578
+ target.request('analysis-state', 7000).then(showHistory).catch(() => {
1579
+ if (panel !== target) return;
1580
+ analysisMessage.textContent = S('retryingStatus');
1581
+ clearTimeout(target.pollTimer); target.pollTimer = setTimeout(pollHistory, 2000);
1582
+ });
1583
+ };
1584
+ target.pollHistory = pollHistory;
1585
+ const showHistory = state => {
1586
+ if (panel !== target || !state || (target.historyRevision ?? -1) > state.revision) return;
1587
+ target.historyRevision = state.revision; target.analysisState = state;
1588
+ const active = (state.timeline || []).find(item => item.source === 'analysis' && item.status === 'pending');
1589
+ target.analyzing = Boolean(active); analyze.disabled = target.analyzing;
1590
+ const stages = strings.analysisStages || { starting: '正在启动分析', reading: '正在读取会话', retrying: '正在重新连接', analyzing: '正在分析任务' };
1591
+ target.stageMessage = active ? (stages[active.stage] || stages.analyzing) : '';
1592
+ const latest = state.timeline?.at(-1);
1593
+ analysisMessage.textContent = target.stageMessage || (latest?.status === 'failed' ? `${S('analysisFailedPrefix')}${latest.error || S('analysisFailedRetry')}` : ''); analyze.textContent = active ? S('btnUpdating') : S('btnUpdate');
1594
+ clearTimeout(target.pollTimer); if (active && !embedded?.streamConnected) target.pollTimer = setTimeout(pollHistory, 2000);
1595
+ refreshPanel();
1596
+ };
1597
+ target.showHistory = showHistory;
1598
+ analyze.onclick = async () => {
1599
+ analyze.disabled = true; analysisMessage.textContent = S('startingAnalysisFeedback');
1600
+ try { showHistory(await target.request('analyze', 7000)); }
1601
+ catch (error) {
1602
+ if (panel !== target) return;
1603
+ if (['STATUS_REQUEST_TIMEOUT', 'STATUS_SEND_FAILED'].includes(error.code)) {
1604
+ analysisMessage.textContent = S('retryingStatus'); clearTimeout(target.pollTimer); target.pollTimer = setTimeout(pollHistory, 2000);
1605
+ } else { analysisMessage.textContent = error.message; analyze.disabled = false; }
1606
+ }
1607
+ };
1608
+ const setProgress = value => {
1609
+ const state = presentation ? presentation.progressState(target.draft.state, value) : value === 100 ? target.draft.state === 'pushed' ? 'pushed' : 'completed'
1610
+ : value === 0 && target.draft.state === 'unstarted' ? 'unstarted' : 'unfinished';
1611
+ updateDraft(target, { progress: value, state });
1612
+ };
1613
+ let dragging = false;
1614
+ slider.onpointerdown = () => { dragging = true; };
1615
+ const endDrag = () => { dragging = false; }; slider.onpointerup = endDrag; slider.onpointercancel = endDrag; slider.onlostpointercapture = endDrag;
1616
+ 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); };
1617
+ 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; };
1618
+ unknown.onclick = () => setProgress(null);
1619
+ note.oninput = () => { target.draft.note = note.value; target.dirty = true; rememberPanel(target); };
1620
+ submit.onclick = async () => { if (await save({}, false, target)) target.setView('overview'); };
1621
+ progress.onkeydown = event => { if (event.key === 'Enter') submit.click(); };
1622
+ clear.onclick = async () => { if (await save({}, true, target)) target.setView('overview'); };
1623
+ if (close) close.onclick = () => closePanel();
1624
+ if (openPane) openPane.onclick = async () => {
1625
+ openPane.disabled = true; analysisMessage.textContent = '';
1626
+ try { await harness.openPane({ entry, request: target.request }); if (panel === target) closePanel(); }
1627
+ catch (error) { if (panel === target) { openPane.disabled = false; analysisMessage.textContent = error.message; } }
1628
+ };
1629
+ // 首次历史读取前以当前快照为基线:读取期间到达的新版快照会触发补读。
1630
+ target.syncVersion = panelVersion(entry.key);
1631
+ if (embedded?.analysisState) showHistory(embedded.analysisState); else pollHistory();
1632
+ pollAppUpdate();
1633
+ target.request('project-git', 14000).then(info => { if (panel === target) { target.projectGit = info; refreshPanel(); } }).catch(() => {
1634
+ if (panel === target) { target.projectGit = { status: 'unknown', hasRemote: false }; refreshPanel(); }
1635
+ });
1636
+ entry.button?.setAttribute('aria-expanded', 'true'); refreshPanel();
1637
+ const remembered = rememberedPanel(entry.key);
1638
+ if (remembered) restorePanel(target, remembered); else if (!embedded) editOpen.focus();
1639
+ }
1640
+
1641
+ function receive(next) {
1642
+ if (!next || (next.revision < snapshot.revision && (!next.lang || next.lang === activeLang))) return;
1643
+ const langChanged = next.lang ? setLang(next.lang) : false;
1644
+ snapshot = next;
1645
+ if (langChanged && panel) panel.applyLocale?.();
1646
+ for (const entry of mounted.values()) paint(entry);
1647
+ refreshPanel();
1648
+ // 其他入口改了这个会话(保存、清除、分析、任务来源):按单会话数据版本补读;弹窗忙时记下,空闲后补读一次。乱序回复由 historyRevision 丢弃。
1649
+ if (panel?.pollHistory) syncPanel(panel);
1650
+ }
1651
+
1652
+ function panelVersion(key) {
1653
+ if (snapshot.keyVersions) return snapshot.keyVersions[key] ?? snapshot.keyVersionBase ?? 0;
1654
+ return JSON.stringify([snapshot.records?.[key] || null, (snapshot.analyzingKeys || []).includes(key)]);
1655
+ }
1656
+
1657
+ function syncPanel(target) {
1658
+ const version = panelVersion(target.entry.key);
1659
+ if (target.syncVersion === undefined) { target.syncVersion = version; return; }
1660
+ if (target.syncVersion === version && !target.syncPending) return;
1661
+ if (target.busy) { target.syncPending = true; return; }
1662
+ target.syncVersion = version; target.syncPending = false; target.pollHistory();
1663
+ }
1664
+
1665
+ function onOutside(event) {
1666
+ if (!panel || event.composedPath().includes(panel.root) || event.composedPath().includes(panel.entry.host)) return;
1667
+ if (event.composedPath().some(node => node.hasAttribute?.('data-codex-session-status'))) return;
1668
+ closePanel(false);
1669
+ }
1670
+
1671
+ function onKey(event) {
1672
+ if (!panel || event.key !== 'Escape') return;
1673
+ event.preventDefault(); event.stopPropagation();
1674
+ closePanel();
1675
+ }
1676
+
1677
+ function onScroll() {
1678
+ if (!panel) return;
1679
+ if (!visible(panel.entry.host)) closePanel(false);
1680
+ else positionPanel();
1681
+ }
1682
+
1683
+ const observer = new MutationObserver(records => {
1684
+ if (records.every(r => r.target.closest?.('[data-codex-session-status], [data-codex-session-status-panel]'))) return;
1685
+ schedule();
1686
+ });
1687
+ 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'];
1688
+ if (!embedded) {
1689
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: filter });
1690
+ document.addEventListener('pointerdown', onOutside, true);
1691
+ document.addEventListener('keydown', onKey, true);
1692
+ document.addEventListener('scroll', onScroll, true);
1693
+ }
1694
+ window.addEventListener('resize', positionPanel);
1695
+ const api = {
1696
+ receive(next) { receive(next); localCards?.receive(next); },
1697
+ receiveCardEvent({ snapshot: next, analysisState, session }) {
1698
+ if (!embedded) return;
1699
+ embedded.streamConnected = true;
1700
+ if (!next || next.revision < snapshot.revision) return;
1701
+ if (panel && session?.key === panel.entry.key) panel.capabilities = session.capabilities;
1702
+ receive(next);
1703
+ panel?.showHistory(analysisState);
1704
+ },
1705
+ disconnectCardEvents() {
1706
+ if (!embedded?.streamConnected) return;
1707
+ embedded.streamConnected = false;
1708
+ if (panel?.analyzing) panel.pollHistory();
1709
+ },
1710
+ setTheme(theme) { if (embedded && embedded.theme !== theme && ['light', 'dark'].includes(theme)) { embedded.theme = theme; positionPanel(); } },
1711
+ reply(message) {
1712
+ localCards?.reply(message);
1713
+ const { requestId, error, errorInfo, session, snapshot: next, analysisState, projectGit, updateInfo, navigation, pane } = message;
1714
+ if (panel && session?.key === panel.entry.key) panel.capabilities = session.capabilities;
1715
+ receive(next);
1716
+ const request = pending.get(requestId);
1717
+ if (!request) return;
1718
+ clearTimeout(request.timer); pending.delete(requestId);
1719
+ if (error) request.reject(Object.assign(new Error(error), errorInfo || {})); else request.resolve(navigation || updateInfo || projectGit || analysisState || pane);
1720
+ },
1721
+ status: () => ({ mounted: mounted.size, panelOpen: Boolean(panel), revision: snapshot.revision, version, startup: { ...startup } }),
1722
+ exportForReload({ allowPending = false } = {}) {
1723
+ if (!allowPending && (panel?.busy || pending.size)) return { busy: true };
1724
+ const active = panel ? rememberPanel(panel) : null;
1725
+ return { snapshot, panel: active, panelStates: [...panelStates], localCards: localCards?.exportState() };
1726
+ },
1727
+ destroy() {
1728
+ destroyed = true; localCards?.destroy(); harness?.dispose?.(); observer.disconnect(); cancelAnimationFrame(frame);
1729
+ 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; }
1730
+ for (const entry of [...mounted.values()]) unmount(entry);
1731
+ document.removeEventListener('pointerdown', onOutside, true); document.removeEventListener('keydown', onKey, true);
1732
+ document.removeEventListener('scroll', onScroll, true); window.removeEventListener('resize', positionPanel);
1733
+ for (const request of pending.values()) { clearTimeout(request.timer); request.reject(new Error(S('cardDaemonDisconnected'))); }
1734
+ pending.clear(); if (!embedded?.independent) delete window.__codexSessionStatus;
1735
+ if (harness?.globalName && window[harness.globalName]) delete window[harness.globalName];
1736
+ }
1737
+ };
1738
+ if (!embedded?.independent) window.__codexSessionStatus = api;
1739
+ if (harness?.globalName) window[harness.globalName] = api;
1740
+ if (embedded) {
1741
+ receive(embedded.snapshot);
1742
+ openPanel({ key: embedded.key, title: embedded.title });
1743
+ if (restored?.panel) restorePanel(panel, restored.panel);
1744
+ return api;
1745
+ }
1746
+ localCards = harness?.createLocalCards?.({
1747
+ mount: (options, state) => installCodexSessionStatus(version, state, options),
1748
+ send: payload => send(payload), snapshot: () => snapshot, restored: restored?.localCards,
1749
+ });
1750
+ reconcile();
1751
+ if (restored) {
1752
+ receive(restored.snapshot);
1753
+ const saved = restored.panel;
1754
+ const entry = saved && [...mounted.values()].find(item => item.key === saved.key);
1755
+ if (entry) {
1756
+ panelStates.set(saved.key, saved);
1757
+ openPanel(entry);
1758
+ }
1759
+ }
1760
+ }
1761
+