Repository navigation
Expand file tree
/
Copy pathpr15_source.diff
More file actions
599 lines (284 loc) · 25.6 KB
/
Copy pathpr15_source.diff
File metadata and controls
599 lines (284 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
diff --git a/athena-gui/src/hooks/usePipeline.ts b/athena-gui/src/hooks/usePipeline.ts
index 6955137..d006d73 100644
--- a/athena-gui/src/hooks/usePipeline.ts
+++ b/athena-gui/src/hooks/usePipeline.ts
@@ -36,6 +36,7 @@ const MAX_LOG_ENTRIES = 500;
/** Maps the backend runtime status to the frontend pipeline status. */
const RUNTIME_STATUS_MAP: Record<string, PipelineViewModel["status"]> = {
+ IDLE: "idle",
RUNNING: "running",
WAITING: "paused",
COMPLETED: "completed",
@@ -113,6 +114,24 @@ function applyHistoryRecords(current: PipelineViewModel, records: SessionRecord[
return next;
}
+/**
+ * 后端是否真的有运行在进行中。
+ *
+ * 上能只看 ``status``:网关构造的全新 runtime 首帧也可能报 RUNNING,而阶段机
+ * 尚未启动;那时首条任务必须走 ``parse_intent`` → ``start_search``。下面三个信号
+ * 只可能由阶段机真正跑过产生——已建计划、已有 SEARCH 尝试、已有 SOTA 基线。
+ *
+ * 例:{plans: [], searchAttempts: 0, latestExperimentId: null} → false
+ * {plans: [{id: "prepare"}], …} → true
+ */
+function hasBackendActivity(model: PipelineViewModel): boolean {
+ return (
+ model.plans.length > 0 ||
+ model.rightRail.searchAttempts > 0 ||
+ model.rightRail.latestExperimentId !== null
+ );
+}
+
/** Applies a single backend event (``state`` / ``output``) to the view model. */
function applyPipelineEvent(current: PipelineViewModel, event: PipelineEvent): PipelineViewModel {
const next: PipelineViewModel = { ...current, rightRail: { ...current.rightRail } };
@@ -145,6 +164,9 @@ function applyPipelineEvent(current: PipelineViewModel, event: PipelineEvent): P
if (typeof sota.metric === "number") next.rightRail.bestPrimary = sota.metric;
if (typeof sota.experiment === "string") next.rightRail.latestExperimentId = sota.experiment;
}
+ if (Array.isArray(data.plans)) {
+ next.plans = data.plans as Array<{ id: string }>;
+ }
if (Array.isArray(data.pending)) {
next.pending = data.pending as Array<{ id: string; statement: string }>;
}
@@ -226,6 +248,9 @@ export function usePipeline(workspaceRoot?: string | null) {
const [logs, setLogs] = useState<LogEntry[]>([]);
const counter = useRef(0);
const logCounter = useRef(0);
+ // 本会话是否已经发出过 start_search:后端首帧回来之前也算「运行在进行中《,
+ // 否则这段窗口里的普通文本会被误当成新任务、再弹一张意图卡。
+ const runStarted = useRef(false);
// 会话标题按工作区隔离:上同项目目录的会话标题互上串扰。
const titlesKey = sessionTitlesKey(workspaceRoot);
@@ -395,7 +420,12 @@ export function usePipeline(workspaceRoot?: string | null) {
}));
// 运行中/暂停中:普通文本是给 Supervisor 的指导/计划调整,上应再次走任务理解预览。
- if (viewModel.status === "running" || viewModel.status === "paused") {
+ // 判定上能只看 status——全新 runtime 的首帧也可能报 RUNNING,那时阶段机还没
+ // 启动,首条任务必须走 parse_intent,否则 start_search 永远上会被调用。
+ const runInProgress =
+ (viewModel.status === "running" || viewModel.status === "paused") &&
+ (runStarted.current || hasBackendActivity(viewModel));
+ if (runInProgress) {
try {
const response = (await sendControl(content)) as { response?: unknown };
const reply = typeof response?.response === "string" ? response.response : "";
@@ -453,9 +483,10 @@ export function usePipeline(workspaceRoot?: string | null) {
}));
throw err;
}
- }, [currentSessionId, nextId, renameSession, viewModel.status]);
+ }, [currentSessionId, nextId, renameSession, viewModel]);
const startRun = useCallback(async (task?: string, messageId?: string) => {
+ runStarted.current = true;
setViewModel((prev) => ({
...prev,
phase: "PREPARE",
@@ -468,6 +499,8 @@ export function usePipeline(workspaceRoot?: string | null) {
// 原始任务文本即后端 start_search 所需的 `task`;task understanding 只用于展示与标题。
await startSearch({ task });
} catch (err) {
+ // start_search 没成功 → 阶段机没起来,普通文本仍应重新走任务理解。
+ runStarted.current = false;
setViewModel((prev) => ({
...prev,
status: "error",
@@ -509,6 +542,7 @@ export function usePipeline(workspaceRoot?: string | null) {
const newSession = useCallback(() => {
// 新建一个独立会话(后端 transcript 按 session_id 分文件),并清空视图。
const id = `s-${Date.now()}`;
+ runStarted.current = false;
sessionSwitch(id).catch(() => {});
setSessions((prev) => [{ id, title: "新会话" }, ...prev.filter((s) => s.id !== id)]);
setCurrentSessionId(id);
@@ -520,6 +554,9 @@ export function usePipeline(workspaceRoot?: string | null) {
// 切到历史会话并重放其 transcript(断点续传),保留当前 phase/status。
try {
const { records } = await sessionSwitch(id);
+ // 换会话即换 runtime:本会话「已发出 start_search《的记忆上能带过去,
+ // 否则新会话的首条任务会被误路由到 supervisor 对话。
+ runStarted.current = false;
setCurrentSessionId(id);
restoreRecords(records, true);
} catch (err) {
diff --git a/athena-gui/src/types/ui.ts b/athena-gui/src/types/ui.ts
index 7943334..045ef33 100644
--- a/athena-gui/src/types/ui.ts
+++ b/athena-gui/src/types/ui.ts
@@ -79,6 +79,12 @@ export interface PipelineViewModel {
pending: Array<{ id: string; statement: string }>;
/** True when the runtime is in manual hypothesis-selection mode. */
manual: boolean;
+ /**
+ * 后端 ``state.plans`` 里的计划(PREPARE / 每个 SEARCH 假设 / VALIDATE)。
+ * 非空说明阶段机确实跑过——``status`` 本身做上到这个判断,全新 runtime 也可能
+ * 上报 RUNNING。
+ */
+ plans: Array<{ id: string }>;
}
/** Returns a default PipelineViewModel with idle state and empty messages. */
@@ -98,5 +104,6 @@ export function createEmptyPipelineViewModel(): PipelineViewModel {
},
pending: [],
manual: false,
+ plans: [],
};
}
diff --git a/src/athena/research/runtime.py b/src/athena/research/runtime.py
index 588c6de..47ea60f 100644
--- a/src/athena/research/runtime.py
+++ b/src/athena/research/runtime.py
@@ -206,17 +206,18 @@ class ResearchRuntime:
if self._tree_path.is_file()
else ResearchTree()
)
- initial_phase = (
- "PREPARE"
- if prepare_phase is not None or task or auto_seed_task
- else "SEARCH"
- )
+ # 全新 runtime 尚未启动任何阶段:状态是 IDLE 而上是 RUNNING,阶段落在
+ # PREPARE 而上是 SEARCH。GUI 网关一连上就把首帧 state 推给前端,首帧若
+ # 谎报 RUNNING/SEARCH,前端会以为已有运行在进行中,把首条任务路由到
+ # supervisor 对话而非 start_search,阶段机永远上启动。
+ # 真正的 RUNNING 由 ``start()`` 在进入阶段机时置上;已有
+ # ``state.json``(断点续传)沿用持久化的状态与阶段,上受此默认值影响。
self._state = (
ResearchState.load(self._state_path)
if self._state_path.is_file()
else ResearchState(
- status="RUNNING",
- phase=initial_phase,
+ status="IDLE",
+ phase="PREPARE",
search_limit=search_limit,
concurrency=concurrency,
ideator_count=ideator_count,
@@ -617,6 +618,13 @@ class ResearchRuntime:
"""
if self._task is not None and not self._task.done():
return self._task
+ # 阶段机从这里真正开跑:把「从未启动《的 IDLE 提升为 RUNNING。只提升
+ # IDLE——WAITING/COMPLETED/STOPPED 等由各自的控制路径(pause/stop/
+ # start_task 重新武装)决定,这里上覆盖。
+ # 只改内存上落盘:state.json 的唯一写者是 Supervisor,它随后的
+ # ``_persist_state`` 会把 RUNNING 持久化。
+ if self.state.status == "IDLE":
+ self.state.status = "RUNNING"
await self._git.init(initial_file=".gitignore", initial_content=".venv/\n")
self._agents.start()
# 断点续传:直接 start()(而非 start_task)的重启路径也恢夊首次任务文本。
diff --git a/src/athena/research/supervisor/state.py b/src/athena/research/supervisor/state.py
index 3ebdcce..75b7ef3 100644
--- a/src/athena/research/supervisor/state.py
+++ b/src/athena/research/supervisor/state.py
@@ -70,7 +70,9 @@ class ResearchState(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
- status: Literal["RUNNING", "WAITING", "COMPLETED", "STOPPED", "FAILED"]
+ # IDLE = 阶段机从未启动(全新 runtime 的初始值);``Supervisor.start()``
+ # 进入阶段机时置 RUNNING。区分二者,观察者才能分辨「没跑《与「在跑《。
+ status: Literal["IDLE", "RUNNING", "WAITING", "COMPLETED", "STOPPED", "FAILED"]
phase: Literal["PREPARE", "SEARCH", "VALIDATE", "COMPLETED"]
search_limit: int = Field(ge=0)
concurrency: int = Field(ge=1)
diff --git a/src/gui_gateway/handler.py b/src/gui_gateway/handler.py
index 39cd1c8..60473e0 100644
--- a/src/gui_gateway/handler.py
+++ b/src/gui_gateway/handler.py
@@ -5,6 +5,7 @@ Routes canonical GUI methods (see ``docs/athena-gui-design.md`` §3) to
transport, which subscribes to runtime ``state``/``output`` events directly.
"""
+import asyncio
import logging
import shutil
from pathlib import Path
@@ -85,6 +86,24 @@ def _require_dict(params: dict[str, Any], key: str, label: str) -> dict[str, Any
return value
+async def _rmtree_when_released(path: Path, attempts: int = 5) -> None:
+ """删除目录树;Windows 释放文件句柄有延迟,短暂重试后再放弃。
+
+ 调用方已经把持有句柄的 runtime 关掉,但句柄落地上是同步的:关闭之后紧接着
+ rmtree 仍可能撞上 ``[WinError 32]``。
+
+ 例:rmtree(dir) 抛 WinError 32 → 100ms 后重试 → 成功返回 None。
+ """
+ for attempt in range(attempts):
+ try:
+ shutil.rmtree(path)
+ return
+ except PermissionError:
+ if attempt == attempts - 1:
+ raise
+ await asyncio.sleep(0.1)
+
+
def _session_state_root(project_root: Path, session_id: str) -> Path | None:
"""Map a conversation id to its isolated state root (``None`` = default session)."""
if session_id == "default":
@@ -108,6 +127,8 @@ class GuiRequestHandler:
self._broker = broker or HumanRequestBroker()
self._service = GuiService(runtime)
self._project_root = Path(runtime.settings().get("project_root") or ".")
+ # 当前 runtime 属于哪个会话:删除会话时据此判断要上要先把 runtime 切走。
+ self._current_session_id = "default"
@property
def runtime(self) -> ResearchRuntime:
@@ -136,8 +157,8 @@ class GuiRequestHandler:
try:
state = getattr(self._runtime, "state", None)
state_path = getattr(self._runtime, "_state_path", None)
- # 只有从磁盘恢夊出的状态才可能是“进行中”;全新会话的内存默认状态
- # (phase=SEARCH/status=RUNNING)上能被误判成需要续跑。
+ # 只有从磁盘恢夊出的状态才可能是“进行中”:全新会话的内存默认状态是
+ # PREPARE/IDLE,本就上满足下面的条件;这里再按有无 state.json 兜一层。
persisted = state_path is not None and Path(state_path).is_file()
mid_run = (
persisted
@@ -172,6 +193,7 @@ class GuiRequestHandler:
raise ValueError("session switching is not configured")
state_root = _session_state_root(self._project_root, session_id)
await self._swap_runtime(str(self._project_root), state_root)
+ self._current_session_id = session_id
return {"session_id": session_id, "records": self._runtime.replay_output_events()}
def _session_ids(self, project_root: Path | None = None) -> list[str]:
@@ -196,8 +218,14 @@ class GuiRequestHandler:
"""列出任意工作区目录的会话 id(上切换 runtime),供前端按工作区分组。"""
return {"sessions": self._session_ids(Path(path))}
- def session_delete(self, session_id: str) -> dict[str, object]:
- """删除一个会话:命吊会话删整个 conversation 目录;``default`` 只清 transcript。"""
+ async def session_delete(self, session_id: str) -> dict[str, object]:
+ """删除一个会话:命吊会话删整个 conversation 目录;``default`` 只清 transcript。
+
+ 删的若是当前所在会话,必须先把 runtime 切回 ``default``——它的 agent
+ rollout writer 在 ``{state_root}/logs/agents/*.jsonl`` 上持着打开的句柄
+ (``ResearchRuntime`` 把 ``rollout_dir`` 指到会话状态根下),句柄上放手,
+ Windows 上 ``shutil.rmtree`` 会抛 ``PermissionError: [WinError 32]``。
+ """
if session_id == "default":
log = (
self._project_root
@@ -209,8 +237,11 @@ class GuiRequestHandler:
log.unlink(missing_ok=True)
return {"deleted": True, "sessions": self._session_ids()}
state_root = _session_state_root(self._project_root, session_id)
+ if session_id == self._current_session_id and self._make_runtime is not None:
+ await self._swap_runtime(str(self._project_root), None)
+ self._current_session_id = "default"
if state_root is not None and state_root.is_dir():
- shutil.rmtree(state_root)
+ await _rmtree_when_released(state_root)
return {"deleted": True, "sessions": self._session_ids()}
async def dispatch(self, method: str, params: dict[str, Any]) -> dict[str, object]:
@@ -251,7 +282,9 @@ class GuiRequestHandler:
_require_str(params, "session_id", "session_id")
)
if method == "session_delete":
- return self.session_delete(_require_str(params, "session_id", "session_id"))
+ return await self.session_delete(
+ _require_str(params, "session_id", "session_id")
+ )
if method == "eda_report":
return service.eda_report()
�