@v587d/capital-generation 2.19.0 → 2.19.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.
@@ -10,12 +10,14 @@ const {
10
10
  IconChevronDownOutlineRegular,
11
11
  IconChevronLeftOutlineRegular,
12
12
  IconChevronRightOutlineRegular,
13
+ IconCloseOutlineRegular,
13
14
  IconClockOutlineRegular,
14
15
  IconCopyOutlineRegular,
15
16
  IconEditOutlineRegular,
16
17
  IconEllipsisOutlineRegular,
17
18
  IconFolderOpenOutlineRegular,
18
19
  IconInfoOutlineRegular,
20
+ IconNewChatOutlineRegular,
19
21
  IconPauseOutlineRegular,
20
22
  IconPlayOutlineRegular,
21
23
  IconPlusOutlineRegular,
@@ -34,7 +36,7 @@ const {
34
36
  TASK_ICON_CATALOG,
35
37
  TASK_ICON_IDS,
36
38
  DEFAULT_CUSTOM_ICON,
37
- builtinTaskIcon,
39
+ taskIconId,
38
40
  } = require('./task-icons.js')
39
41
 
40
42
  const ENTRY_NAME = 'capital-automation'
@@ -125,8 +127,15 @@ const zh = {
125
127
  briefSkipped: '这次运行没有可简报的结论',
126
128
  retry: '重试',
127
129
  retryQueued: '已重新提交任务简报',
128
- aiBadge: 'AI 简报',
129
- partial: '原文过长,已取头尾',
130
+ askLabel: '就这条简报提问',
131
+ askPlaceholder: '快速提问…',
132
+ askDialogTitle: '对话',
133
+ askEmptyTitle: '暂无提问',
134
+ askSubmit: '提问',
135
+ askCollapse: '收起',
136
+ askPending: '正在回答…',
137
+ askFailed: '回答失败',
138
+ askMore: '查看更多',
130
139
  stocksCount: '{n} 个标的',
131
140
  gapsCount: '{n} 个缺口',
132
141
  todoConfirm: '待确认',
@@ -494,7 +503,7 @@ function installStyles() {
494
503
  body:not([data-ds-dark-theme]) .capital-automation-page, body:not([data-ds-dark-theme]) .capital-automation-modal { --ca-line: #0000001f; --ca-line-soft: #0000001a; --ca-table-line: #00000026; --ca-muted: #5d626a; --ca-caption: #6a6f77; --ca-hover: #eef1f5; --ca-field: #f7f8fa; --ca-business: #2f63d6; --ca-success: #16a34a; --ca-error: #dc2626; --ca-warn: #d97706; --ca-business-text: #2f63d6; --ca-success-text: #15803d; --ca-error-text: #c81e1e; --ca-warn-text: #b45309; --ca-tag-news: #2f6fd0; --ca-tag-market: #a85a08; --ca-tag-review: #6d4ac4; --ca-tag-research: #0f766e; --ca-tag-portfolio: #4d7c0f; --ca-tag-monitor: #0e7490; --ca-tag-custom: #b3246d; --ca-heat-0: #eef1f4; --ca-heat-1: #b7e4c0; --ca-heat-2: #74c98a; --ca-heat-3: #3ba55c; --ca-heat-4: #1f7a3a; --ca-heat-fail: #cf222e; }
495
504
  .capital-automation-page { display: flex; flex-direction: column; min-height: 0; height: 100%; color: var(--dsw-alias-label-primary); }
496
505
  .capital-automation-head { flex: none; padding: 18px 0 0; }
497
- .capital-automation-headinner { box-sizing: border-box; width: min(1080px, 100%); margin: 0 auto; padding: 0 clamp(20px, 3vw, 36px); }
506
+ .capital-automation-headinner { box-sizing: border-box; width: min(1080px, 100%); margin: 0 auto 5px; padding: 0 clamp(20px, 3vw, 36px); }
498
507
  .capital-automation-topbar { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; gap: 12px 18px; min-width: 0; }
499
508
  .capital-automation-brand { display: flex; align-items: center; gap: 10px; min-width: 0; justify-self: start; }
500
509
  .capital-automation-brandmark { flex: none; width: 28px; height: 28px; display: grid; place-items: center; border-radius: 9px; color: #fff; background: linear-gradient(135deg, #4f8cff, #7c3aed); box-shadow: inset 0 1px 0 rgba(255,255,255,.24); }
@@ -968,11 +977,47 @@ function installStyles() {
968
977
  .capital-automation-brieftitle h3 { margin: 0; color: var(--dsw-alias-label-primary); font-size: 13.5px; line-height: 20px; font-weight: 600; overflow-wrap: anywhere; }
969
978
  .capital-automation-brieftime { color: var(--ca-caption); font-size: 11.5px; line-height: 18px; font-variant-numeric: tabular-nums; }
970
979
  .capital-automation-briefcard h4 { margin: 0; color: var(--dsw-alias-label-primary); font-size: 18px; line-height: 27px; font-weight: 600; letter-spacing: .1px; overflow-wrap: anywhere; }
980
+ .capital-automation-briefbody { display: flex; flex-direction: column; gap: 7px; min-width: 0; }
971
981
  .capital-automation-brieftext { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 1.68; overflow-wrap: anywhere; }
972
- .capital-automation-briefmeta { display: flex; flex-wrap: wrap; align-items: center; gap: 5px 10px; color: var(--ca-caption); font-size: 11.5px; line-height: 18px; }
973
- .capital-automation-briefpartial { color: var(--ca-warn-text); }
974
- .capital-automation-briefai { color: var(--ca-business-text); font-weight: 500; }
975
982
  .capital-automation-briefstate { display: flex; flex-direction: column; gap: 7px; color: var(--ca-muted); font-size: 12.5px; line-height: 19px; }
983
+ .capital-automation-briefheadactions { display: flex; align-items: center; gap: 6px; }
984
+ .capital-automation-askdock { display: flex; flex-direction: column; gap: 8px; min-width: 0; margin-top: 1px; padding-top: 10px; border-top: .5px solid var(--ca-line); }
985
+ .capital-automation-askinput { box-sizing: border-box; flex: 1 1 auto; min-width: 0; height: 34px; padding: 0 11px; border: .5px solid var(--ca-line-soft); border-radius: 10px; background: var(--ca-field); color: var(--dsw-alias-label-primary); font: inherit; font-size: 12.5px; line-height: 20px; outline: 0; }
986
+ .capital-automation-askinput::placeholder { color: var(--ca-caption); }
987
+ .capital-automation-askinput:focus-visible { outline: 2px solid var(--dsw-focus-ring-color, var(--ca-business)); outline-offset: 1px; }
988
+ .capital-automation-askinput:disabled { opacity: .62; cursor: not-allowed; }
989
+ .capital-automation-askthread { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
990
+ .capital-automation-askuser { display: block; align-self: flex-end; max-width: min(100%, 620px); padding: 7px 10px; border: .5px solid color-mix(in srgb, var(--ca-business) 26%, var(--ca-line-soft)); border-radius: 12px 12px 4px 12px; background: color-mix(in srgb, var(--ca-business) 11%, var(--ca-field)); }
991
+ .capital-automation-askquestion { margin: 0; color: var(--dsw-alias-label-primary); font-size: 12.5px; line-height: 18px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow-wrap: anywhere; }
992
+ .capital-automation-askreply { display: flex; flex-direction: column; gap: 5px; align-self: stretch; padding: 8px 10px; border: .5px solid var(--ca-line); border-left: 2px solid var(--ca-business); border-radius: 4px 12px 12px 12px; background: var(--ca-field); }
993
+ .capital-automation-askreply[data-status="failed"] { border-left-color: var(--ca-error); }
994
+ .capital-automation-askpreview { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 13px; line-height: 20px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow-wrap: anywhere; }
995
+ .capital-automation-askfull { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 13px; line-height: 20px; white-space: pre-wrap; overflow-wrap: anywhere; }
996
+ .capital-automation-askhint { margin: 0; color: var(--ca-muted); font-size: 12px; line-height: 19px; }
997
+ .capital-automation-askaction { align-self: flex-end; margin-top: 1px; }
998
+ .capital-automation-askaction[data-expanded="true"] { color: var(--ca-muted); }
999
+ .capital-automation-askerror { margin: 0; color: var(--ca-error-text); font-size: 11.5px; line-height: 18px; overflow-wrap: anywhere; }
1000
+ .capital-automation-modal-chat { width: min(640px, calc(100vw - 32px)); max-width: min(640px, calc(100vw - 32px)); }
1001
+ .capital-automation-chatshell { display: flex; flex-direction: column; height: min(640px, calc(100dvh - 40px)); max-height: calc(100dvh - 40px); min-height: 360px; overflow: hidden; border-radius: 16px; background: var(--ca-card); }
1002
+ .capital-automation-chathead { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 10px 14px 6px; }
1003
+ .capital-automation-chaticonbtn { display: grid; flex: none; place-items: center; width: 30px; height: 30px; padding: 0; border: 0; border-radius: 50%; background: transparent; color: var(--dsw-alias-label-primary); cursor: pointer; }
1004
+ .capital-automation-chaticonbtn:hover { background: var(--ca-hover); }
1005
+ .capital-automation-chaticonbtn:focus-visible { outline: 2px solid var(--dsw-focus-ring-color, var(--ca-business)); outline-offset: 1px; }
1006
+ .capital-automation-chatscroll { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 2px 18px 12px; }
1007
+ .capital-automation-chatcontext { display: grid; grid-template-columns: 38px minmax(0, 1fr); gap: 10px; padding: 8px 0 14px; }
1008
+ .capital-automation-chatcontextbody { min-width: 0; }
1009
+ .capital-automation-chatcontexthead { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 8px; min-width: 0; }
1010
+ .capital-automation-chatcontexthead strong { color: var(--dsw-alias-label-primary); font-size: 13.5px; line-height: 20px; font-weight: 600; }
1011
+ .capital-automation-chatcontextmeta { color: var(--ca-caption); font-size: 11.5px; line-height: 18px; }
1012
+ .capital-automation-chatcontext h3 { margin: 5px 0 0; color: var(--dsw-alias-label-primary); font-size: 16px; line-height: 24px; font-weight: 600; letter-spacing: .1px; overflow-wrap: anywhere; }
1013
+ .capital-automation-chatcontexttext { margin: 5px 0 0; color: var(--dsw-alias-label-secondary); font-size: 13px; line-height: 20px; white-space: pre-wrap; overflow-wrap: anywhere; }
1014
+ .capital-automation-chatthread { margin-left: 18px; padding: 12px 0 4px 30px; border-left: 2px solid var(--ca-line); }
1015
+ .capital-automation-chatempty { margin-left: 18px; padding: 12px 0 4px 30px; border-left: 2px solid var(--ca-line); }
1016
+ .capital-automation-chatempty p { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 13px; line-height: 20px; }
1017
+ .capital-automation-chatcomposer { display: flex; align-items: center; gap: 8px; padding: 10px 16px 14px; border-top: .5px solid var(--ca-line); }
1018
+ .capital-automation-chatcomposer .capital-automation-askinput { height: 38px; }
1019
+ .capital-automation-chatsend { flex: none; height: 36px; padding: 0 16px; font-weight: 600; }
1020
+ .capital-automation-chaterror { padding: 8px 0 0; }
976
1021
  .capital-automation-briefstate[data-tone="error"] { color: var(--ca-error-text); }
977
1022
  .capital-automation-briefstate p { margin: 0; }
978
1023
  .capital-automation-briefactions { display: flex; flex-wrap: wrap; align-items: center; gap: 7px; margin-top: 2px; }
@@ -1071,10 +1116,35 @@ function installStyles() {
1071
1116
  return () => style.remove()
1072
1117
  }
1073
1118
 
1119
+ const BOARD_SNAPSHOT_MAX_AGE_MS = 30 * 60_000
1120
+ let boardSnapshot = null
1121
+ let warmStarted = false
1122
+ let lastBoardFetchAt = 0
1123
+ let lastClickAt = 0
1124
+
1125
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
1126
+ // Capture fires before any panel handler, so the page can report click → mount (shell cost).
1127
+ document.addEventListener('click', () => {
1128
+ lastClickAt = typeof performance === 'undefined' ? Date.now() : performance.now()
1129
+ }, true)
1130
+ }
1131
+
1132
+ function readBoardSnapshot(query) {
1133
+ if (boardSnapshot === null || boardSnapshot.query !== query) return null
1134
+ if (Date.now() - boardSnapshot.at > BOARD_SNAPSHOT_MAX_AGE_MS) return null
1135
+ return boardSnapshot.value
1136
+ }
1137
+
1138
+ function writeBoardSnapshot(query, value) {
1139
+ // Entry always starts at the default view; a filtered board must not evict its snapshot.
1140
+ if (query !== boardQueryOf('14', 'all', null)) return
1141
+ boardSnapshot = { query, at: Date.now(), value }
1142
+ }
1143
+
1074
1144
  function createApi() {
1075
1145
  async function request(path, options = {}) {
1076
1146
  const controller = typeof AbortController === 'function' ? new AbortController() : undefined
1077
- const timeout = setTimeout(() => controller?.abort(), 20_000)
1147
+ const timeout = setTimeout(() => controller?.abort(), options.timeoutMs ?? 20_000)
1078
1148
  let response
1079
1149
  let payload
1080
1150
  try {
@@ -1101,6 +1171,25 @@ function createApi() {
1101
1171
  }
1102
1172
  return payload
1103
1173
  }
1174
+
1175
+ /**
1176
+ * Boot-time idle prefetch: it only seeds the snapshot. The page still fetches a fresh board
1177
+ * on open, so a snapshot is never mistaken for a revalidated payload.
1178
+ */
1179
+ async function warm() {
1180
+ if (warmStarted) return
1181
+ const query = boardQueryOf('14', 'all', null)
1182
+ if (readBoardSnapshot(query) !== null) return
1183
+ if (Date.now() - lastBoardFetchAt < 10_000) return
1184
+ warmStarted = true
1185
+ lastBoardFetchAt = Date.now()
1186
+ try {
1187
+ writeBoardSnapshot(query, await request(`/board${query}`))
1188
+ } catch {
1189
+ warmStarted = false
1190
+ }
1191
+ }
1192
+
1104
1193
  return {
1105
1194
  meta: () => request('/meta'),
1106
1195
  tasks: () => request('/tasks'),
@@ -1113,9 +1202,20 @@ function createApi() {
1113
1202
  cancel: (id) => request(`/runs/${encodeURIComponent(id)}/cancel`, { method: 'POST' }),
1114
1203
  runs: (query = '') => request(`/runs${query}`),
1115
1204
  history: (query = '') => request(`/runs/history${query}`),
1116
- board: (query = '') => request(`/board${query}`),
1205
+ board: (query = '') => {
1206
+ lastBoardFetchAt = Date.now()
1207
+ return request(`/board${query}`)
1208
+ },
1209
+ warm,
1117
1210
  confirmTodo: (id) => request('/board/todos/confirm', { method: 'POST', body: { id } }),
1118
1211
  retryBrief: (runId) => request(`/board/briefs/${encodeURIComponent(runId)}/retry`, { method: 'POST' }),
1212
+ askBrief: (runId, question, timeZone) => request(`/board/briefs/${encodeURIComponent(runId)}/ask`, {
1213
+ method: 'POST',
1214
+ body: { question, timeZone },
1215
+ timeoutMs: 60_000,
1216
+ }),
1217
+ askStatus: (askId) => request(`/board/asks/${encodeURIComponent(askId)}`),
1218
+ askAnswer: (askId) => request(`/board/asks/${encodeURIComponent(askId)}/answer`),
1119
1219
  notifications: () => request('/notifications'),
1120
1220
  markRead: (body) => request('/notifications/read', { method: 'POST', body }),
1121
1221
  }
@@ -1196,12 +1296,6 @@ function iconDefinition(id) {
1196
1296
  : undefined
1197
1297
  }
1198
1298
 
1199
- function taskIconId(task) {
1200
- if (iconDefinition(task?.icon) !== undefined) return task.icon
1201
- if (task?.origin === 'custom') return DEFAULT_CUSTOM_ICON
1202
- return builtinTaskIcon(task?.sourceBuiltinId)
1203
- }
1204
-
1205
1299
  function taskIcon(task) {
1206
1300
  return iconDefinition(taskIconId(task)) ?? TASK_ICON_CATALOG[DEFAULT_CUSTOM_ICON]
1207
1301
  }
@@ -1226,13 +1320,13 @@ function TaskGlyph(props) {
1226
1320
  }
1227
1321
 
1228
1322
  function Glyph(props) {
1229
- const { task, size = 34, large = false } = props
1323
+ const { task, size = 34, large = false, radius, glyphSize } = props
1230
1324
  const edge = large ? 44 : size
1231
1325
  return h('span', {
1232
1326
  className: 'capital-automation-glyph',
1233
1327
  'data-tone': toneOf(task),
1234
- style: { width: edge, height: edge, borderRadius: large ? 13 : 10 },
1235
- }, h(TaskGlyph, { task, size: large ? 22 : 17 }))
1328
+ style: { width: edge, height: edge, borderRadius: radius ?? (large ? 13 : 10) },
1329
+ }, h(TaskGlyph, { task, size: glyphSize ?? (large ? 22 : 17) }))
1236
1330
  }
1237
1331
 
1238
1332
  function IconPickerTrigger(props) {
@@ -1303,19 +1397,28 @@ function StateBadge(props) {
1303
1397
  label)
1304
1398
  }
1305
1399
 
1400
+ const TIME_FORMATTERS = new Map()
1401
+ const RELATIVE_TIME_FORMAT = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'auto' })
1402
+
1306
1403
  function formatTime(value, options = {}) {
1307
1404
  if (typeof value !== 'string' || value.length === 0) return zh.never
1308
1405
  const date = new Date(value)
1309
1406
  if (Number.isNaN(date.getTime())) return value
1310
- return new Intl.DateTimeFormat('zh-CN', {
1311
- year: options.short === true ? undefined : 'numeric',
1312
- month: '2-digit',
1313
- day: '2-digit',
1314
- hour: '2-digit',
1315
- minute: '2-digit',
1316
- hourCycle: 'h23',
1317
- ...(typeof options.timeZone === 'string' && options.timeZone.length > 0 ? { timeZone: options.timeZone } : {}),
1318
- }).format(date)
1407
+ const key = `${options.short === true ? 'short' : 'full'}|${options.timeZone ?? ''}`
1408
+ let formatter = TIME_FORMATTERS.get(key)
1409
+ if (formatter === undefined) {
1410
+ formatter = new Intl.DateTimeFormat('zh-CN', {
1411
+ year: options.short === true ? undefined : 'numeric',
1412
+ month: '2-digit',
1413
+ day: '2-digit',
1414
+ hour: '2-digit',
1415
+ minute: '2-digit',
1416
+ hourCycle: 'h23',
1417
+ ...(typeof options.timeZone === 'string' && options.timeZone.length > 0 ? { timeZone: options.timeZone } : {}),
1418
+ })
1419
+ TIME_FORMATTERS.set(key, formatter)
1420
+ }
1421
+ return formatter.format(date)
1319
1422
  }
1320
1423
 
1321
1424
  function formatShortTime(value, timeZone) {
@@ -1343,7 +1446,7 @@ function formatRelative(value) {
1343
1446
  [3_600_000, 'hour'],
1344
1447
  [60_000, 'minute'],
1345
1448
  ]
1346
- const formatter = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'auto' })
1449
+ const formatter = RELATIVE_TIME_FORMAT
1347
1450
  for (const [unitMs, unit] of units) {
1348
1451
  if (abs >= unitMs || unit === 'minute') return formatter.format(Math.round(diff / unitMs), unit)
1349
1452
  }
@@ -4049,8 +4152,295 @@ function BoardToolbar(props) {
4049
4152
  h('span', { className: 'capital-automation-btnlabel' }, railOpen === true ? zh.board.hideRail : zh.board.showRail))))
4050
4153
  }
4051
4154
 
4155
+ function AskExchange(props) {
4156
+ const { ask, api } = props
4157
+ const [expanded, setExpanded] = useState(false)
4158
+ const [full, setFull] = useState('')
4159
+ const [truncated, setTruncated] = useState(false)
4160
+ const [loading, setLoading] = useState(false)
4161
+ const [error, setError] = useState('')
4162
+
4163
+ useEffect(() => {
4164
+ setExpanded(false)
4165
+ setFull('')
4166
+ setTruncated(false)
4167
+ setLoading(false)
4168
+ setError('')
4169
+ }, [ask?.id])
4170
+
4171
+ async function toggle() {
4172
+ if (expanded) {
4173
+ setExpanded(false)
4174
+ return
4175
+ }
4176
+ if (full.length > 0) {
4177
+ setExpanded(true)
4178
+ return
4179
+ }
4180
+ if (typeof api?.askAnswer !== 'function') {
4181
+ setError(zh.errorGeneric)
4182
+ return
4183
+ }
4184
+ setLoading(true)
4185
+ setError('')
4186
+ try {
4187
+ const payload = await api.askAnswer(ask.id)
4188
+ if (typeof payload?.answer === 'string' && payload.answer.length > 0) {
4189
+ setFull(payload.answer)
4190
+ setTruncated(payload.truncated === true)
4191
+ setExpanded(true)
4192
+ } else {
4193
+ setError(zh.errorGeneric)
4194
+ }
4195
+ } catch (failure) {
4196
+ setError(failure?.message ?? zh.errorGeneric)
4197
+ } finally {
4198
+ setLoading(false)
4199
+ }
4200
+ }
4201
+
4202
+ const ready = ask.status === 'ready'
4203
+ const canExpand = ready && typeof ask.preview === 'string' && ask.preview.endsWith('…')
4204
+ const fullText = expanded && full.length > 0
4205
+ return h('div', { className: 'capital-automation-askthread', 'data-status': ask.status },
4206
+ h('div', { className: 'capital-automation-askuser' },
4207
+ h('p', { className: 'capital-automation-askquestion', title: ask.question }, ask.question)),
4208
+ h('div', { className: 'capital-automation-askreply', 'data-status': ask.status },
4209
+ ready
4210
+ ? h('p', { className: fullText ? 'capital-automation-askfull' : 'capital-automation-askpreview' },
4211
+ fullText ? full : (ask.preview ?? ''))
4212
+ : ask.status === 'failed'
4213
+ ? h('p', { className: 'capital-automation-askerror' }, ask.error ?? zh.board.askFailed)
4214
+ : h('p', { className: 'capital-automation-askhint', role: 'status' }, zh.board.askPending),
4215
+ canExpand
4216
+ ? h('button', {
4217
+ type: 'button',
4218
+ className: 'capital-automation-btn capital-automation-askaction',
4219
+ 'data-size': 'sm',
4220
+ 'data-variant': 'ghost',
4221
+ 'data-expanded': fullText ? 'true' : 'false',
4222
+ disabled: loading,
4223
+ onClick: toggle,
4224
+ }, loading ? zh.loading : fullText ? zh.board.askCollapse : zh.board.askMore,
4225
+ loading || fullText ? null : h(IconChevronDownOutlineRegular, { size: 12 }))
4226
+ : null,
4227
+ error.length > 0 ? h('p', { className: 'capital-automation-askerror', role: 'alert' }, error) : null,
4228
+ truncated ? h('p', { className: 'capital-automation-askhint' }, '回答过长,已截断;完整内容请打开 session 查看。') : null))
4229
+ }
4230
+
4231
+ function AskDialog(props) {
4232
+ const { open, onClose, card, identity, ask, api, question, onQuestionChange, onSubmit, busy, error, onOpenSession } = props
4233
+ const inputRef = useRef(null)
4234
+ useEffect(() => {
4235
+ if (!open) return undefined
4236
+ const timer = setTimeout(() => inputRef.current?.focus?.(), 0)
4237
+ return () => clearTimeout(timer)
4238
+ }, [open])
4239
+ if (!open) return null
4240
+ const brief = card.brief
4241
+ const status = brief?.status ?? 'pending'
4242
+ const sessionId = card.sessionId
4243
+ const openSession = typeof onOpenSession === 'function' && typeof sessionId === 'string' && sessionId.length > 0
4244
+ ? () => onOpenSession(sessionId)
4245
+ : null
4246
+ const trigger = card.trigger === 'manual' ? zh.triggerManual : zh.triggerScheduled
4247
+ const relativeTime = boardRelativeTime(card.finishedAt)
4248
+ const exactTime = formatTime(card.finishedAt)
4249
+ const running = ask?.status === 'running'
4250
+ let context
4251
+ if (status === 'ready') {
4252
+ context = h('div', null,
4253
+ h('h3', null, brief.headline),
4254
+ h('p', { className: 'capital-automation-chatcontexttext' }, brief.plain))
4255
+ } else if (status === 'failed') {
4256
+ context = h('div', null,
4257
+ h('p', { className: 'capital-automation-chatcontexttext' }, zh.board.briefFailed),
4258
+ h('p', { className: 'capital-automation-askhint' }, brief?.error ?? zh.errorGeneric))
4259
+ } else if (status === 'skipped') {
4260
+ context = h('p', { className: 'capital-automation-chatcontexttext' }, zh.board.briefSkipped)
4261
+ } else {
4262
+ context = h('p', { className: 'capital-automation-chatcontexttext' }, zh.board.briefPending)
4263
+ }
4264
+ return h(Modal, {
4265
+ open,
4266
+ headless: true,
4267
+ onClose,
4268
+ title: zh.board.askDialogTitle,
4269
+ closeLabel: zh.close,
4270
+ className: 'capital-automation-modal capital-automation-modal-chat',
4271
+ },
4272
+ h('div', { className: 'capital-automation-chatshell' },
4273
+ h('header', { className: 'capital-automation-chathead' },
4274
+ h('button', {
4275
+ type: 'button',
4276
+ className: 'capital-automation-chaticonbtn',
4277
+ title: zh.close,
4278
+ 'aria-label': zh.close,
4279
+ onClick: onClose,
4280
+ }, h(IconCloseOutlineRegular, { size: 18 })),
4281
+ openSession
4282
+ ? h('button', {
4283
+ type: 'button',
4284
+ className: 'capital-automation-chaticonbtn',
4285
+ title: zh.openSession,
4286
+ 'aria-label': zh.openSession,
4287
+ onClick: openSession,
4288
+ }, h(IconRightUpOutlineRegular, { size: 18 }))
4289
+ : null),
4290
+ h('div', { className: 'capital-automation-chatscroll' },
4291
+ h('div', { className: 'capital-automation-chatcontext' },
4292
+ h(Glyph, { task: identity ?? card, size: 38, radius: 999, glyphSize: 18 }),
4293
+ h('div', { className: 'capital-automation-chatcontextbody' },
4294
+ h('div', { className: 'capital-automation-chatcontexthead' },
4295
+ h('strong', null, card.taskTitle),
4296
+ h('span', { className: 'capital-automation-chatcontextmeta' },
4297
+ `${categoryLabel(card.category)} · ${trigger} · `,
4298
+ h('time', { dateTime: card.finishedAt, title: exactTime }, relativeTime))),
4299
+ context)),
4300
+ ask !== null
4301
+ ? h('div', { className: 'capital-automation-chatthread' }, h(AskExchange, { key: ask.id, ask, api }))
4302
+ : h('div', { className: 'capital-automation-chatempty' },
4303
+ h('p', null, zh.board.askEmptyTitle)),
4304
+ error.length > 0 ? h('p', { className: 'capital-automation-askerror', role: 'alert' }, error) : null),
4305
+ h('form', { className: 'capital-automation-chatcomposer', onSubmit },
4306
+ h('input', {
4307
+ ref: inputRef,
4308
+ type: 'text',
4309
+ className: 'capital-automation-askinput',
4310
+ value: question,
4311
+ maxLength: 500,
4312
+ enterKeyHint: 'send',
4313
+ placeholder: running ? zh.board.askPending : zh.board.askPlaceholder,
4314
+ 'aria-label': zh.board.askLabel,
4315
+ disabled: busy || running,
4316
+ onChange: (event) => onQuestionChange(event.target.value),
4317
+ onKeyDown: (event) => {
4318
+ if (event.key === 'Enter' && event.nativeEvent?.isComposing === true) event.preventDefault()
4319
+ },
4320
+ }),
4321
+ h('button', {
4322
+ type: 'submit',
4323
+ className: 'capital-automation-btn capital-automation-chatsend',
4324
+ 'data-variant': 'primary',
4325
+ disabled: busy || running || question.trim().length === 0,
4326
+ }, busy ? zh.processing : zh.board.askSubmit))))
4327
+ }
4328
+
4329
+ function AskDock(props) {
4330
+ const { card, identity, api, onOpenSession, open, onClose } = props
4331
+ const [latest, setLatest] = useState(card.ask ?? null)
4332
+ const [question, setQuestion] = useState('')
4333
+ const [busy, setBusy] = useState(false)
4334
+ const [error, setError] = useState('')
4335
+ const incoming = card.ask ?? null
4336
+
4337
+ useEffect(() => {
4338
+ setLatest((current) => {
4339
+ // A board refresh can trail a just-created/resolved local ask; never drop or roll it back.
4340
+ if (incoming === null) return current
4341
+ if (current === null || current.id !== incoming.id) {
4342
+ if (current !== null && String(current.createdAt ?? '') > String(incoming.createdAt ?? '')) return current
4343
+ return incoming
4344
+ }
4345
+ if (current.status !== 'running' && incoming.status === 'running') return current
4346
+ return incoming
4347
+ })
4348
+ }, [incoming?.id, incoming?.status, incoming?.preview, incoming?.error])
4349
+
4350
+ useEffect(() => {
4351
+ if (!open) return
4352
+ setQuestion('')
4353
+ setError('')
4354
+ }, [open])
4355
+
4356
+ useEffect(() => {
4357
+ if (latest === null || latest.status !== 'ready' || typeof api?.askStatus !== 'function') return undefined
4358
+ if (typeof latest.preview !== 'string' || !latest.preview.endsWith('…') || Array.from(latest.preview).length > 80) return undefined
4359
+ let cancelled = false
4360
+ api.askStatus(latest.id).then((payload) => {
4361
+ if (!cancelled && payload?.ask) setLatest(payload.ask)
4362
+ }).catch(() => {})
4363
+ return () => {
4364
+ cancelled = true
4365
+ }
4366
+ }, [latest?.id, latest?.status, latest?.preview, api])
4367
+
4368
+ useEffect(() => {
4369
+ if (latest === null || latest.status !== 'running' || typeof api?.askStatus !== 'function') return undefined
4370
+ let cancelled = false
4371
+ let timer
4372
+ const poll = async () => {
4373
+ try {
4374
+ const payload = await api.askStatus(latest.id)
4375
+ if (cancelled) return
4376
+ if (payload?.ask) setLatest(payload.ask)
4377
+ } catch {
4378
+ // The dialog shows the actionable error; the card preview keeps its last known state.
4379
+ } finally {
4380
+ if (!cancelled) timer = setTimeout(poll, 2_000)
4381
+ }
4382
+ }
4383
+ void poll()
4384
+ return () => {
4385
+ cancelled = true
4386
+ clearTimeout(timer)
4387
+ }
4388
+ }, [latest?.id, latest?.status, api])
4389
+
4390
+ async function submit(event) {
4391
+ event.preventDefault()
4392
+ const text = question.trim()
4393
+ const running = latest?.status === 'running'
4394
+ if (text.length === 0 || busy || running) return
4395
+ if (typeof api?.askBrief !== 'function') {
4396
+ setError(zh.errorGeneric)
4397
+ return
4398
+ }
4399
+ setBusy(true)
4400
+ setError('')
4401
+ try {
4402
+ const payload = await api.askBrief(card.runId, text, browserTimeZone())
4403
+ if (payload?.ask) {
4404
+ setLatest(payload.ask)
4405
+ setQuestion('')
4406
+ } else {
4407
+ setError(zh.errorGeneric)
4408
+ }
4409
+ } catch (failure) {
4410
+ setError(failure?.message ?? zh.errorGeneric)
4411
+ } finally {
4412
+ setBusy(false)
4413
+ }
4414
+ }
4415
+
4416
+ const requestClose = () => {
4417
+ if (!busy) onClose()
4418
+ }
4419
+ const dialog = h(AskDialog, {
4420
+ open,
4421
+ onClose: requestClose,
4422
+ card,
4423
+ identity,
4424
+ ask: latest,
4425
+ api,
4426
+ question,
4427
+ onQuestionChange: setQuestion,
4428
+ onSubmit: submit,
4429
+ busy,
4430
+ error,
4431
+ onOpenSession,
4432
+ })
4433
+ if (latest === null) return dialog
4434
+ return h('div', { className: 'capital-automation-askdock' },
4435
+ h(AskExchange, { key: latest.id, ask: latest, api }),
4436
+ dialog)
4437
+ }
4438
+
4052
4439
  function BriefCard(props) {
4053
- const { card, onOpenSession, onRetry, retrying } = props
4440
+ const { card, task, api, onOpenSession, onRetry, retrying } = props
4441
+ const [askOpen, setAskOpen] = useState(false)
4442
+ // Older /board payloads omit icon/origin; the task list carries the same identity.
4443
+ const identity = typeof card.icon === 'string' ? card : (task ?? card)
4054
4444
  const brief = card.brief
4055
4445
  const status = brief?.status ?? 'pending'
4056
4446
  const titleId = `capital-automation-brief-${card.runId}`
@@ -4066,6 +4456,16 @@ function BriefCard(props) {
4066
4456
  onClick: openSession,
4067
4457
  }, h(IconRightUpOutlineRegular, { size: 14 }))
4068
4458
  : null
4459
+ const askIcon = sessionId
4460
+ ? h('button', {
4461
+ type: 'button',
4462
+ className: 'capital-automation-btn',
4463
+ 'data-size': 'icon',
4464
+ title: zh.board.askDialogTitle,
4465
+ 'aria-label': `${zh.board.askDialogTitle}:${card.taskTitle ?? ''}`,
4466
+ onClick: () => setAskOpen(true),
4467
+ }, h(IconNewChatOutlineRegular, { size: 14 }))
4468
+ : null
4069
4469
  const openLink = openSession
4070
4470
  ? h('button', { type: 'button', className: 'capital-automation-btn', 'data-size': 'sm', onClick: openSession }, zh.openSession)
4071
4471
  : null
@@ -4074,12 +4474,9 @@ function BriefCard(props) {
4074
4474
  const exactTime = formatTime(card.finishedAt)
4075
4475
  let body
4076
4476
  if (status === 'ready') {
4077
- body = h('div', null,
4477
+ body = h('div', { className: 'capital-automation-briefbody' },
4078
4478
  h('h4', null, brief.headline),
4079
- h('p', { className: 'capital-automation-brieftext' }, brief.plain),
4080
- h('div', { className: 'capital-automation-briefmeta' },
4081
- brief.coverage === 'partial' ? h('span', { className: 'capital-automation-briefpartial' }, zh.board.partial) : null,
4082
- h('span', { className: 'capital-automation-briefai' }, zh.board.aiBadge)))
4479
+ h('p', { className: 'capital-automation-brieftext' }, brief.plain))
4083
4480
  } else if (status === 'failed') {
4084
4481
  body = h('div', { className: 'capital-automation-briefstate', 'data-tone': 'error' },
4085
4482
  h('p', null, zh.board.briefFailed),
@@ -4107,6 +4504,7 @@ function BriefCard(props) {
4107
4504
  return h('article', { className: 'capital-automation-briefcard', 'data-status': status, 'aria-labelledby': titleId },
4108
4505
  h('div', { className: 'capital-automation-briefhead' },
4109
4506
  h('div', { className: 'capital-automation-brieftitle' },
4507
+ h(Glyph, { task: identity, size: 24, radius: 8, glyphSize: 14 }),
4110
4508
  h('h3', { id: titleId }, card.taskTitle),
4111
4509
  h('span', { className: 'capital-automation-tag', 'data-tone': card.category }, categoryLabel(card.category)),
4112
4510
  h('span', { className: 'capital-automation-tag' }, trigger),
@@ -4115,8 +4513,16 @@ function BriefCard(props) {
4115
4513
  dateTime: card.finishedAt,
4116
4514
  title: exactTime,
4117
4515
  }, relativeTime)),
4118
- openIcon),
4119
- body)
4516
+ h('div', { className: 'capital-automation-briefheadactions' }, askIcon, openIcon)),
4517
+ body,
4518
+ h(AskDock, {
4519
+ card,
4520
+ identity,
4521
+ api,
4522
+ onOpenSession,
4523
+ open: askOpen,
4524
+ onClose: () => setAskOpen(false),
4525
+ }))
4120
4526
  }
4121
4527
 
4122
4528
  function BoardSkeleton(props) {
@@ -4132,7 +4538,9 @@ function BoardSkeleton(props) {
4132
4538
  h('div', { className: 'capital-automation-boardgrid', 'data-rail': railOpen === true ? 'open' : 'closed' },
4133
4539
  h('section', { className: 'capital-automation-boardmain' },
4134
4540
  [0, 1].map((index) => h('div', { key: index, className: 'capital-automation-briefcard' },
4135
- h(SkeletonBlock, { width: '48%', height: 12 }),
4541
+ h('div', { className: 'capital-automation-brieftitle' },
4542
+ h(SkeletonBlock, { width: 24, height: 24, radius: 8 }),
4543
+ h(SkeletonBlock, { width: '48%', height: 12 })),
4136
4544
  h(SkeletonBlock, { width: '80%', height: 16 }),
4137
4545
  h(SkeletonBlock, { width: '100%', height: 10 }),
4138
4546
  h(SkeletonBlock, { width: '92%', height: 10 })))),
@@ -4146,7 +4554,7 @@ function BoardSkeleton(props) {
4146
4554
  }
4147
4555
 
4148
4556
  function BriefFeed(props) {
4149
- const { cards, loading, error, onOpenSession, onRetry, retryingRunId, onViewAll, onClearFilter, onLoadMore, hasMore, loadingMore, railOpen } = props
4557
+ const { cards, tasks, api, loading, error, onOpenSession, onRetry, retryingRunId, onViewAll, onClearFilter, onLoadMore, hasMore, loadingMore, railOpen } = props
4150
4558
  if (loading === true) return h(BoardSkeleton, { railOpen })
4151
4559
  if (typeof error === 'string' && error.length > 0) {
4152
4560
  return h('section', { className: 'capital-automation-boardmain', id: 'capital-automation-briefs' },
@@ -4162,10 +4570,13 @@ function BriefFeed(props) {
4162
4570
  onViewAll ? h('button', { type: 'button', className: 'capital-automation-btn', onClick: onViewAll }, zh.board.viewAll) : null,
4163
4571
  onClearFilter ? h('button', { type: 'button', className: 'capital-automation-btn', onClick: onClearFilter }, zh.board.clearFilter) : null)))
4164
4572
  }
4573
+ const taskById = new Map((Array.isArray(tasks) ? tasks : []).map((task) => [task.id, task]))
4165
4574
  return h('section', { className: 'capital-automation-boardmain', id: 'capital-automation-briefs', 'aria-label': zh.board.briefTitle },
4166
4575
  cards.map((card) => h(BriefCard, {
4167
4576
  key: card.runId,
4168
4577
  card,
4578
+ task: taskById.get(card.taskId),
4579
+ api,
4169
4580
  onOpenSession,
4170
4581
  onRetry,
4171
4582
  retrying: retryingRunId === card.runId,
@@ -4224,7 +4635,16 @@ function TodoRow(props) {
4224
4635
  source
4225
4636
  ? h('div', { className: 'capital-automation-todosource' },
4226
4637
  h('span', null, `${zh.board.sourceRun}:${source.taskTitle} · ${formatShortTime(source.finishedAt)}`),
4227
- source.sessionId ? h('button', { type: 'button', className: 'capital-automation-btn', 'data-size': 'sm', onClick: () => onOpenSession(source.sessionId) }, zh.openSession) : null)
4638
+ source.sessionId
4639
+ ? h('button', {
4640
+ type: 'button',
4641
+ className: 'capital-automation-btn',
4642
+ 'data-size': 'icon',
4643
+ title: zh.openSession,
4644
+ 'aria-label': zh.openSession,
4645
+ onClick: () => onOpenSession(source.sessionId),
4646
+ }, h(IconRightUpOutlineRegular, { size: 14 }))
4647
+ : null)
4228
4648
  : null)
4229
4649
  : null)
4230
4650
  }
@@ -4469,7 +4889,7 @@ function RunHealthPanel(props) {
4469
4889
 
4470
4890
  function BoardPage(props) {
4471
4891
  const {
4472
- board, loading, error, range, category, onRange, onCategory, onRefresh,
4892
+ board, tasks, api, loading, error, range, category, onRange, onCategory, onRefresh,
4473
4893
  onOpenSession, onRetryBrief, retryingRunId, onLoadMore, loadingMore, onGoTasks, onNewTask, onGoRuns,
4474
4894
  onAckTodo, ackingTodoId, hasActiveTasks, storageReady,
4475
4895
  } = props
@@ -4554,6 +4974,8 @@ function BoardPage(props) {
4554
4974
  },
4555
4975
  h(BriefFeed, {
4556
4976
  cards: board?.cards ?? [],
4977
+ tasks,
4978
+ api,
4557
4979
  loading: loading === true && board === null,
4558
4980
  error: '',
4559
4981
  onOpenSession,
@@ -4619,6 +5041,8 @@ function AutomationPage(props) {
4619
5041
  const [ackingTodoId, setAckingTodoId] = useState(null)
4620
5042
  const [boardLoadingMore, setBoardLoadingMore] = useState(false)
4621
5043
  const [unread, setUnread] = useState(0)
5044
+ const [tasksReady, setTasksReady] = useState(false)
5045
+ const [runsReady, setRunsReady] = useState(false)
4622
5046
  const [selectedId, setSelectedId] = useState(null)
4623
5047
  const [detail, setDetail] = useState(null)
4624
5048
  const [tab, setTab] = useState('board')
@@ -4634,12 +5058,23 @@ function AutomationPage(props) {
4634
5058
  const [loadError, setLoadError] = useState('')
4635
5059
  const mountedRef = useRef(false)
4636
5060
  const tasksRef = useRef([])
5061
+ const tabRef = useRef('board')
5062
+ const inboxRef = useRef(false)
4637
5063
  const selectedIdRef = useRef(null)
4638
5064
  const refreshInFlightRef = useRef(null)
5065
+ const metaInFlightRef = useRef(null)
5066
+ const tasksInFlightRef = useRef(null)
5067
+ const runsInFlightRef = useRef(null)
5068
+ const notificationsInFlightRef = useRef(null)
4639
5069
  const refreshSequenceRef = useRef(0)
4640
5070
  const detailSequenceRef = useRef(0)
4641
5071
  const boardSequenceRef = useRef(0)
4642
5072
  const scrollRef = useRef(null)
5073
+ const mountedAtRef = useRef(typeof performance === 'undefined' ? 0 : performance.now())
5074
+ const timingRecordedRef = useRef(false)
5075
+ // Polls and visibility wake-ups close over the first render; the current tab must be a ref.
5076
+ tabRef.current = tab
5077
+ inboxRef.current = inbox
4643
5078
 
4644
5079
  useEffect(() => {
4645
5080
  if (notice.length === 0) return undefined
@@ -4647,44 +5082,126 @@ function AutomationPage(props) {
4647
5082
  return () => clearTimeout(timer)
4648
5083
  }, [notice])
4649
5084
 
4650
- async function refresh() {
4651
- if (refreshInFlightRef.current !== null) return refreshInFlightRef.current
4652
- const requestSequence = refreshSequenceRef.current + 1
4653
- refreshSequenceRef.current = requestSequence
5085
+ async function loadMeta() {
5086
+ if (metaInFlightRef.current !== null) return metaInFlightRef.current
5087
+ const request = (async () => {
5088
+ try {
5089
+ const value = await api.meta()
5090
+ if (!mountedRef.current) return
5091
+ setMeta(value)
5092
+ if (typeof value?.notifications?.unread === 'number') setUnread(value.notifications.unread)
5093
+ setLoadError('')
5094
+ } catch (error) {
5095
+ if (mountedRef.current) setLoadError(error.message ?? zh.errorGeneric)
5096
+ }
5097
+ })()
5098
+ metaInFlightRef.current = request
5099
+ try {
5100
+ await request
5101
+ } finally {
5102
+ if (metaInFlightRef.current === request) metaInFlightRef.current = null
5103
+ }
5104
+ }
5105
+
5106
+ function reconcileSelection(nextTaskList) {
5107
+ const currentId = selectedIdRef.current
5108
+ const nextId = currentId !== null && nextTaskList.some((task) => task.id === currentId) ? currentId : null
5109
+ if (nextId === currentId) return
5110
+ selectedIdRef.current = nextId
5111
+ detailSequenceRef.current += 1
5112
+ setDetail(null)
5113
+ setSelectedId(nextId)
5114
+ if (nextId === null) setDetailTab('overview')
5115
+ }
5116
+
5117
+ async function loadTasks() {
5118
+ if (tasksInFlightRef.current !== null) return tasksInFlightRef.current
5119
+ const request = (async () => {
5120
+ try {
5121
+ const body = await api.tasks()
5122
+ if (!mountedRef.current) return
5123
+ const nextTaskList = Array.isArray(body.tasks) ? body.tasks : []
5124
+ tasksRef.current = nextTaskList
5125
+ setTasks(nextTaskList)
5126
+ reconcileSelection(nextTaskList)
5127
+ setLoadError('')
5128
+ } catch (error) {
5129
+ if (mountedRef.current) setLoadError(error.message ?? zh.errorGeneric)
5130
+ } finally {
5131
+ if (mountedRef.current) setTasksReady(true)
5132
+ }
5133
+ })()
5134
+ tasksInFlightRef.current = request
5135
+ try {
5136
+ await request
5137
+ } finally {
5138
+ if (tasksInFlightRef.current === request) tasksInFlightRef.current = null
5139
+ }
5140
+ }
5141
+
5142
+ async function loadRuns() {
5143
+ if (runsInFlightRef.current !== null) return runsInFlightRef.current
4654
5144
  const request = (async () => {
4655
5145
  try {
4656
- const [nextMeta, nextTasks, nextRuns, nextHistory, nextNotifications] = await Promise.all([
4657
- api.meta(),
4658
- api.tasks(),
5146
+ const [nextRuns, nextHistory] = await Promise.all([
4659
5147
  api.runs('?limit=200'),
4660
5148
  api.history(`?days=${HISTORY_DAYS}&tz=${encodeURIComponent(browserTimeZone())}`),
4661
- api.notifications(),
4662
5149
  ])
4663
- if (!mountedRef.current || requestSequence !== refreshSequenceRef.current) return
4664
- const nextTaskList = Array.isArray(nextTasks.tasks) ? nextTasks.tasks : []
4665
- setMeta(nextMeta)
4666
- tasksRef.current = nextTaskList
4667
- setTasks(nextTaskList)
5150
+ if (!mountedRef.current) return
4668
5151
  setRuns(Array.isArray(nextRuns.runs) ? nextRuns.runs : [])
4669
5152
  setHistory(nextHistory ?? null)
4670
- setNotifications(Array.isArray(nextNotifications.notifications) ? nextNotifications.notifications : [])
4671
- setUnread(typeof nextNotifications.unread === 'number' ? nextNotifications.unread : 0)
4672
5153
  setLoadError('')
4673
- const currentId = selectedIdRef.current
4674
- const nextId = currentId !== null && nextTaskList.some((task) => task.id === currentId) ? currentId : null
4675
- if (nextId !== currentId) {
4676
- selectedIdRef.current = nextId
4677
- detailSequenceRef.current += 1
4678
- setDetail(null)
4679
- setSelectedId(nextId)
4680
- if (nextId === null) setDetailTab('overview')
4681
- }
4682
5154
  } catch (error) {
4683
- if (mountedRef.current && requestSequence === refreshSequenceRef.current) {
4684
- setLoadError(error.message ?? zh.errorGeneric)
4685
- }
5155
+ if (mountedRef.current) setLoadError(error.message ?? zh.errorGeneric)
5156
+ } finally {
5157
+ if (mountedRef.current) setRunsReady(true)
5158
+ }
5159
+ })()
5160
+ runsInFlightRef.current = request
5161
+ try {
5162
+ await request
5163
+ } finally {
5164
+ if (runsInFlightRef.current === request) runsInFlightRef.current = null
5165
+ }
5166
+ }
5167
+
5168
+ async function loadNotifications() {
5169
+ if (notificationsInFlightRef.current !== null) return notificationsInFlightRef.current
5170
+ const request = (async () => {
5171
+ try {
5172
+ const body = await api.notifications()
5173
+ if (!mountedRef.current) return
5174
+ setNotifications(Array.isArray(body.notifications) ? body.notifications : [])
5175
+ setUnread(typeof body.unread === 'number' ? body.unread : 0)
5176
+ setLoadError('')
5177
+ } catch (error) {
5178
+ if (mountedRef.current) setLoadError(error.message ?? zh.errorGeneric)
4686
5179
  }
4687
5180
  })()
5181
+ notificationsInFlightRef.current = request
5182
+ try {
5183
+ await request
5184
+ } finally {
5185
+ if (notificationsInFlightRef.current === request) notificationsInFlightRef.current = null
5186
+ }
5187
+ }
5188
+
5189
+ /**
5190
+ * Fetches the page shell plus the visible slice only. Tasks, runs and notifications belong
5191
+ * to their tabs and loaders and are fetched when that tab is opened.
5192
+ */
5193
+ async function refresh() {
5194
+ if (refreshInFlightRef.current !== null) return refreshInFlightRef.current
5195
+ const requestSequence = refreshSequenceRef.current + 1
5196
+ refreshSequenceRef.current = requestSequence
5197
+ const request = (async () => {
5198
+ const pending = [loadMeta()]
5199
+ if (selectedIdRef.current !== null || tabRef.current === 'tasks') pending.push(loadTasks())
5200
+ if (tabRef.current === 'runs') pending.push(loadRuns())
5201
+ if (inboxRef.current) pending.push(loadNotifications())
5202
+ await Promise.all(pending)
5203
+ if (!mountedRef.current || requestSequence !== refreshSequenceRef.current) return
5204
+ })()
4688
5205
  refreshInFlightRef.current = request
4689
5206
  try {
4690
5207
  await request
@@ -4694,14 +5211,25 @@ function AutomationPage(props) {
4694
5211
  }
4695
5212
 
4696
5213
  async function loadBoard(nextRange = boardRange, nextCategory = boardCategory, before = null) {
5214
+ const query = boardQueryOf(nextRange, nextCategory, before)
5215
+ const snapshot = before === null ? readBoardSnapshot(query) : null
4697
5216
  const requestSequence = boardSequenceRef.current + 1
4698
5217
  boardSequenceRef.current = requestSequence
4699
- if (before === null) setBoardLoading(true)
5218
+ if (before === null) {
5219
+ // A cached board paints immediately; the request below still revalidates it.
5220
+ if (snapshot === null) setBoardLoading(true)
5221
+ else {
5222
+ setBoard(snapshot)
5223
+ setBoardLoading(false)
5224
+ }
5225
+ }
4700
5226
  try {
4701
- const value = await api.board(boardQueryOf(nextRange, nextCategory, before))
5227
+ const value = await api.board(query)
4702
5228
  if (!mountedRef.current || requestSequence !== boardSequenceRef.current) return
4703
- if (before === null) setBoard(value)
4704
- else setBoard((current) => current === null
5229
+ if (before === null) {
5230
+ setBoard(value)
5231
+ writeBoardSnapshot(query, value)
5232
+ } else setBoard((current) => current === null
4705
5233
  ? value
4706
5234
  : { ...value, cards: [...current.cards, ...value.cards] })
4707
5235
  setBoardError('')
@@ -4892,6 +5420,7 @@ function AutomationPage(props) {
4892
5420
  setInboxBusy(true)
4893
5421
  try {
4894
5422
  await api.markRead({ all: true })
5423
+ setUnread(0)
4895
5424
  setNotice(zh.markReadDone)
4896
5425
  await refresh()
4897
5426
  } catch (failure) {
@@ -4901,14 +5430,14 @@ function AutomationPage(props) {
4901
5430
  }
4902
5431
  }
4903
5432
 
5433
+ async function openTaskById(taskId) {
5434
+ if (!tasksRef.current.some((task) => task.id === taskId)) await loadTasks()
5435
+ if (tasksRef.current.some((task) => task.id === taskId)) selectTask(taskId)
5436
+ }
5437
+
4904
5438
  async function openTaskFromNotification(taskId) {
4905
5439
  setInbox(false)
4906
- if (tasksRef.current.some((task) => task.id === taskId)) {
4907
- selectTask(taskId)
4908
- return
4909
- }
4910
- await refresh()
4911
- if (tasksRef.current.some((task) => task.id === taskId)) selectTask(taskId)
5440
+ await openTaskById(taskId)
4912
5441
  }
4913
5442
 
4914
5443
  useEffect(() => {
@@ -4916,7 +5445,7 @@ function AutomationPage(props) {
4916
5445
  void refresh()
4917
5446
  const timer = setInterval(() => {
4918
5447
  if (document.visibilityState !== 'hidden') void refresh()
4919
- }, 15_000)
5448
+ }, 30_000)
4920
5449
  const onVisibilityChange = () => {
4921
5450
  if (document.visibilityState === 'visible') void refresh()
4922
5451
  }
@@ -4931,6 +5460,33 @@ function AutomationPage(props) {
4931
5460
  }
4932
5461
  }, [])
4933
5462
 
5463
+ useEffect(() => {
5464
+ if (tab === 'tasks') {
5465
+ void loadMeta()
5466
+ void loadTasks()
5467
+ } else if (tab === 'runs') {
5468
+ void loadMeta()
5469
+ void loadRuns()
5470
+ }
5471
+ return undefined
5472
+ }, [tab])
5473
+
5474
+ useEffect(() => {
5475
+ if (inbox) void loadNotifications()
5476
+ return undefined
5477
+ }, [inbox])
5478
+
5479
+ // A restart hands the lease over only after the previous owner's 90s lease expires, and the
5480
+ // scheduler retries on its next tick. While standby, poll the shell faster so the banner
5481
+ // clears itself instead of waiting for the normal 30s refresh.
5482
+ useEffect(() => {
5483
+ if (meta?.scheduler?.state !== 'standby') return undefined
5484
+ const timer = setInterval(() => {
5485
+ if (document.visibilityState !== 'hidden') void loadMeta()
5486
+ }, 10_000)
5487
+ return () => clearInterval(timer)
5488
+ }, [meta?.scheduler?.state])
5489
+
4934
5490
  useEffect(() => {
4935
5491
  if (tab !== 'board') return undefined
4936
5492
  void loadBoard(boardRange, boardCategory)
@@ -4959,6 +5515,25 @@ function AutomationPage(props) {
4959
5515
  return () => { detailSequenceRef.current += 1 }
4960
5516
  }, [selectedId])
4961
5517
 
5518
+ // Read-only diagnostics: `window.__CA_LAST_TIMING__` separates shell cost (click → mount)
5519
+ // from this page's cost (mount → board painted).
5520
+ useEffect(() => {
5521
+ if (board === null || timingRecordedRef.current) return undefined
5522
+ if (typeof window === 'undefined' || typeof requestAnimationFrame !== 'function') return undefined
5523
+ const frame = requestAnimationFrame(() => {
5524
+ const mountedAt = mountedAtRef.current
5525
+ if (mountedAt === 0) return
5526
+ timingRecordedRef.current = true
5527
+ const elapsed = performance.now() - mountedAt
5528
+ window.__CA_LAST_TIMING__ = {
5529
+ clickToMountMs: lastClickAt > 0 && mountedAt - lastClickAt < 30_000 ? Math.round(mountedAt - lastClickAt) : null,
5530
+ mountToBoardMs: Math.round(elapsed),
5531
+ at: new Date().toISOString(),
5532
+ }
5533
+ })
5534
+ return () => cancelAnimationFrame(frame)
5535
+ }, [board])
5536
+
4962
5537
  const schedulerActive = meta?.scheduler?.state === 'active'
4963
5538
  const storageReady = meta?.storage?.state !== 'unavailable'
4964
5539
  const templates = tasks
@@ -4966,8 +5541,11 @@ function AutomationPage(props) {
4966
5541
  .sort(compareTemplates)
4967
5542
  const selectedTask = tasks.find((task) => task.id === selectedId)
4968
5543
  const detailOpen = tab === 'tasks' && selectedId !== null
4969
- // `/meta` arrives in the same batch as `/tasks`; until then the empty state would be a lie.
5544
+ // The shell (`/meta`) and the board are the entry payload; other tabs report "loading"
5545
+ // until their first lazy fetch lands, so an unvisited tab never shows a false empty state.
4970
5546
  const initialLoading = meta === null && loadError.length === 0
5547
+ const tasksPending = initialLoading || !tasksReady
5548
+ const runsPending = initialLoading || !runsReady
4971
5549
 
4972
5550
  return h('div', { className: 'capital-automation-page' },
4973
5551
  detailOpen ? null : h(Header, {
@@ -4983,6 +5561,8 @@ function AutomationPage(props) {
4983
5561
  tab === 'board'
4984
5562
  ? h(BoardPage, {
4985
5563
  board,
5564
+ tasks,
5565
+ api,
4986
5566
  loading: boardLoading,
4987
5567
  error: boardError,
4988
5568
  range: boardRange,
@@ -5026,7 +5606,7 @@ function AutomationPage(props) {
5026
5606
  if (id !== null && selectedIdRef.current === id) await loadDetail(id)
5027
5607
  },
5028
5608
  }))
5029
- : initialLoading
5609
+ : tasksPending
5030
5610
  ? h(TaskDashboardSkeleton)
5031
5611
  : h(TaskDashboard, {
5032
5612
  tasks,
@@ -5043,7 +5623,7 @@ function AutomationPage(props) {
5043
5623
  storageReady,
5044
5624
  busyTaskId,
5045
5625
  })
5046
- : initialLoading
5626
+ : runsPending
5047
5627
  ? h(RunsSkeleton)
5048
5628
  : h(RunsPage, {
5049
5629
  runs,
@@ -5051,7 +5631,7 @@ function AutomationPage(props) {
5051
5631
  tasks,
5052
5632
  onCancel: (run) => requestConfirm('cancel-run', { id: run.taskId, title: run.taskTitle }, run),
5053
5633
  onOpenSession: openSession,
5054
- onOpenTask: (id) => { if (tasksRef.current.some((task) => task.id === id)) selectTask(id) },
5634
+ onOpenTask: (id) => { void openTaskById(id) },
5055
5635
  onGoTasks: () => switchTab('tasks'),
5056
5636
  onNewTask: () => setWizard(true),
5057
5637
  busy: confirmBusy,
@@ -5064,7 +5644,7 @@ function AutomationPage(props) {
5064
5644
  onCreated: async (taskId) => {
5065
5645
  setWizard(false)
5066
5646
  setNotice(zh.created)
5067
- await refresh()
5647
+ await loadTasks()
5068
5648
  if (taskId !== null && tasksRef.current.some((task) => task.id === taskId)) selectTask(taskId)
5069
5649
  },
5070
5650
  }),
@@ -5101,6 +5681,13 @@ function apply(ctx) {
5101
5681
  }
5102
5682
  }
5103
5683
  ctx.effect(() => installStyles(), `${ENTRY_NAME}: styles`)
5684
+ // Warm the default board while the app idles so the first open has no data wait. A page
5685
+ // that opens later still revalidates; a page that never opens costs one request.
5686
+ if (typeof window !== 'undefined' && typeof location !== 'undefined') {
5687
+ const startWarm = () => { void api.warm() }
5688
+ if (typeof requestIdleCallback === 'function') requestIdleCallback(startWarm, { timeout: 4_000 })
5689
+ else setTimeout(startWarm, 2_000)
5690
+ }
5104
5691
  ctx.slots.inject('main', () => ctx.slots.register({
5105
5692
  name: 'main',
5106
5693
  key: PANEL_ID,