@keyou007/agent-bot 0.1.25-alpha.0 → 0.1.25-alpha.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 (103) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +60 -5
  3. package/README.zh.md +60 -5
  4. package/config.example.yaml +1 -3
  5. package/dist/cli/controlProtocol.js.map +1 -1
  6. package/dist/cli/help.js +14 -0
  7. package/dist/cli/help.js.map +1 -1
  8. package/dist/cli.js +32 -0
  9. package/dist/cli.js.map +1 -1
  10. package/dist/codex/CodexRuntime.js +15 -5
  11. package/dist/codex/CodexRuntime.js.map +1 -1
  12. package/dist/commands/CommandRouter.js +7 -0
  13. package/dist/commands/CommandRouter.js.map +1 -1
  14. package/dist/config/SettingsStore.js +341 -0
  15. package/dist/config/SettingsStore.js.map +1 -0
  16. package/dist/config/loadConfig.js +1 -2
  17. package/dist/config/loadConfig.js.map +1 -1
  18. package/dist/config/schema.js +0 -1
  19. package/dist/config/schema.js.map +1 -1
  20. package/dist/console/ConsoleTurnPresenter.js +3 -0
  21. package/dist/console/ConsoleTurnPresenter.js.map +1 -1
  22. package/dist/feishu/CardRenderer.js +32 -96
  23. package/dist/feishu/CardRenderer.js.map +1 -1
  24. package/dist/feishu/FeishuConnector.js +9 -0
  25. package/dist/feishu/FeishuConnector.js.map +1 -1
  26. package/dist/feishu/FeishuMessageClient.js +35 -14
  27. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  28. package/dist/feishu/FeishuTurnPresenter.js +36 -23
  29. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  30. package/dist/feishu/LocalCardImage.js.map +1 -1
  31. package/dist/feishu/LocalImageMarkdown.js +59 -3
  32. package/dist/feishu/LocalImageMarkdown.js.map +1 -1
  33. package/dist/feishu/SettingsCard.js +199 -0
  34. package/dist/feishu/SettingsCard.js.map +1 -0
  35. package/dist/index.js +17 -6
  36. package/dist/index.js.map +1 -1
  37. package/dist/local-files/TurnPreviewPage.js +8 -4
  38. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  39. package/dist/presentation/TurnStateReducer.js +21 -2
  40. package/dist/presentation/TurnStateReducer.js.map +1 -1
  41. package/dist/presentation/turnStatus.js +34 -0
  42. package/dist/presentation/turnStatus.js.map +1 -0
  43. package/dist/proxy/ProxySessionController.js +688 -153
  44. package/dist/proxy/ProxySessionController.js.map +1 -1
  45. package/dist/runtime/submissionErrors.js +15 -0
  46. package/dist/runtime/submissionErrors.js.map +1 -0
  47. package/dist/scheduling/ScheduleCards.js +240 -0
  48. package/dist/scheduling/ScheduleCards.js.map +1 -0
  49. package/dist/scheduling/ScheduleCommand.js +67 -0
  50. package/dist/scheduling/ScheduleCommand.js.map +1 -0
  51. package/dist/scheduling/ScheduledTaskStore.js +226 -0
  52. package/dist/scheduling/ScheduledTaskStore.js.map +1 -0
  53. package/dist/scheduling/TaskScheduler.js +132 -0
  54. package/dist/scheduling/TaskScheduler.js.map +1 -0
  55. package/dist/scheduling/types.js +89 -0
  56. package/dist/scheduling/types.js.map +1 -0
  57. package/dist/state/ExecutionProvenanceStore.js +58 -0
  58. package/dist/state/ExecutionProvenanceStore.js.map +1 -0
  59. package/dist/state/StateStore.js +145 -45
  60. package/dist/state/StateStore.js.map +1 -1
  61. package/dist/state/migrations.js +37 -0
  62. package/dist/state/migrations.js.map +1 -1
  63. package/dist/supervision/SafeRestartNotifier.js +1 -1
  64. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  65. package/docs/technical-reference.md +11 -8
  66. package/docs/technical-reference.zh.md +11 -8
  67. package/npm-shrinkwrap.json +24 -2
  68. package/package.json +2 -1
  69. package/skills/agent-bot/SKILL.md +33 -3
  70. package/src/cli/controlProtocol.ts +1 -0
  71. package/src/cli/help.ts +14 -0
  72. package/src/cli.ts +25 -0
  73. package/src/codex/CodexRuntime.ts +14 -5
  74. package/src/commands/CommandRouter.ts +7 -0
  75. package/src/commands/commandTypes.ts +2 -0
  76. package/src/config/SettingsStore.ts +588 -0
  77. package/src/config/loadConfig.ts +1 -2
  78. package/src/config/schema.ts +0 -1
  79. package/src/console/ConsoleTurnPresenter.ts +2 -0
  80. package/src/feishu/CardRenderer.ts +33 -110
  81. package/src/feishu/FeishuConnector.ts +9 -0
  82. package/src/feishu/FeishuMessageClient.ts +39 -17
  83. package/src/feishu/FeishuTurnPresenter.ts +33 -22
  84. package/src/feishu/LocalCardImage.ts +0 -1
  85. package/src/feishu/LocalImageMarkdown.ts +54 -3
  86. package/src/feishu/SettingsCard.ts +231 -0
  87. package/src/index.ts +17 -6
  88. package/src/local-files/TurnPreviewPage.ts +8 -4
  89. package/src/presentation/TurnStateReducer.ts +21 -2
  90. package/src/presentation/turnStatus.ts +38 -0
  91. package/src/presentation/turnViewTypes.ts +3 -0
  92. package/src/proxy/ProxySessionController.ts +628 -152
  93. package/src/runtime/submissionErrors.ts +15 -0
  94. package/src/runtime/types.ts +1 -0
  95. package/src/scheduling/ScheduleCards.ts +317 -0
  96. package/src/scheduling/ScheduleCommand.ts +76 -0
  97. package/src/scheduling/ScheduledTaskStore.ts +332 -0
  98. package/src/scheduling/TaskScheduler.ts +171 -0
  99. package/src/scheduling/types.ts +151 -0
  100. package/src/state/ExecutionProvenanceStore.ts +100 -0
  101. package/src/state/StateStore.ts +167 -44
  102. package/src/state/migrations.ts +37 -0
  103. package/src/supervision/SafeRestartNotifier.ts +1 -1
@@ -0,0 +1,231 @@
1
+ import {
2
+ SETTINGS_SECTIONS,
3
+ type SettingsField,
4
+ type SettingsSnapshot,
5
+ } from "../config/SettingsStore.js";
6
+
7
+ const plain = (content: string) => ({ tag: "plain_text", content });
8
+ const md = (content: string) => ({ tag: "markdown", content });
9
+ const button = (
10
+ content: string,
11
+ value: Record<string, string>,
12
+ type = "default",
13
+ ) => ({ tag: "button", text: plain(content), type, value });
14
+ const row = (columns: unknown[][], weighted = false) => ({
15
+ tag: "column_set",
16
+ flex_mode: weighted ? "none" : "flow",
17
+ horizontal_spacing: "12px",
18
+ columns: columns.map((elements) => ({
19
+ tag: "column",
20
+ width: weighted ? "weighted" : "auto",
21
+ ...(weighted ? { weight: 1 } : {}),
22
+ vertical_align: "center",
23
+ elements,
24
+ })),
25
+ });
26
+ const link = (title: string, value: Record<string, string>) => ({
27
+ tag: "interactive_container",
28
+ padding: "4px 0px",
29
+ margin: "0px",
30
+ has_border: false,
31
+ elements: [md(title)],
32
+ behaviors: [{ type: "callback", value }],
33
+ });
34
+
35
+ const NOTES = {
36
+ general: "默认值仅影响新任务;群消息响应仍受 /mute 与飞书权限限制。",
37
+ agents: "仅影响新任务,继承的任务设置优先。",
38
+ naming:
39
+ "仅影响新群。必须包含一个 {taskname};可用 {agent}、{project}、{os}、{date}。",
40
+ services: "终端与预览共用地址;更改地址或端口可能使旧链接失效。",
41
+ };
42
+
43
+ const PAIRED_FIELDS: Record<string, string> = {
44
+ ownerOnly: "allGroupMessages",
45
+ reasoningEffort: "permissionMode",
46
+ host: "port",
47
+ };
48
+
49
+ function renderField(
50
+ entry: SettingsField,
51
+ value: string | boolean | number,
52
+ callback: Record<string, string>,
53
+ ): unknown[] {
54
+ const behaviors = [{ type: "callback", value: callback }];
55
+ if (entry.kind === "boolean")
56
+ return [
57
+ {
58
+ tag: "checker",
59
+ name: entry.name,
60
+ checked: value === true,
61
+ text: plain(entry.label),
62
+ overall_checkable: true,
63
+ behaviors,
64
+ },
65
+ ];
66
+ const label = md(entry.label);
67
+ if (entry.kind === "select")
68
+ return [
69
+ label,
70
+ {
71
+ tag: "select_static",
72
+ name: entry.name,
73
+ behaviors,
74
+ width: "fill",
75
+ initial_option: String(value) || "__agent_default__",
76
+ options: (entry.options ?? []).map((item) => ({
77
+ text: plain(item.label),
78
+ value: item.value || "__agent_default__",
79
+ })),
80
+ },
81
+ ];
82
+ return [
83
+ label,
84
+ {
85
+ tag: "input",
86
+ name: entry.name,
87
+ default_value: String(value),
88
+ behaviors,
89
+ input_type: "text",
90
+ ...(entry.kind === "number"
91
+ ? { placeholder: plain("0:自动分配并复用") }
92
+ : {}),
93
+ width: "fill",
94
+ max_length: entry.kind === "number" ? 5 : 1000,
95
+ },
96
+ ];
97
+ }
98
+
99
+ export function renderSettingsCard(
100
+ snapshot: SettingsSnapshot,
101
+ contextKey: string,
102
+ notice?: string,
103
+ ): Record<string, unknown> {
104
+ const common = {
105
+ contextKey,
106
+ section: snapshot.section,
107
+ ...(snapshot.agentName ? { agentName: snapshot.agentName } : {}),
108
+ };
109
+ const navigation = row(
110
+ Object.entries(SETTINGS_SECTIONS).map(([section, title]) => [
111
+ link(
112
+ section === snapshot.section
113
+ ? `**${title}**`
114
+ : `<font color='blue'>${title}</font>`,
115
+ { action: "bot_settings_show", contextKey, section },
116
+ ),
117
+ ]),
118
+ true,
119
+ );
120
+ const elements: unknown[] = [
121
+ {
122
+ tag: "column_set",
123
+ flex_mode: "none",
124
+ horizontal_spacing: "16px",
125
+ columns: [
126
+ { tag: "column", width: "weighted", weight: 1, elements: [navigation] },
127
+ {
128
+ tag: "column",
129
+ width: "auto",
130
+ elements: [
131
+ link("<font color='grey'>刷新</font>", {
132
+ ...common,
133
+ action: "bot_settings_show",
134
+ }),
135
+ ],
136
+ },
137
+ ],
138
+ },
139
+ { tag: "hr" },
140
+ ];
141
+ if (snapshot.section === "agents" && snapshot.agents.length > 1)
142
+ elements.push({
143
+ tag: "select_static",
144
+ placeholder: plain("选择 Agent"),
145
+ initial_option: snapshot.agentName,
146
+ width: "fill",
147
+ options: snapshot.agents.map((agent) => ({
148
+ text: plain(`${agent.title} (${agent.name})`),
149
+ value: agent.name,
150
+ })),
151
+ behaviors: [
152
+ {
153
+ type: "callback",
154
+ value: {
155
+ action: "bot_settings_agent",
156
+ contextKey,
157
+ section: "agents",
158
+ },
159
+ },
160
+ ],
161
+ });
162
+ if (snapshot.warning) elements.push(md(`> ${snapshot.warning}`));
163
+ const controlsFor = (entry: SettingsField) =>
164
+ renderField(entry, snapshot.values[entry.name]!, {
165
+ ...common,
166
+ action: "bot_settings_change",
167
+ field: entry.name,
168
+ revision: snapshot.fieldRevisions[entry.name]!,
169
+ });
170
+ for (let index = 0; index < snapshot.fields.length; index++) {
171
+ const entry = snapshot.fields[index]!;
172
+ const controls = controlsFor(entry);
173
+ const next = snapshot.fields[index + 1];
174
+ if (next && PAIRED_FIELDS[entry.name] === next.name) {
175
+ elements.push(row([controls, controlsFor(next)], true));
176
+ index++;
177
+ } else {
178
+ elements.push(...controls);
179
+ }
180
+ }
181
+ elements.push(
182
+ { tag: "hr" },
183
+ {
184
+ tag: "column_set",
185
+ flex_mode: "none",
186
+ horizontal_spacing: "12px",
187
+ columns: [
188
+ {
189
+ tag: "column",
190
+ width: "weighted",
191
+ weight: 1,
192
+ vertical_align: "center",
193
+ elements: [
194
+ md(
195
+ notice ??
196
+ (snapshot.pendingRestart
197
+ ? "<font color='orange'>已保存,待安全重启生效</font>"
198
+ : "自动保存,安全重启后生效"),
199
+ ),
200
+ ],
201
+ },
202
+ {
203
+ tag: "column",
204
+ width: "auto",
205
+ elements: [
206
+ {
207
+ ...button("安全重启", {
208
+ ...common,
209
+ action: "bot_settings_restart",
210
+ }),
211
+ confirm: {
212
+ title: plain("安全重启 Agent Bot?"),
213
+ text: plain("等待活跃任务、终端和结果投递完成后重启。"),
214
+ },
215
+ },
216
+ ],
217
+ },
218
+ ],
219
+ },
220
+ md(`> ${NOTES[snapshot.section]}`),
221
+ );
222
+ return {
223
+ schema: "2.0",
224
+ config: { update_multi: true, width_mode: "fill" },
225
+ header: {
226
+ template: "blue",
227
+ title: plain("Agent Bot 设置"),
228
+ },
229
+ body: { padding: "12px", vertical_spacing: "8px", elements },
230
+ };
231
+ }
package/src/index.ts CHANGED
@@ -8,8 +8,8 @@ import { LocalControlServer } from "./cli/LocalControlServer.js";
8
8
  import { controlEndpoint, type ControlRequest, type ControlResponse } from "./cli/controlProtocol.js";
9
9
  import { readPackageVersion } from "./cli/packageVersion.js";
10
10
  import { loadConfig } from "./config/loadConfig.js";
11
+ import { SettingsStore } from "./config/SettingsStore.js";
11
12
  import { persistFeishuUserOpenIdIfMissing } from "./config/FeishuUserOpenIdStore.js";
12
- import { writeAgentExecutionDefaults } from "./config/AgentExecutionDefaultsStore.js";
13
13
  import {
14
14
  agentBotHome,
15
15
  defaultConfigPath,
@@ -34,6 +34,7 @@ import { createAgentRuntimeRegistry } from "./runtime/createAgentRuntimeRegistry
34
34
  import { StateStore } from "./state/StateStore.js";
35
35
  import { ManualUpdateController } from "./updates/ManualUpdateController.js";
36
36
  import { DailyUpdateMonitor } from "./updates/DailyUpdateMonitor.js";
37
+ import { TaskScheduler } from "./scheduling/TaskScheduler.js";
37
38
  import { readLatestStableVersion, readReleaseNotes, readPublishedReleases } from "./updates/PublishedRelease.js";
38
39
  import { checkAutomaticUpdateSupport, prepareAutomaticUpdate, prepareSelectedUpdate } from "./updates/AutomaticUpdatePreparer.js";
39
40
  import { StartupNotifier } from "./startup/StartupNotifier.js";
@@ -120,12 +121,13 @@ let consoleConnector: ConsoleConnector | undefined;
120
121
  let startupNotifier: StartupNotifier | undefined;
121
122
  let safeRestartNotifier: SafeRestartNotifier | undefined;
122
123
  let dailyUpdateMonitor: DailyUpdateMonitor | undefined;
124
+ let taskScheduler: TaskScheduler | undefined;
123
125
  let controlServer: LocalControlServer | undefined;
124
126
  let serverReady = false;
125
127
 
126
128
  const feishuOutbound = transport === "sdk" ? new FeishuMessageClient(config, logger) : undefined;
127
129
  if (feishuOutbound) {
128
- const renderer = new CardRenderer({ thinkingCardLayout: config.feishu.thinkingCardLayout });
130
+ const renderer = new CardRenderer();
129
131
  const presenter = new FeishuTurnPresenter(feishuOutbound, store, renderer, {
130
132
  normalIntervalMs: 2_000,
131
133
  criticalGapMs: 500,
@@ -265,6 +267,8 @@ function serverActivity() {
265
267
  }
266
268
 
267
269
  const controller = new ProxySessionController(config, store, runtimes, outbound, logger, {
270
+ settings: new SettingsStore(activeConfigPath, config),
271
+ canStartScheduledTasks: () => serverReady && !shuttingDown && !restartRequested && !safeRestart.scheduled,
268
272
  supervised,
269
273
  terminalUrl: (jobId) => terminalServer?.createUrl(jobId),
270
274
  authorizeTerminal: (action) => {
@@ -307,10 +311,6 @@ const controller = new ProxySessionController(config, store, runtimes, outbound,
307
311
  "Stored the default Lark user Open ID from the first private chat message.",
308
312
  );
309
313
  },
310
- persistAgentExecutionDefaults: (agentName, defaults) => {
311
- const changed = writeAgentExecutionDefaults(activeConfigPath, agentName, defaults);
312
- logger.info({ agentName, changed }, "Stored Agent execution defaults.");
313
- },
314
314
  }, undefined, undefined, shellCommandJobs);
315
315
  loadTurnDetails = (turnId) => controller.loadTurnDetails(turnId);
316
316
 
@@ -353,12 +353,20 @@ if (feishuConnector && startupNotifier) {
353
353
  await feishuConnector?.start();
354
354
  serverReady = true;
355
355
  }
356
+ taskScheduler = new TaskScheduler({
357
+ store, logger,
358
+ canDispatch: () => serverReady && !shuttingDown && !restartRequested && !safeRestart.scheduled,
359
+ ownerId: () => config.feishu.userOpenId,
360
+ drain: (sessionId) => controller.drainScheduledPrompts(sessionId),
361
+ notify: (job, text) => controller.notifySchedule(job, text),
362
+ });
356
363
  await controller.recoverInterruptedTasks().catch((error: unknown) => {
357
364
  logger.error({ error }, "Startup task recovery failed; the server will remain available.");
358
365
  });
359
366
  consoleConnector?.start();
360
367
  recoverPendingSelfUpdate();
361
368
  await dailyUpdateMonitor?.start();
369
+ await taskScheduler.start();
362
370
 
363
371
  function recoverPendingSelfUpdate(): void {
364
372
  const pending = readPendingSelfUpdate(agentBotHome());
@@ -518,6 +526,8 @@ async function handleControlRequest(request: ControlRequest): Promise<ControlRes
518
526
  activity: serverActivity(),
519
527
  },
520
528
  };
529
+ case "schedule":
530
+ return { ok: true, data: await controller.controlSchedule(request.command, request.localSessionId) };
521
531
  case "server_restart": {
522
532
  if (pendingSelfUpdatePlanPath) {
523
533
  return { ok: false, message: "An Agent Bot update is already pending." };
@@ -669,6 +679,7 @@ async function shutdown(
669
679
  ): Promise<void> {
670
680
  if (shuttingDown) return;
671
681
  shuttingDown = true;
682
+ await taskScheduler?.stop();
672
683
  await dailyUpdateMonitor?.stop();
673
684
  if (pendingSelfUpdatePlanPath) {
674
685
  releaseSelfUpdatePlan(pendingSelfUpdatePlanPath);
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { approvalActivityId } from "../presentation/TurnStateReducer.js";
3
+ import { isSettledTurnStatus } from "../presentation/turnStatus.js";
3
4
  import path from "node:path";
4
5
  import { enableDiagramFences, DIAGRAM_PREVIEW_CLIENT_SCRIPT, DIAGRAM_PREVIEW_CSS } from "./DiagramPreview.js";
5
6
  import MarkdownIt from "markdown-it";
@@ -70,6 +71,7 @@ const PREVIEW_LABELS = {
70
71
  running: "正在处理",
71
72
  tool_running: "正在处理",
72
73
  waiting_for_approval: "等待确认",
74
+ unknown: "待核实",
73
75
  completed: "已完成",
74
76
  cancelled: "已停止",
75
77
  failed: "执行失败",
@@ -114,6 +116,7 @@ const PREVIEW_LABELS = {
114
116
  running: "Processing",
115
117
  tool_running: "Processing",
116
118
  waiting_for_approval: "Waiting for approval",
119
+ unknown: "Unverified",
117
120
  completed: "Completed",
118
121
  cancelled: "Stopped",
119
122
  failed: "Failed",
@@ -656,7 +659,7 @@ export function renderTurnPreviewSnapshot(
656
659
  const renderText = (value: string): string => renderMarkdown(value, state.projectCwd, localFileUrl, language);
657
660
  const timeline = renderTimeline({ ...state, activities: visibleTurnActivities(state) }, renderText, resolveFileUrl, state.fullToolOutputs, state.fullToolErrors, language, state.projectCwd, options.deferDetails);
658
661
  const terminal = isTerminal(state.status);
659
- const waitingForProgress = !terminal && !state.finalResponse && !state.assistantText
662
+ const waitingForProgress = !isSettledTurnStatus(state.status) && !state.finalResponse && !state.assistantText
660
663
  && !state.error && !state.approval && state.status !== "waiting_for_approval"
661
664
  && state.plan.length === 0 && state.fileSummary.length === 0;
662
665
  const timelineContent = timeline || (waitingForProgress
@@ -675,11 +678,12 @@ export function renderTurnPreviewSnapshot(
675
678
  `<section class="timeline" data-preview-key="timeline"${timelineContent ? "" : " hidden"}>${timelineContent}</section>`,
676
679
  state.fileSummary.length > 0 ? renderFileSummary(state, language, resolveFileUrl, options.deferDetails) : "",
677
680
  state.approval ? renderApprovalNotice(state.approval, renderText, language) : "",
681
+ state.statusMessage ? `<section class="notice" data-preview-key="execution-status">${escapeHtml(state.statusMessage)}</section>` : "",
678
682
  state.error ? `<section class="result error-result" data-preview-key="error"><h2>${escapeHtml(labels.error)}</h2><pre>${escapeHtml(displayRuntimeError(state.error))}</pre></section>` : "",
679
683
  state.finalResponse
680
684
  ? renderFinalAnswer(state.finalResponse, state.turnId, renderText, language)
681
685
  : state.assistantText
682
- ? `<section class="result" data-preview-key="result"><h2>${escapeHtml(labels.generating)}</h2><div class="markdown">${renderText(state.assistantText)}</div></section>`
686
+ ? `<section class="result" data-preview-key="result"><h2>${escapeHtml(state.status === "unknown" ? labels.result : labels.generating)}</h2><div class="markdown">${renderText(state.assistantText)}</div></section>`
683
687
  : "",
684
688
  ].filter(Boolean).join("");
685
689
  return {
@@ -1211,7 +1215,7 @@ function renderMetadata(state: TurnViewState, language: TurnPreviewLanguage): st
1211
1215
  const completedAt = state.completedAt ?? (isTerminal(state.status) && state.durationMs !== undefined
1212
1216
  ? state.startedAt + state.durationMs
1213
1217
  : undefined);
1214
- const elapsed = `<span>${escapeHtml(labels.elapsed)}<strong${isTerminal(state.status) ? "" : ` data-live-elapsed data-started-at="${state.startedAt}"`}>${completedAt === undefined && isTerminal(state.status) ? escapeHtml(labels.unknown) : formatDuration((completedAt ?? Date.now()) - state.startedAt)}</strong></span>`;
1218
+ const elapsed = `<span>${escapeHtml(labels.elapsed)}<strong${isSettledTurnStatus(state.status) ? "" : ` data-live-elapsed data-started-at="${state.startedAt}"`}>${completedAt === undefined && isSettledTurnStatus(state.status) ? escapeHtml(labels.unknown) : formatDuration((completedAt ?? Date.now()) - state.startedAt)}</strong></span>`;
1215
1219
  const fields = [
1216
1220
  elapsed,
1217
1221
  state.modelProvider?.trim() ? `<span title="Provider">${escapeHtml(state.modelProvider.trim())}</span>` : "",
@@ -1315,7 +1319,7 @@ h2 span { margin-left: 6px; color: var(--muted); font-size: 12px; font-weight: 4
1315
1319
  .status { display: inline-flex; align-items: center; gap: 8px; }
1316
1320
  .status::before { content: "·"; color: var(--muted); }
1317
1321
  .status.starting, .status.running, .status.tool_running, .tool-state.running { color: var(--accent); }
1318
- .status.waiting_for_approval { color: #926a08; }
1322
+ .status.waiting_for_approval, .status.unknown { color: #926a08; }
1319
1323
  .status.completed, .tool-state.completed { color: var(--success); }
1320
1324
  .status.cancelled { color: var(--muted); }
1321
1325
  .status.failed, .tool-state.failed { color: var(--danger); }
@@ -4,6 +4,7 @@ import type { MessageReplyTarget } from "../feishu/types.js";
4
4
  import { formatStorageSize } from "../utils/formatStorageSize.js";
5
5
  import type { FileSummary, TurnActivity, TurnReasoningItem, TurnViewState } from "./turnViewTypes.js";
6
6
  import { turnReasoningItems } from "./turnReasoning.js";
7
+ import { canApplyTurnEvent } from "./turnStatus.js";
7
8
 
8
9
  const MAX_TEXT = 6_000;
9
10
  const MAX_COMPLETED_TOOLS = 20;
@@ -60,6 +61,7 @@ export function hydrateTurnViewState(summary: TurnViewState, details: RemoteTurn
60
61
  summary.agentLabel, summary.model, summary.promptImagePaths, summary.modelProvider),
61
62
  historyDetail: "full",
62
63
  historyDetailError: undefined,
64
+ statusMessage: undefined,
63
65
  };
64
66
  let hasPrompt = false;
65
67
  const identity = { sessionId: state.sessionId, turnId: state.turnId };
@@ -107,7 +109,7 @@ export function hydrateTurnViewState(summary: TurnViewState, details: RemoteTurn
107
109
  }
108
110
 
109
111
  export function reduceTurnEvent(state: TurnViewState, event: AgentEvent, complete = false): TurnViewState {
110
- if (event.sessionId !== state.sessionId || event.turnId !== state.turnId) return state;
112
+ if (!canApplyTurnEvent(state, event)) return state;
111
113
  const next = reduceEvent(state, event);
112
114
  if (!complete) return next;
113
115
  if (event.type === "turn_completed") next.finalResponse = event.finalResponse;
@@ -344,6 +346,8 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
344
346
  return {
345
347
  ...state,
346
348
  status: "completed",
349
+ statusMessage: undefined,
350
+ error: undefined,
347
351
  activeTool: undefined,
348
352
  approval: undefined,
349
353
  completedAt: state.startedAt + durationMs,
@@ -360,6 +364,7 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
360
364
  return {
361
365
  ...state,
362
366
  status: "cancelled",
367
+ statusMessage: undefined,
363
368
  activeTool: undefined,
364
369
  approval: undefined,
365
370
  completedAt,
@@ -371,6 +376,7 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
371
376
  return {
372
377
  ...state,
373
378
  status: "failed",
379
+ statusMessage: undefined,
374
380
  activeTool: undefined,
375
381
  approval: undefined,
376
382
  completedAt,
@@ -378,6 +384,19 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
378
384
  error: event.message,
379
385
  };
380
386
  }
387
+ case "turn_status_unknown":
388
+ return {
389
+ ...state,
390
+ status: "unknown",
391
+ statusMessage: event.message,
392
+ activeTool: undefined,
393
+ approval: undefined,
394
+ progressText: undefined,
395
+ contextCompactionStatus: undefined,
396
+ completedAt: undefined,
397
+ durationMs: undefined,
398
+ error: undefined,
399
+ };
381
400
  }
382
401
  }
383
402
 
@@ -389,7 +408,7 @@ export function continueTurnView(state: TurnViewState, turnId: string, startedAt
389
408
  return { ...state, turnId, previewTurnId: state.previewTurnId ?? state.turnId,
390
409
  continuedFromTurnId: state.turnId, continuedToTurnId: undefined, segmentStartedAt: startedAt,
391
410
  status: "running", completedAt: undefined, durationMs: undefined, finalResponse: undefined,
392
- error: undefined, approval: undefined, activeTool: undefined, assistantText: "", progressText: undefined };
411
+ error: undefined, statusMessage: undefined, approval: undefined, activeTool: undefined, assistantText: "", progressText: undefined };
393
412
  }
394
413
 
395
414
  function approvalHistoryText(request: ApprovalRequest, decision?: ApprovalDecision, automatic = false): string {
@@ -0,0 +1,38 @@
1
+ import type { AgentEvent } from "../runtime/types.js";
2
+ import type { TurnViewState, TurnViewStatus } from "./turnViewTypes.js";
3
+
4
+ export function isTerminalTurnStatus(status: string): boolean {
5
+ return status === "completed" || status === "cancelled" || status === "failed";
6
+ }
7
+
8
+ /** Settled monitoring does not imply that the remote execution has ended. */
9
+ export function isSettledTurnStatus(status: string): boolean {
10
+ return status === "unknown" || isTerminalTurnStatus(status);
11
+ }
12
+
13
+ export function canApplyTurnEvent(
14
+ state: Pick<TurnViewState, "sessionId" | "turnId" | "status">,
15
+ event: AgentEvent,
16
+ ): boolean {
17
+ if (event.sessionId !== state.sessionId || event.turnId !== state.turnId) return false;
18
+ // Late accounting may enrich a result, but never change its adjudication.
19
+ if (event.type === "token_usage_updated") return true;
20
+ if (isTerminalTurnStatus(state.status)) return state.status !== "completed" && event.type === "turn_completed";
21
+ if (state.status !== "unknown") return true;
22
+ return event.type === "turn_completed" || event.type === "turn_cancelled" || event.type === "turn_failed"
23
+ || event.type === "turn_status_unknown" || event.type === "agent_text_delta";
24
+ }
25
+
26
+ export function turnStatusLabel(status: TurnViewStatus, language: "zh" | "en" = "zh"): string {
27
+ const labels: Record<TurnViewStatus, [string, string]> = {
28
+ starting: ["正在处理", "Starting"],
29
+ running: ["正在处理", "Processing"],
30
+ tool_running: ["正在处理", "Processing"],
31
+ waiting_for_approval: ["等待确认", "Waiting for approval"],
32
+ unknown: ["待核实", "Unverified"],
33
+ completed: ["已完成", "Completed"],
34
+ cancelled: ["已停止", "Stopped"],
35
+ failed: ["执行失败", "Failed"],
36
+ };
37
+ return labels[status]?.[language === "zh" ? 0 : 1] ?? status;
38
+ }
@@ -6,6 +6,7 @@ export type TurnViewStatus =
6
6
  | "running"
7
7
  | "tool_running"
8
8
  | "waiting_for_approval"
9
+ | "unknown"
9
10
  | "completed"
10
11
  | "cancelled"
11
12
  | "failed";
@@ -52,6 +53,8 @@ export interface TurnViewState {
52
53
  projectCwd?: string;
53
54
  replyTarget?: MessageReplyTarget;
54
55
  status: TurnViewStatus;
56
+ /** Execution uncertainty, independent of transport connectivity and final delivery. */
57
+ statusMessage?: string;
55
58
  startedAt: number;
56
59
  completedAt?: number;
57
60
  durationMs?: number;