Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat:定时任务功能问题修复,可审批可续跑

hanjiahui6c44dc93db34
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.json
index 67c16d5caa..3b965ad140 100644
--- a/jiuwenswarm/channels/web/frontend/package.json
+++ b/jiuwenswarm/channels/web/frontend/package.json
@@ -23,6 +23,7 @@
"test:cron-expr-validation": "tsc src/components/CronPanel/cronExprValidation.ts src/components/CronPanel/cronWeekAlpha.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/cron-expr-validation --skipLibCheck --noEmitOnError && node --test tests/cronExprValidation.test.mjs",
"test:cron-project-display": "tsc src/components/CronPanel/cronProjectDisplay.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/cron-project-display --skipLibCheck --noEmitOnError && node --test tests/cronProjectDisplay.test.mjs",
"test:cron-job-sync": "esbuild src/features/cron/cronJobSync.ts --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/cron-job-sync/cronJobSync.mjs && node --test tests/cronJobSync.test.mjs",
+ "test:cron-live-skip-replay": "node --test tests/cronLiveSkipReplayUpgrade.test.mjs",
"test:xiaoyi-cron-target": "tsc src/components/CronPanel/xiaoyiCronTarget.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/xiaoyi-cron-target --skipLibCheck --noEmitOnError && node --test tests/xiaoyiCronTarget.test.mjs",
"test:stream-delta-batcher": "tsc src/services/streamDeltaBatcher.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/stream-delta-batcher --skipLibCheck --noEmitOnError && node --test tests/streamDeltaBatcher.test.mjs",
"test:file-download-dedup": "tsc src/utils/fileDownloadDedup.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/file-download-dedup --skipLibCheck --noEmitOnError && node --test tests/fileDownloadDedup.test.mjs",
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index 46b44ecd30..548f9a8f63 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -56,8 +56,15 @@ import {
import { webRequest } from './services/webClient';
import { OPEN_SESSION_EVENT, type OpenSessionDetail } from './features/longHorizon/sessionNav';
import { getWebTransport } from './utils/env';
+import {
+ bindCronLiveWatchLifecycle,
+ dismissCronAskUser,
+ isCronAskUserDismissed,
+ settleCronSessionRuntime,
+ shouldAcceptCronAskUserQuestion,
+} from './features/cron/cronLiveWatch';
import { useTeamPanelState } from './features/teamPanelState';
-import { AgentMode, MediaItem, UserAnswer, ModelEntry, type Session, type UserAnswerStatus } from './types';
+import { AgentMode, MediaItem, UserAnswer, ModelEntry, type Message, type Session, type UserAnswerStatus } from './types';
import {
ensureSessionRuntimes,
useSessionStore,
@@ -704,6 +711,7 @@ function AppContent() {
const messages = useChatStore((s) => s.runtimes[sessionId]?.messages ?? []);
const isLoadingHistory = useChatStore((s) => s.runtimes[sessionId]?.isLoadingHistory ?? false);
const replaceHistoryMessages = useChatStore((s) => s.replaceHistoryMessages);
+ const applyHistoryMessagesKeepLive = useChatStore((s) => s.applyHistoryMessagesKeepLive);
const restoreReasoningSegments = useChatStore((s) => s.restoreReasoningSegments);
const setPendingQuestion = useChatStore((s) => s.setPendingQuestion);
const isRestoringHistorySession = isLoadingHistory && !historyPagerMeta && messages.length === 0;
@@ -1530,6 +1538,32 @@ function AppContent() {
const startHistoryRestore = useCallback((sid: string): { done: Promise<boolean> } => {
let settleDone!: (ok: boolean) => void;
const done = new Promise<boolean>((resolve) => { settleDone = resolve; });
+ // 只认「还在飞」:结束后若仍因思考段/工具列表判 busy,会 keep-live 跳过
+ // reasoning 回放,切走再回来只剩工具、思考丢失。
+ const cronLiveBusy = () => {
+ if (!sid.startsWith('cron_')) return false;
+ const runtime = useChatStore.getState().getRuntime(sid);
+ if (!runtime) return false;
+ return Boolean(
+ runtime.isProcessing ||
+ runtime.pendingQuestion ||
+ runtime.currentStreamId,
+ );
+ };
+ /** 内存里已有助手正文而 history 本轮缺正文时,禁止整表覆盖抹掉实时气泡。 */
+ const cronShouldKeepLiveAgainstThinHistory = (historyMessages: Message[]) => {
+ if (!sid.startsWith('cron_')) return false;
+ const runtime = useChatStore.getState().getRuntime(sid);
+ if (!runtime) return false;
+ const memAssistants = runtime.messages.filter(
+ (m) => m.role === 'assistant' && String(m.content || '').trim(),
+ ).length;
+ if (memAssistants === 0) return false;
+ const histAssistants = historyMessages.filter(
+ (m) => m.role === 'assistant' && String(m.content || '').trim(),
+ ).length;
+ return memAssistants > histAssistants;
+ };
const restoreHandle = beginHistoryRestore({
sessionId: sid,
onReady: (messages, totalPages) => {
@@ -1539,10 +1573,16 @@ function AppContent() {
// hooks/useWebSocket.ts 的 applyIncomingGoal/mergePersistedGoalCompletionMessages。
// 同时给命中"曾经设置过目标"的 user 消息回填 isGoalObjectiveMessage 徽章标记,
// 见 stampGoalObjectiveMessages。
- replaceHistoryMessages(
+ const stamped = stampGoalObjectiveMessages(
sid,
- stampGoalObjectiveMessages(sid, mergePersistedGoalCompletionMessages(sid, messages))
+ mergePersistedGoalCompletionMessages(sid, messages),
);
+ // cron 监听流进行中,或内存正文比 history 更完整:只补消息,不清实时态。
+ if (cronLiveBusy() || cronShouldKeepLiveAgainstThinHistory(stamped)) {
+ applyHistoryMessagesKeepLive(sid, stamped);
+ } else {
+ replaceHistoryMessages(sid, stamped);
+ }
const restoredTotalPages = totalPages ?? 1;
setHistoryPagerMeta(sid, {
loadedPages: 1,
@@ -1558,7 +1598,10 @@ function AppContent() {
settleDone(true);
},
onEmpty: (emptyTotalPages) => {
- replaceHistoryMessages(sid, mergePersistedGoalCompletionMessages(sid, []));
+ // 全新 cron_* 常先空历史;若已在听流,不能 replace 空列表清掉实时态。
+ if (!cronLiveBusy()) {
+ replaceHistoryMessages(sid, mergePersistedGoalCompletionMessages(sid, []));
+ }
const restoredTotalPages = emptyTotalPages ?? 1;
setHistoryPagerMeta(sid, {
loadedPages: 1,
@@ -1566,12 +1609,14 @@ function AppContent() {
});
if (historyRestoreFromPanelHintRef.current) {
historyRestoreFromPanelHintRef.current = false;
- addMessage(sid, {
- id: `history-restore-empty-${Date.now()}`,
- role: 'system',
- content: tRef.current('sessions.restoreEmpty'),
- timestamp: new Date().toISOString(),
- });
+ if (!cronLiveBusy()) {
+ addMessage(sid, {
+ id: `history-restore-empty-${Date.now()}`,
+ role: 'system',
+ content: tRef.current('sessions.restoreEmpty'),
+ timestamp: new Date().toISOString(),
+ });
+ }
}
setLoadingHistory(sid, false);
startBackgroundHistoryPrefetch(sid, 1, restoredTotalPages);
@@ -1581,6 +1626,8 @@ function AppContent() {
settleDone(true);
},
onToolReplay: (items) => {
+ // 监听流已有工具态时不要用历史回放盖掉。
+ if (cronLiveBusy()) return;
clearSubtasks(sid);
for (const item of items) {
if (item.kind === 'tool_call') {
@@ -1620,6 +1667,7 @@ function AppContent() {
settleHistoricalToolExecutions(sid);
},
onHarnessReplay: (items: HistoryHarnessReplayItem[]) => {
+ if (cronLiveBusy()) return;
const harnessStore = useHarnessStore.getState();
const harnessRuntime = harnessStore.getRuntime(sid);
for (const item of items) {
@@ -1661,9 +1709,45 @@ function AppContent() {
}
},
onReasoningReplay: (items) => {
+ if (cronLiveBusy()) return;
restoreReasoningSegments(sid, items);
},
onAskUserReplay: (question) => {
+ // 监听流已挂审批卡时保留实时卡;否则按历史回放。
+ if (cronLiveBusy() && useChatStore.getState().getRuntime(sid)?.pendingQuestion) {
+ return;
+ }
+ if (question) {
+ if (
+ !shouldAcceptCronAskUserQuestion(sid, {
+ request_id: question.request_id,
+ source: question.source,
+ })
+ ) {
+ return;
+ }
+ const askRid = String(question.request_id || '').trim();
+ if (askRid && isCronAskUserDismissed(sid, askRid)) {
+ return;
+ }
+ const runtime = useChatStore.getState().getRuntime(sid);
+ const hasAssistant = (runtime?.messages ?? []).some(
+ (m: { role?: string; content?: string }) =>
+ m.role === 'assistant' && String(m.content || '').trim(),
+ );
+ // keep-live 时窗口里往往已有续跑正文,而 history 尚未带上 answered/final,
+ // materialize 会把 permission 卡当成仍 pending——有终态正文则不再挂卡。
+ if (
+ question.source === 'permission_interrupt' &&
+ hasAssistant &&
+ !runtime?.pendingQuestion
+ ) {
+ if (askRid) {
+ dismissCronAskUser(sid, askRid);
+ }
+ return;
+ }
+ }
// replaceHistoryMessages 会把 pendingQuestion 清掉;回放必须在它之后。
setPendingQuestion(sid, question);
if (question) {
@@ -1722,6 +1806,7 @@ function AppContent() {
setLoadingHistory,
setHistoryPagerMeta,
replaceHistoryMessages,
+ applyHistoryMessagesKeepLive,
restoreReasoningSegments,
startBackgroundHistoryPrefetch,
setPendingQuestion,
@@ -1729,9 +1814,8 @@ function AppContent() {
setThinking,
]);
- // 轮询兜底刷新:企业版 HTTP 无 cron 结果 push,立即执行跳转后 skipHistoryLoad,
- // syncJobRuns 检测到「当前正打开会话 == 新 last_session_id」时投递刷新请求,
- // 这里消费并触发一次完整的历史恢复(与首次点击激活会话的时机一逻辑一致)。
+ // 轮询兜底刷新:企业版 HTTP 无 cron 结果 push。syncJobRuns 在当前窗口属于
+ // 刚跑完的任务时投递刷新(不要求它仍是任务上的最新会话)。
const pendingActiveHistoryRefresh = useCronStore((s) => s.pendingActiveHistoryRefresh);
useEffect(() => {
if (!pendingActiveHistoryRefresh) return;
@@ -1743,6 +1827,10 @@ function AppContent() {
startHistoryRestore(sid);
}, [pendingActiveHistoryRefresh, startHistoryRestore]);
+ // 企业版 HTTP 不在网关 WebSocket 上。为当前 cron_* 与仍在 processing 的 cron
+ // 维持 live;切走不拆仍在跑的订阅,否则收不到 processing_status=false 会干转。
+ useEffect(() => bindCronLiveWatchLifecycle(), []);
+
// 当会话 ID 变化或页面加载时,自动加载历史会话
useEffect(() => {
if (!isConnected || !sessionId || sessionId === NEW_CONVERSATION_ID) return;
@@ -2164,7 +2252,12 @@ function AppContent() {
]);
const performSessionRestore = useCallback(
- async (targetSessionId: string, targetMode?: string, targetSession?: Session, options?: { skipHistoryLoad?: boolean }) => {
+ async (
+ targetSessionId: string,
+ targetMode?: string,
+ targetSession?: Session,
+ options?: { skipHistoryLoad?: boolean; seedUserMessage?: string },
+ ) => {
const previousSessionId = sessionIdRef.current;
const previousMode =
useSessionStore.getState().getRuntime(previousSessionId)?.mode ?? mode;
@@ -2192,10 +2285,59 @@ function AppContent() {
// 整页重拉历史,replaceHistoryMessages 换掉整条时间线(render key 重排+滚动效果
// 重跑),这就是"切回已访问会话时的跳闪"。只有即将走预载/重载路径的会话才清旧状态。
setHistoryLoadingMore(false);
+ // 立即执行打开的全新 cron_*:预载仍可走 history(用于补任务内容 user 消息),
+ // 但 restore 路径会 keep-live,避免清掉监听流。这里先标 processing,时间线不要「已完成」。
+ if (options?.skipHistoryLoad && targetSessionId.startsWith('cron_')) {
+ historyRestoreFromPanelHintRef.current = false;
+ setProcessing(targetSessionId, true);
+ setThinking(targetSessionId, false);
+ const seed = String(options.seedUserMessage || '').trim();
+ if (seed) {
+ const runtime = useChatStore.getState().getRuntime(targetSessionId);
+ const hasUser = Boolean(runtime?.messages.some((m) => m.role === 'user'));
+ if (!hasUser) {
+ addMessage(targetSessionId, {
+ id: `cron-seed-${targetSessionId}`,
+ role: 'user',
+ content: seed,
+ timestamp: new Date().toISOString(),
+ });
+ }
+ }
+ }
+ // 切回已跑完但仍标 processing 的 cron_*(连点立即执行切走漏收尾):
+ // job.last_session_id 已指向本会话则强制收口,否则 keep-live 会永远转圈。
+ if (
+ targetSessionId.startsWith('cron_') &&
+ existingRuntime &&
+ !options?.skipHistoryLoad &&
+ existingRuntime.isProcessing &&
+ !existingRuntime.pendingQuestion
+ ) {
+ const finishedOnServer = useCronStore
+ .getState()
+ .jobs.some((job) => (job.last_session_id || '').trim() === targetSessionId);
+ if (finishedOnServer) {
+ settleCronSessionRuntime(targetSessionId);
+ }
+ }
+ // 已结束的 cron_*:切回时强制重拉历史。内存里可能只有思考/工具、缺正文,
+ // 且旧 historyPagerMeta 会让 bootstrap 直接跳过恢复。
+ const cronRuntimeAfterSettle = useChatStore.getState().getRuntime(targetSessionId);
+ const cronNeedsHistoryReload =
+ Boolean(targetSessionId.startsWith('cron_')) &&
+ Boolean(cronRuntimeAfterSettle || existingRuntime) &&
+ !options?.skipHistoryLoad &&
+ !cronRuntimeAfterSettle?.isProcessing &&
+ !cronRuntimeAfterSettle?.pendingQuestion &&
+ !cronRuntimeAfterSettle?.currentStreamId;
+ if (cronNeedsHistoryReload) {
+ setHistoryPagerMeta(targetSessionId, null);
+ }
const willLoadHistory =
!options?.skipHistoryLoad &&
- !existingRuntime?.historyPagerMeta &&
- !existingRuntime?.isNewSession &&
+ (!(cronRuntimeAfterSettle ?? existingRuntime)?.historyPagerMeta || cronNeedsHistoryReload) &&
+ !(cronRuntimeAfterSettle ?? existingRuntime)?.isNewSession &&
!promotedFromNewSessionIdsRef.current.has(targetSessionId);
if (willLoadHistory) {
setHistoryPagerMeta(targetSessionId, null);
@@ -2287,6 +2429,7 @@ function AppContent() {
setProcessing,
setSessionId,
setThinking,
+ addMessage,
startHistoryRestore,
t,
upsertSessionMetadata,
@@ -2298,7 +2441,7 @@ function AppContent() {
targetSessionId: string,
targetMode?: string,
targetSession?: Session,
- options?: { skipHistoryLoad?: boolean },
+ options?: { skipHistoryLoad?: boolean; seedUserMessage?: string },
): Promise<void> => {
// WebSocket requests are processed concurrently by AgentServer. Queue
// navigation here so rapid A -> B -> C clicks cannot race and let an
@@ -2777,14 +2920,16 @@ function AppContent() {
<CronPanel
sessionId={sessionId}
onCreateViaChat={(initialInputValue) => requestSessionNavigation('new', { initialInputValue })}
- onSelectSession={(session) => {
+ onSelectSession={(session, selectOptions) => {
if (typeof session === 'string') {
// 立即执行返回的 session_id 可能还未在后端创建(agent 刚开始执行),
// 构造最小 Session 占位对象,让 upsertSessionMetadata 直接加入会话列表,
// 避免 loadSessionMetadata 立即失败导致"对话不存在或已删除"。
// 后续 cron 广播到达时会刷新会话列表补全完整元数据。
- // 跳过初始历史加载:session 是全新的,空响应的 replaceHistoryMessages
- // 会覆盖后续到达的广播消息。
+ // skipHistoryLoad 只跳过切换预载;bootstrap 仍会拉历史,且 cron
+ // 进行中走 keep-live,只补任务内容、不清监听流。
+ // 复用待审批会话:必须拉历史回放审批卡,勿当新 run 只 seed + 干转。
+ const reusePending = Boolean(selectOptions?.reusePendingApproval);
void handleRestoreSession(session, undefined, {
session_id: session,
title: '',
@@ -2795,7 +2940,10 @@ function AppContent() {
message_count: 0,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
- }, { skipHistoryLoad: true });
+ }, {
+ skipHistoryLoad: !reusePending,
+ seedUserMessage: reusePending ? undefined : selectOptions?.seedUserMessage,
+ });
return;
}
requestSessionNavigation(session);
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx
index f37b31cc9a..6f1b862b48 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx
@@ -147,7 +147,10 @@ interface CronPanelProps {
* 传 Session 对象(如"触发的会话"列表里已有完整数据)或直接传 session_id 字符串
* (如立即执行返回的 session_id,还没有完整 Session 数据)。
*/
- onSelectSession: (session: Session | string) => void;
+ onSelectSession: (
+ session: Session | string,
+ options?: { seedUserMessage?: string; reusePendingApproval?: boolean },
+ ) => void;
}
type TabKey = 'list' | 'template' | 'history';
@@ -696,14 +699,34 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession
return;
}
- const result = await webRequest<{ accepted: boolean; run_id: string; session_id?: string }>('cron.job.run_now', {
+ const result = await webRequest<{
+ accepted: boolean;
+ run_id: string;
+ session_id?: string;
+ awaiting_approval?: boolean;
+ reused_pending_session?: boolean;
+ }>('cron.job.run_now', {
id: job.id,
});
if (result.session_id) {
useCronStore.getState().setLastRunSessionId(job.id, result.session_id);
- onSelectSession(result.session_id);
+ const reused =
+ Boolean(result.reused_pending_session) || Boolean(result.awaiting_approval);
+ if (reused) {
+ // 上一轮审批未完成:打开旧 cron_*,拉历史回放审批卡,勿新建空会话干转。
+ onSelectSession(result.session_id, { reusePendingApproval: true });
+ setSuccess(t('cron.success.runNowPendingApproval'));
+ } else {
+ const seed = String(job.description || job.name || '').trim();
+ onSelectSession(
+ result.session_id,
+ seed ? { seedUserMessage: seed } : undefined,
+ );
+ setSuccess(t('cron.success.runNow'));
+ }
+ } else {
+ setSuccess(t('cron.success.runNow'));
}
- setSuccess(t('cron.success.runNow'));
// 刷新左侧栏该定时任务下展开的 session 列表(project.get_cron_sessions)
const { id: cronId, projectId } = job;
if (cronId && projectId) {
diff --git a/jiuwenswarm/channels/web/frontend/src/features/cron/cronJobSync.ts b/jiuwenswarm/channels/web/frontend/src/features/cron/cronJobSync.ts
index 1ce1e18a9b..d36a3d5c4c 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/cron/cronJobSync.ts
+++ b/jiuwenswarm/channels/web/frontend/src/features/cron/cronJobSync.ts
@@ -84,3 +84,33 @@ export function detectCronJobRunUpdates(
return { updatedJobIds, nextFingerprints };
}
+
+/**
+ * 企业版 HTTP 没有定时任务结果推送。当前窗口只要属于刚跑完的这个任务,
+ * 就再读一次它的历史;不必等于任务上的最新会话。连续执行时最新会话会被
+ * 下一次覆盖,正看着的上一个窗口否则要刷新页面才看得到回复。
+ * 没有打开相关窗口时返回空串,不额外请求历史。
+ */
+export function resolveOpenCronHistoryRefresh(input: {
+ jobId: string;
+ lastSessionId: string;
+ activeSessionId: string;
+ activeCronId: string;
+ rememberedRunSessionId: string;
+}): string {
+ const active = input.activeSessionId.trim();
+ if (!active) {
+ return '';
+ }
+ const last = input.lastSessionId.trim();
+ if (last && last === active) {
+ return active;
+ }
+ if (input.activeCronId.trim() === input.jobId) {
+ return active;
+ }
+ if (input.rememberedRunSessionId.trim() === active) {
+ return active;
+ }
+ return '';
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/cron/cronLiveSkipReplayPolicy.ts b/jiuwenswarm/channels/web/frontend/src/features/cron/cronLiveSkipReplayPolicy.ts
new file mode 100644
index 0000000000..07d05448b4
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/cron/cronLiveSkipReplayPolicy.ts
@@ -0,0 +1,23 @@
+/**
+ * Cron live SSE:何时禁止 full-replay → skip_replay 中途升级。
+ * 纯函数,便于单测;实现见 cronLiveWatch.upgradeCronLiveWatchToSkipReplay。
+ */
+
+export type CronLiveSkipReplayRuntimeHint = {
+ isProcessing?: boolean;
+ currentStreamId?: string | null;
+ pendingQuestion?: unknown;
+};
+
+/**
+ * 出字中 / 本轮仍在跑 / 挂审批:禁止切连(字级 CJK delta 易丢/乱序)。
+ * 冷刷新等审批应走「首连 skip_replay」,不走 upgrade。
+ */
+export function shouldDeferCronLiveSkipReplayUpgrade(
+ runtime?: CronLiveSkipReplayRuntimeHint | null,
+): boolean {
+ if (!runtime) return false;
+ return Boolean(
+ runtime.isProcessing || runtime.currentStreamId || runtime.pendingQuestion,
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/cron/cronLiveWatch.ts b/jiuwenswarm/channels/web/frontend/src/features/cron/cronLiveWatch.ts
new file mode 100644
index 0000000000..03b91a9cd2
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/cron/cronLiveWatch.ts
@@ -0,0 +1,710 @@
+/**
+ * 企业版 HTTP 没有网关 WebSocket。正在看某个 cron_* 窗口时,订一条监听流,
+ * 把思考、正文和审批卡送进现有 chat.* 处理。点允许之后的续跑走这次点击自己的
+ * chat.send,不从这里再画一遍。
+ *
+ * 同一 session 稳态只保留一条 live SSE。冷刷新 / 等审批时 history 已就绪则
+ * **首连** skip_replay。出字中、本轮 processing、或挂着权限卡时禁止
+ * full-replay → skip_replay 中途升级(切连会丢字级 CJK delta)。
+ *
+ * 连点多个「立即执行」会切走当前 cron_*:切走时不能拆掉仍在跑的 live,
+ * 否则收不到 processing_status=false,UI 会永远转圈;跑完后 gateway 还会
+ * clear replay,晚订阅也补不回收尾帧。
+ *
+ * 刷新竞态:live 若在 history 完成前订上,replay 里的 processing=true 会打开
+ * acceptContent,把上一轮思考/审批整段灌进空 runtime——表现为「又在验证
+ * read_file」+ 权限条。故 idle 冷启动等 history;history 已就绪时 skip_replay。
+ *
+ * 收尾:processing=false 后短暂保活等 chat.final 覆盖 delta 拼接;有权限卡时不拆。
+ */
+import { isEnterprise } from '../../edition';
+import {
+ hasManagerSessionCredentials,
+ managerAuthenticatedFetch,
+} from '../../auth/manager/authSession';
+import { hitlRequestIdsMatch } from '../historyRestore';
+import { webClient } from '../../services/webClient';
+import { buildRuntimeIdentityHeaders } from '../../services/runtimeScope';
+import { useChatStore, type ChatRuntime } from '../../stores/chatStore';
+import type { WsEvent } from '../../types';
+import { getGatewayHttpBase, getWebTransport } from '../../utils/env';
+import { shouldDeferCronLiveSkipReplayUpgrade } from './cronLiveSkipReplayPolicy';
+
+export { shouldDeferCronLiveSkipReplayUpgrade } from './cronLiveSkipReplayPolicy';
+
+type ChatStoreSnapshot = ReturnType<typeof useChatStore.getState>;
+/** Content frames that must not overwrite history on an idle refresh. */
+const CRON_LIVE_CONTENT_EVENTS = new Set([
+ 'chat.delta',
+ 'chat.final',
+ 'chat.reasoning',
+ 'chat.tool_call',
+ 'chat.tool_update',
+ 'chat.tool_result',
+ // 与正文同属本轮内容:idle 刷新勿用 stale replay 把 usage 贴到错气泡上。
+ 'chat.usage_summary',
+]);
+
+type LiveWatchHandle = {
+ stop: () => void;
+ /** Whether this watch prefers skip_replay=1 once history is ready. */
+ skipReplay: boolean;
+};
+function authorizedFetch(input: RequestInfo | URL, init: RequestInit): Promise<Response> {
+ if (isEnterprise() && hasManagerSessionCredentials()) {
+ return managerAuthenticatedFetch(input, init);
+ }
+ return fetch(input, init);
+}
+function parseSseBlock(raw: string): WsEvent | null {
+ let eventName = '';
+ const dataLines: string[] = [];
+ for (const line of raw.split(/\r?\n/)) {
+ if (line.startsWith('event:')) {
+ eventName = line.slice(6).trim();
+ } else if (line.startsWith('data:')) {
+ // SSE: strip at most one leading space after the colon (do not trim JSON).
+ const value = line.slice(5);
+ dataLines.push(value.startsWith(' ') ? value.slice(1) : value);
+ }
+ }
+ if (!dataLines.length) return null;
+ try {
+ const parsed = JSON.parse(dataLines.join('\n')) as {
+ event?: string;
+ payload?: Record<string, unknown>;
+ };
+ const payload = parsed.payload;
+ if (!payload || typeof payload !== 'object') return null;
+ const event = String(parsed.event || eventName || '').trim();
+ if (!event) return null;
+ const requestId = typeof payload.request_id === 'string' ? payload.request_id : undefined;
+ return { type: 'event', event, payload, request_id: requestId };
+ } catch {
+ return null;
+ }
+}
+function readLiveSeq(payload: Record<string, unknown>): number | null {
+ const raw = payload.live_seq;
+ if (typeof raw === 'number' && Number.isFinite(raw)) {
+ return raw;
+ }
+ if (typeof raw === 'string' && raw.trim()) {
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : null;
+ }
+ return null;
+}
+
+/** session_id → current (newest) live watch. */
+const activeLiveWatches = new Map<string, LiveWatchHandle>();
+
+/** session_id → last applied live_seq (drop stale/dup frames from overlapping SSE). */
+const lastLiveSeqBySession = new Map<string, number>();
+
+/** session_id → 已答过的 ask request_id(防 live replay 把权限卡复活). */
+const dismissedCronAskIds = new Map<string, Set<string>>();
+
+/**
+ * processing=false 之后、权威 chat.final 到达之前,短暂保持 shouldWatch,
+ * 避免 zustand 订阅立刻拆掉 live、终稿盖不回 delta 错拼。
+ */
+const CRON_LIVE_FINAL_GRACE_MS = 2500;
+const awaitingFinalDeadlineBySession = new Map<string, number>();
+const awaitingFinalTimerBySession = new Map<string, ReturnType<typeof setTimeout>>();
+
+export function isCronSessionLiveWatchActive(sessionId: string): boolean {
+ return activeLiveWatches.has(sessionId.trim());
+}
+
+function isCronLiveAwaitingFinal(sessionId: string): boolean {
+ const sid = sessionId.trim();
+ const deadline = awaitingFinalDeadlineBySession.get(sid);
+ if (deadline == null) return false;
+ if (Date.now() >= deadline) {
+ awaitingFinalDeadlineBySession.delete(sid);
+ return false;
+ }
+ return true;
+}
+
+function clearCronLiveAwaitingFinalTimer(sessionId: string): void {
+ const sid = sessionId.trim();
+ const timer = awaitingFinalTimerBySession.get(sid);
+ if (timer != null) {
+ clearTimeout(timer);
+ awaitingFinalTimerBySession.delete(sid);
+ }
+}
+
+/** processing=false 且无权限卡时调用:保活至 final 或宽限到期。 */
+export function markCronLiveAwaitingFinal(
+ sessionId: string,
+ graceMs: number = CRON_LIVE_FINAL_GRACE_MS,
+): void {
+ const sid = sessionId.trim();
+ if (!sid.startsWith('cron_')) return;
+ const runtime = useChatStore.getState().getRuntime(sid);
+ if (runtime?.pendingQuestion) return;
+ clearCronLiveAwaitingFinalTimer(sid);
+ const deadline = Date.now() + Math.max(0, graceMs);
+ awaitingFinalDeadlineBySession.set(sid, deadline);
+ const timer = setTimeout(() => {
+ awaitingFinalTimerBySession.delete(sid);
+ const currentDeadline = awaitingFinalDeadlineBySession.get(sid);
+ if (currentDeadline !== deadline) return;
+ awaitingFinalDeadlineBySession.delete(sid);
+ if (!shouldWatchCronSession(sid)) {
+ stopCronSessionLiveWatch(sid);
+ }
+ }, Math.max(0, graceMs) + 25);
+ awaitingFinalTimerBySession.set(sid, timer);
+}
+
+/**
+ * 权威 chat.final 已写入气泡后调用:结束保活并拆 live。
+ * 仅在 markCronLiveAwaitingFinal 窗口内生效——避免 HITL 前铺垫 final 误拆 live。
+ * 仍挂权限卡时不拆。
+ */
+export function noteCronLiveContentFinal(sessionId: string): void {
+ const sid = sessionId.trim();
+ if (!sid.startsWith('cron_')) return;
+ if (!isCronLiveAwaitingFinal(sid)) return;
+ const runtime = useChatStore.getState().getRuntime(sid);
+ if (runtime?.pendingQuestion) return;
+ clearCronLiveAwaitingFinalTimer(sid);
+ awaitingFinalDeadlineBySession.delete(sid);
+ stopCronSessionLiveWatch(sid);
+}
+
+export function stopAllCronSessionLiveWatches(): void {
+ for (const sid of [...activeLiveWatches.keys()]) {
+ stopCronSessionLiveWatch(sid);
+ }
+}
+
+/** 用户已提交权限/审批后调用,后续 live/history 回放同 request_id 不再挂卡. */
+export function dismissCronAskUser(sessionId: string, requestId: string): void {
+ const sid = sessionId.trim();
+ const rid = requestId.trim();
+ if (!sid.startsWith('cron_') || !rid) return;
+ let bucket = dismissedCronAskIds.get(sid);
+ if (!bucket) {
+ bucket = new Set();
+ dismissedCronAskIds.set(sid, bucket);
+ }
+ bucket.add(rid);
+}
+
+export function isCronAskUserDismissed(sessionId: string, requestId: string): boolean {
+ const rid = requestId.trim();
+ if (!rid) return false;
+ const bucket = dismissedCronAskIds.get(sessionId.trim());
+ if (!bucket || bucket.size === 0) return false;
+ if (bucket.has(rid)) return true;
+ for (const dismissed of bucket) {
+ if (hitlRequestIdsMatch(dismissed, rid)) return true;
+ }
+ return false;
+}
+function cronRuntimeHasAssistantContent(sessionId: string): boolean {
+ const messages = useChatStore.getState().getRuntime(sessionId)?.messages ?? [];
+ return messages.some(
+ (m: { role?: string; content?: string }) =>
+ m.role === 'assistant' && String(m.content || '').trim(),
+ );
+}
+
+/** 末条非 system 是 user → 本轮续聊尚未收到助手终态,不能当 stale 收口。 */
+function cronRuntimeHasOpenUserTurn(sessionId: string): boolean {
+ const messages = useChatStore.getState().getRuntime(sessionId)?.messages ?? [];
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
+ const role = messages[i]?.role;
+ if (role === 'user') return true;
+ if (role === 'assistant') return false;
+ }
+ return false;
+}
+function isCronPermissionPromptSource(source: string | undefined): boolean {
+ const src = String(source || '').trim();
+ // 无 source 时授权条仍可能按选项形态展示;收口时一并清掉更稳妥。
+ return !src || src === 'permission_interrupt' || src === 'confirm_interrupt';
+}
+
+/**
+ * Gateway 流以 HITL 暂停结束时仍可能误补 processing=false。
+ * 若 cron 上仍挂着权限/确认卡,应保留进行中,不能当「已完成」清卡。
+ */
+export function shouldRetainCronPermissionOnProcessingFalse(
+ sessionId: string,
+ pending: { source?: string } | null | undefined,
+): boolean {
+ const sid = sessionId.trim();
+ if (!sid.startsWith('cron_')) return false;
+ if (!pending) return false;
+ return isCronPermissionPromptSource(pending.source);
+}
+
+/**
+ * cron 等审批时调度器不会推 processing=false。
+ * 收到 false / 终态 final 后若仍挂着权限卡,视为过期残留并清掉。
+ * 例外:见 shouldRetainCronPermissionOnProcessingFalse(续跑二次审批)。
+ */
+export function clearStaleCronPermissionPrompt(sessionId: string): boolean {
+ const sid = sessionId.trim();
+ if (!sid.startsWith('cron_')) return false;
+ const chat = useChatStore.getState();
+ const pending = chat.getRuntime(sid)?.pendingQuestion;
+ if (!pending || !isCronPermissionPromptSource(pending.source)) {
+ return false;
+ }
+ const rid = String(pending.request_id || '').trim();
+ if (rid) {
+ dismissCronAskUser(sid, rid);
+ }
+ chat.setPendingQuestion(sid, null);
+ return true;
+}
+
+/**
+ * live / chat.send SSE 共用:已结束会话上的 stale permission ask 不再写入 pending。
+ * 真正等审批时 isProcessing 仍为 true,会放行。
+ */
+export function shouldAcceptCronAskUserQuestion(
+ sessionId: string,
+ question: { request_id?: string; source?: string },
+): boolean {
+ const sid = sessionId.trim();
+ if (!sid.startsWith('cron_')) return true;
+ const rid = String(question.request_id || '').trim();
+ if (rid && isCronAskUserDismissed(sid, rid)) {
+ return false;
+ }
+ if (!isCronPermissionPromptSource(question.source)) {
+ return true;
+ }
+ const runtime = useChatStore.getState().getRuntime(sid);
+ if (
+ !runtime?.isProcessing &&
+ !runtime?.pendingQuestion &&
+ cronRuntimeHasAssistantContent(sid)
+ ) {
+ if (rid) {
+ dismissCronAskUser(sid, rid);
+ }
+ return false;
+ }
+ return true;
+}
+
+export function stopCronSessionLiveWatch(sessionId: string): void {
+ const sid = sessionId.trim();
+ if (!sid) return;
+ clearCronLiveAwaitingFinalTimer(sid);
+ awaitingFinalDeadlineBySession.delete(sid);
+ activeLiveWatches.get(sid)?.stop();
+}
+
+/**
+ * 立即执行切走后再切回、或 job sync 发现任务已终态时,
+ * 清掉残留的 isProcessing / 子任务转圈,并拆掉 live。
+ *
+ * 不能因「会话里曾经有过助手消息」就收口正在跑的续聊:否则会停掉
+ * chat.send 流并触发 history 整表覆盖,把内存里尚未落盘的正文抹掉。
+ */
+export function settleCronSessionRuntime(sessionId: string): boolean {
+ const sid = sessionId.trim();
+ if (!sid.startsWith('cron_')) return false;
+ const chat = useChatStore.getState();
+ const runtime = chat.getRuntime(sid);
+ if (!runtime) {
+ stopCronSessionLiveWatch(sid);
+ return false;
+ }
+ if (runtime.pendingQuestion) return false;
+ // 本轮仍在出字 / 等 final:绝不强制收口。
+ if (runtime.currentStreamId) return false;
+ if (isCronLiveAwaitingFinal(sid)) return false;
+ if (runtime.isProcessing && isCronSessionLiveWatchActive(sid)) return false;
+ // 续聊已发 user、尚无对应 assistant:processing 也可能短暂无 streamId。
+ if (runtime.isProcessing && cronRuntimeHasOpenUserTurn(sid)) return false;
+ // 首轮尚无助手正文:仍可能在等 ask 帧或 live replay。
+ if (
+ !cronRuntimeHasAssistantContent(sid) &&
+ (runtime.isProcessing || isCronSessionLiveWatchActive(sid))
+ ) {
+ return false;
+ }
+ const hasSubtasks = (runtime.activeSubtasks?.size ?? 0) > 0;
+ const busy = Boolean(runtime.isProcessing || runtime.currentStreamId || hasSubtasks);
+ if (!busy) {
+ stopCronSessionLiveWatch(sid);
+ return false;
+ }
+ chat.setProcessing(sid, false);
+ chat.setThinking(sid, false);
+ chat.clearSubtasks(sid);
+ chat.stopStreaming(sid);
+ stopCronSessionLiveWatch(sid);
+ return true;
+}
+
+/**
+ * 是否应订 live:
+ * - 本页已在跑 / 已挂审批 → 订(run-now 可带 replay)
+ * - 冷刷新:等 history 完成;仅当 history 回放出仍在等审批时再订,且 skip_replay
+ * - processing=false 后短暂等 chat.final → 仍订(见 markCronLiveAwaitingFinal)
+ * - 已结束且空闲 → 不订,避免 stale replay 重建上一轮
+ */
+export function shouldWatchCronSession(
+ sessionId: string,
+ runtime?: ChatRuntime | null,
+): boolean {
+ const sid = sessionId.trim();
+ if (!sid.startsWith('cron_')) return false;
+ const rt = runtime ?? useChatStore.getState().getRuntime(sid);
+ if (!rt) return false;
+ if (rt.isProcessing || rt.pendingQuestion) return true;
+ if (isCronLiveAwaitingFinal(sid)) return true;
+ return false;
+}
+
+/**
+ * history 已就绪且当前 watch 仍是 full-replay:先开 skip_replay 新连,再关旧。
+ * 出字中 / processing / 权限卡期间禁止升级(A');冷刷新等审批应走首连 skip_replay。
+ */
+export function upgradeCronLiveWatchToSkipReplay(sessionId: string): void {
+ const sid = sessionId.trim();
+ if (getWebTransport() !== 'http' || !sid.startsWith('cron_')) return;
+ if (!shouldWatchCronSession(sid)) return;
+ const runtime = useChatStore.getState().getRuntime(sid);
+ if (shouldDeferCronLiveSkipReplayUpgrade(runtime)) return;
+ const current = activeLiveWatches.get(sid);
+ if (!current || current.skipReplay) return;
+ startCronSessionLiveWatch(sid, {
+ skipReplay: true,
+ previousStop: current.stop,
+ });
+}
+
+/** 已有同 session 的 live 则复用,避免切会话时重启 SSE 丢帧. */
+export function ensureCronSessionLiveWatch(sessionId: string): () => void {
+ const sid = sessionId.trim();
+ if (getWebTransport() !== 'http' || !sid.startsWith('cron_')) {
+ return () => undefined;
+ }
+ if (!shouldWatchCronSession(sid)) {
+ stopCronSessionLiveWatch(sid);
+ return () => undefined;
+ }
+ const existing = activeLiveWatches.get(sid);
+ if (existing) {
+ const wantSkip = Boolean(useChatStore.getState().getRuntime(sid)?.historyPagerMeta);
+ const runtime = useChatStore.getState().getRuntime(sid);
+ if (
+ wantSkip &&
+ !existing.skipReplay &&
+ !shouldDeferCronLiveSkipReplayUpgrade(runtime)
+ ) {
+ upgradeCronLiveWatchToSkipReplay(sid);
+ return activeLiveWatches.get(sid)?.stop ?? existing.stop;
+ }
+ return existing.stop;
+ }
+ return startCronSessionLiveWatch(sid).stop;
+}
+
+export function startCronSessionLiveWatch(
+ sessionId: string,
+ options?: {
+ skipReplay?: boolean;
+ /** Open-new-then-close-old: keep this connection until the new one is ready. */
+ previousStop?: () => void;
+ },
+): LiveWatchHandle {
+ const sid = sessionId.trim();
+ const noop: LiveWatchHandle = {
+ stop: () => undefined,
+ skipReplay: Boolean(options?.skipReplay),
+ };
+ if (getWebTransport() !== 'http' || !sid.startsWith('cron_')) {
+ return noop;
+ }
+ let previousStop = options?.previousStop;
+ // Immediate replace (no overlap): tear down any prior watch first.
+ if (!previousStop) {
+ activeLiveWatches.get(sid)?.stop();
+ activeLiveWatches.delete(sid);
+ }
+ const controller = new AbortController();
+ let stopped = false;
+ // Only accept content after processing_status=true on this connection.
+ // Stale replay on an idle follow-up session must not rebuild the first run.
+ let acceptContent = false;
+ const preferSkipReplay =
+ options?.skipReplay ?? Boolean(useChatStore.getState().getRuntime(sid)?.historyPagerMeta);
+ const stop = () => {
+ if (stopped) return;
+ stopped = true;
+ controller.abort();
+ const current = activeLiveWatches.get(sid);
+ if (current?.stop === stop) {
+ activeLiveWatches.delete(sid);
+ }
+ // Full teardown only when no active watch remains (overlap keeps seq).
+ if (!activeLiveWatches.has(sid)) {
+ lastLiveSeqBySession.delete(sid);
+ }
+ };
+ const handle: LiveWatchHandle = { stop, skipReplay: preferSkipReplay };
+ activeLiveWatches.set(sid, handle);
+ const shouldInject = (event: WsEvent): boolean => {
+ const runtime = useChatStore.getState().getRuntime(sid);
+ // 冷刷新:history 未就绪且本页未在跑 → 丢掉一切 live(含 processing=true),
+ // 否则 replay 会先把 isProcessing/acceptContent 打开,整段上一轮灌进来。
+ const coldIdle =
+ !runtime?.isProcessing &&
+ !runtime?.pendingQuestion &&
+ (Boolean(runtime?.isLoadingHistory) || !runtime?.historyPagerMeta);
+ if (coldIdle) {
+ return false;
+ }
+ if (event.event === 'chat.processing_status') {
+ const on = Boolean(event.payload.is_processing);
+ // 已结束会话上的 stale processing=true,勿重新打开 acceptContent / 转圈。
+ if (
+ on &&
+ !runtime?.isProcessing &&
+ !runtime?.pendingQuestion &&
+ cronRuntimeHasAssistantContent(sid)
+ ) {
+ return false;
+ }
+ acceptContent = on;
+ return true;
+ }
+ if (event.event === 'chat.ask_user_question') {
+ if (
+ !shouldAcceptCronAskUserQuestion(sid, {
+ request_id: String(event.payload.request_id || ''),
+ source: typeof event.payload.source === 'string' ? event.payload.source : undefined,
+ })
+ ) {
+ return false;
+ }
+ acceptContent = true;
+ return true;
+ }
+ if (!CRON_LIVE_CONTENT_EVENTS.has(event.event)) {
+ return true;
+ }
+ // Active run (this connection saw processing=true, or UI already in-flight).
+ if (acceptContent || runtime?.isProcessing || runtime?.pendingQuestion) {
+ return true;
+ }
+ // Idle follow-up window: drop leftover bus replay so refresh cannot rebuild
+ // the first cron-run answer on top of history.
+ return false;
+ };
+ const maybeStopAfterSettled = () => {
+ queueMicrotask(() => {
+ if (stopped) return;
+ const current = activeLiveWatches.get(sid);
+ if (current?.stop !== stop) return;
+ const runtime = useChatStore.getState().getRuntime(sid);
+ // 护栏:有权限卡绝不拆。
+ if (runtime?.pendingQuestion) return;
+ if (runtime?.isProcessing) return;
+ // B':仍在等 chat.final 覆盖正文时不拆;宽限到期或 noteCronLiveContentFinal 再拆。
+ if (isCronLiveAwaitingFinal(sid)) return;
+ stop();
+ });
+ };
+ const run = async () => {
+ while (!stopped) {
+ try {
+ acceptContent = false;
+ // history 已落盘后再订:跳过 bus 缓冲,只收实时帧。
+ const rtAtConnect = useChatStore.getState().getRuntime(sid);
+ const skipReplay =
+ preferSkipReplay || Boolean(rtAtConnect?.historyPagerMeta);
+ // Keep handle metadata in sync if history landed mid-reconnect loop.
+ handle.skipReplay = skipReplay;
+ const liveUrl =
+ `${getGatewayHttpBase()}/sessions/${encodeURIComponent(sid)}/live` +
+ (skipReplay ? '?skip_replay=1' : '');
+ const response = await authorizedFetch(liveUrl, {
+ method: 'GET',
+ headers: {
+ ...buildRuntimeIdentityHeaders(`cron-live-${sid}`, { session_id: sid }),
+ Accept: 'text/event-stream',
+ },
+ cache: 'no-store',
+ signal: controller.signal,
+ });
+ if (stopped) return;
+ // Superseded by a newer watch (overlap upgrade) before we connected.
+ if (activeLiveWatches.get(sid)?.stop !== stop) {
+ stop();
+ return;
+ }
+ if (!response.ok || !response.body) {
+ throw new Error(`cron live watch failed (${response.status})`);
+ }
+ // New SSE ready: close the previous full-replay connection (open-new-then-close-old).
+ if (previousStop) {
+ const retiring = previousStop;
+ previousStop = undefined;
+ retiring();
+ }
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ // Use own `stopped` flag only — map entry may briefly point at us while
+ // an overlap peer also injects; live_seq dedupes. When we are retired,
+ // stop() sets stopped=true.
+ while (!stopped) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const blocks = buffer.split(/\r?\n\r?\n/);
+ buffer = blocks.pop() ?? '';
+ for (const block of blocks) {
+ if (stopped) return;
+ const event = parseSseBlock(block);
+ if (!event) continue;
+ const eventSession = String(
+ event.payload.session_id || event.payload.exec_session_id || '',
+ );
+ if (eventSession && eventSession !== sid) continue;
+ const liveSeq = readLiveSeq(event.payload);
+ if (liveSeq != null) {
+ const last = lastLiveSeqBySession.get(sid) ?? 0;
+ // Overlapping SSE (reconnect / StrictMode / skip_replay upgrade)
+ // can deliver older frames after newer ones; drop to avoid CJK swap.
+ if (liveSeq <= last) continue;
+ lastLiveSeqBySession.set(sid, liveSeq);
+ }
+ if (!shouldInject(event)) continue;
+ // 先于 inject 打 awaiting-final:否则 setProcessing(false) 的同步订阅会立刻拆 live。
+ if (
+ event.event === 'chat.processing_status' &&
+ !Boolean(event.payload.is_processing)
+ ) {
+ const rtBefore = useChatStore.getState().getRuntime(sid);
+ if (!rtBefore?.pendingQuestion) {
+ markCronLiveAwaitingFinal(sid);
+ }
+ }
+ webClient.injectEvent(event);
+ if (
+ event.event === 'chat.processing_status' &&
+ !Boolean(event.payload.is_processing)
+ ) {
+ // final 常在 false 之前已写入;气泡已非 streaming 时可立刻收口。
+ const rtAfter = useChatStore.getState().getRuntime(sid);
+ if (
+ !rtAfter?.pendingQuestion &&
+ !rtAfter?.isProcessing &&
+ !rtAfter?.currentStreamId
+ ) {
+ noteCronLiveContentFinal(sid);
+ } else {
+ maybeStopAfterSettled();
+ }
+ }
+ if (event.event === 'chat.final') {
+ // 仅当已进入 awaiting-final(false 已到)时收口;铺垫 final 不拆线。
+ noteCronLiveContentFinal(sid);
+ }
+ }
+ }
+ } catch {
+ if (stopped || controller.signal.aborted) {
+ return;
+ }
+ }
+ if (stopped) return;
+ // Only the newest watch may reconnect after drop.
+ if (activeLiveWatches.get(sid)?.stop !== stop) {
+ stop();
+ return;
+ }
+ await new Promise((resolve) => {
+ window.setTimeout(resolve, 2000);
+ });
+ }
+ };
+ void run();
+ return handle;
+}
+
+/**
+ * 企业版 HTTP:仅为「仍在跑 / 仍挂审批」的 cron 维持 live。
+ * 已结束的空闲 cron 不订,避免刷新时 stale replay 重建上一轮。
+ * history 回放出 pendingQuestion 后会再 ensure(skip_replay)。
+ */
+export function bindCronLiveWatchLifecycle(): () => void {
+ if (getWebTransport() !== 'http') {
+ return () => undefined;
+ }
+ const syncWatches = () => {
+ const state = useChatStore.getState();
+ for (const sid of Object.keys(state.runtimes)) {
+ if (!sid.startsWith('cron_')) continue;
+ if (shouldWatchCronSession(sid, state.runtimes[sid])) {
+ ensureCronSessionLiveWatch(sid);
+ } else {
+ stopCronSessionLiveWatch(sid);
+ }
+ }
+ const active = (state.activeSessionId || '').trim();
+ if (active.startsWith('cron_') && shouldWatchCronSession(active)) {
+ ensureCronSessionLiveWatch(active);
+ }
+ };
+ syncWatches();
+ const unsub = useChatStore.subscribe((state: ChatStoreSnapshot, prev: ChatStoreSnapshot) => {
+ const active = (state.activeSessionId || '').trim();
+ const prevActive = (prev.activeSessionId || '').trim();
+ if (active.startsWith('cron_') && active !== prevActive) {
+ if (shouldWatchCronSession(active)) {
+ ensureCronSessionLiveWatch(active);
+ } else {
+ stopCronSessionLiveWatch(active);
+ }
+ if (prevActive.startsWith('cron_') && !shouldWatchCronSession(prevActive)) {
+ stopCronSessionLiveWatch(prevActive);
+ }
+ }
+ for (const sid of Object.keys(state.runtimes)) {
+ if (!sid.startsWith('cron_')) continue;
+ const runtime: ChatRuntime | undefined = state.runtimes[sid];
+ const prevRt: ChatRuntime | undefined = prev.runtimes[sid];
+ const nowWatch = shouldWatchCronSession(sid, runtime);
+ const wasWatch = shouldWatchCronSession(sid, prevRt);
+ if (nowWatch && !wasWatch) {
+ ensureCronSessionLiveWatch(sid);
+ }
+ if (wasWatch && !nowWatch) {
+ stopCronSessionLiveWatch(sid);
+ }
+ // history 刚落盘:full-replay → skip_replay(先开新再关旧)。
+ if (
+ nowWatch &&
+ wasWatch &&
+ !prevRt?.historyPagerMeta &&
+ runtime?.historyPagerMeta
+ ) {
+ upgradeCronLiveWatchToSkipReplay(sid);
+ if (!isCronSessionLiveWatchActive(sid)) {
+ ensureCronSessionLiveWatch(sid);
+ }
+ }
+ }
+ });
+ return () => {
+ unsub();
+ stopAllCronSessionLiveWatches();
+ };
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts
index eff0a746b5..375500ccb8 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts
+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts
@@ -698,6 +698,25 @@ interface MaterializedHistoryTimeline {
pendingAskUser: AskUserQuestionPayload | null;
}
+/**
+ * HITL 卡片 id 可能带 ``{call_id}#{n}``;作答落盘曾 strip 后缀,刷新要对得上。
+ * 规则:exact 优先;仅允许「裸 base」↔「base#n」。禁止 ``#1``↔``#2`` 互认(多步同 call)。
+ */
+export function hitlRequestIdsMatch(left: string, right: string): boolean {
+ const a = String(left || '').trim();
+ const b = String(right || '').trim();
+ if (!a || !b) return false;
+ if (a === b) return true;
+ const strip = (value: string) => value.replace(/#\d+$/, '');
+ const baseA = strip(a);
+ const baseB = strip(b);
+ // a is unsuffixed base, b is a#n
+ if (a === baseA && baseB === a && b !== baseB) return true;
+ // b is unsuffixed base, a is b#n
+ if (b === baseB && baseA === b && a !== baseA) return true;
+ return false;
+}
+
/** 将已按时间升序的 history 条目折叠成消息/工具/思考,供 restore / page / 文件预览共用。 */
function materializeHistoryTimeline(entries: HistoryTimelineEntry[]): MaterializedHistoryTimeline {
const messages: Message[] = [];
@@ -713,7 +732,7 @@ function materializeHistoryTimeline(entries: HistoryTimelineEntry[]): Materializ
continue;
}
if (e.kind === 'ask_user_question_expired' || e.kind === 'ask_user_answered') {
- if (pendingAskUser?.request_id === e.requestId) {
+ if (pendingAskUser && hitlRequestIdsMatch(pendingAskUser.request_id, e.requestId)) {
pendingAskUser = null;
}
continue;
@@ -723,6 +742,13 @@ function materializeHistoryTimeline(entries: HistoryTimelineEntry[]): Materializ
// 不能把它当成「已经答完」。只有用户又发了新消息才收起卡片。
if (e.message.role === 'user') {
pendingAskUser = null;
+ } else if (
+ e.message.role === 'assistant' &&
+ pendingAskUser?.source === 'permission_interrupt' &&
+ String(e.message.content || '').trim()
+ ) {
+ // 权限卡之后若已有正文终态,说明本轮已批准并跑完;缺 ask_user_answered 时也不应复活。
+ pendingAskUser = null;
}
messages.push(e.message);
continue;
@@ -803,6 +829,8 @@ export interface HistoryTimelinePreview {
executions: ToolExecution[];
reasoningSegments: { id: string; text: string; startedAt: number; closed: true; closedAt?: number }[];
mode: 'team' | null;
+ /** 刷新后仍应展示的未作答 HITL 卡;已作答 / 权限后已出正文则为 null */
+ pendingAskUser: AskUserQuestionPayload | null;
}
/**
@@ -813,7 +841,13 @@ export function parseHistoryJsonFileToTimelinePreview(
sessionId: string
): HistoryTimelinePreview {
if (!Array.isArray(parsed)) {
- return { messages: [], executions: [], reasoningSegments: [], mode: null };
+ return {
+ messages: [],
+ executions: [],
+ reasoningSegments: [],
+ mode: null,
+ pendingAskUser: null,
+ };
}
const entries: HistoryTimelineEntry[] = [];
@@ -843,7 +877,8 @@ export function parseHistoryJsonFileToTimelinePreview(
return safeTimestampMs(aAt) - safeTimestampMs(bAt);
});
- const { messages, toolReplay, reasoningReplay } = materializeHistoryTimeline(entries);
+ const { messages, toolReplay, reasoningReplay, pendingAskUser } =
+ materializeHistoryTimeline(entries);
const executions = buildToolExecutionsFromReplay(toolReplay);
const reasoningSegments = buildReasoningSegmentsFromReplay(sessionId, reasoningReplay);
@@ -852,6 +887,7 @@ export function parseHistoryJsonFileToTimelinePreview(
executions,
reasoningSegments,
mode: isTeam ? 'team' : null,
+ pendingAskUser,
};
}
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index 7299ece31a..ccbe1741b7 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -60,6 +60,15 @@ import {
} from '../services/runtimeScope';
import { getWebTransport } from '../utils/env';
import { isEnterprise } from '../edition';
+import {
+ clearStaleCronPermissionPrompt,
+ dismissCronAskUser,
+ isCronSessionLiveWatchActive,
+ markCronLiveAwaitingFinal,
+ noteCronLiveContentFinal,
+ shouldAcceptCronAskUserQuestion,
+ shouldRetainCronPermissionOnProcessingFalse,
+} from '../features/cron/cronLiveWatch';
import { createStreamDeltaBatcher } from '../services/streamDeltaBatcher';
import { createStreamDeltaStripper } from '../utils/toolProtocol';
import {
@@ -2176,6 +2185,12 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
usePlanStore.getState().setActive(sessionId, false);
pendingPlanExecuteRef.current.add(sessionId);
}
+ // 与普通 sendMessage 一样挂上 client request id,便于流式事件对齐;
+ // cron 审批续跑可能数十秒,必须保持 isProcessing,避免时间线先收成「已完成」。
+ const resumeClientRid = makeClientRequestId('chat');
+ activeRequestIdRef.current = resumeClientRid;
+ useChatStore.getState().setProcessing(sessionId, true);
+ useChatStore.getState().setThinking(sessionId, false);
await request('chat.send', {
session_id: sessionId,
query: '',
@@ -2189,7 +2204,23 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
...approvalSchemaPayload,
...evolutionMetaPayload,
...agentScopePayload,
- });
+ }, { requestId: resumeClientRid });
+ // chat.send 的 await 在 SSE 建连后就返回;cron 续跑结束后若正文没进
+ // 内存,延迟用历史补齐(processing_status=false 路径也会再试一次)。
+ if (sessionId.startsWith('cron_') && effectiveSource === 'permission_interrupt') {
+ const refreshIfMissingAssistant = () => {
+ const rt = useChatStore.getState().getRuntime(sessionId);
+ if (!rt || rt.isProcessing || rt.pendingQuestion) return;
+ const hasAssistant = (rt.messages ?? []).some(
+ (m) => m.role === 'assistant' && String(m.content || '').trim(),
+ );
+ if (!hasAssistant) {
+ useCronStore.getState().requestActiveHistoryRefresh(sessionId);
+ }
+ };
+ window.setTimeout(refreshIfMissingAssistant, 4000);
+ window.setTimeout(refreshIfMissingAssistant, 20000);
+ }
} else if (effectiveSource === 'activate_confirm') {
const action = answers[0]?.selected_options[0] === '拒绝' ? 'reject' : 'accept';
const interactionId = requestId || useHarnessStore.getState().getRuntime(sessionId)?.activateInteraction?.interactionId || '';
@@ -2222,6 +2253,9 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
...agentScopePayload,
});
}
+ if (sessionId.startsWith('cron_') && requestId) {
+ dismissCronAskUser(sessionId, requestId);
+ }
useChatStore.getState().setPendingQuestion(sessionId, null);
return true;
} catch (error) {
@@ -2352,6 +2386,11 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
if (!runtime || runtime.isProcessing || runtime.isLoadingHistory) {
return false;
}
+ // cron 首轮不走本地 chat.send:没有 activeRequestId / inflight。监听流里的
+ // reasoning 必须能把 isProcessing 拉起来,否则时间线会按「已完成」折叠。
+ if (sessionId.startsWith('cron_')) {
+ return true;
+ }
if (runtime.currentStreamId) {
return true;
}
@@ -2686,6 +2725,14 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
if (!sessionId) return;
flushPendingStreamDelta(sessionId);
+ // cron B':本帧 final 写完气泡后(含 chat.send 续跑路径),结束 live 保活窗口。
+ // 有权限卡时 noteCronLiveContentFinal 内部会直接 return。
+ if (sessionId.startsWith('cron_')) {
+ queueMicrotask(() => {
+ noteCronLiveContentFinal(sessionId);
+ });
+ }
+
const memberAction = pickString(payload.member_action);
const actionMemberName = pickString(payload.member_name);
if (
@@ -2756,12 +2803,23 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
// In team mode the backend suppresses chat.final while the team is
// still running and only sends chat.processing_status(is_complete=true)
// on team.completed, so we must NOT reset isProcessing here.
- // 企业版错误后的 final 只是回复段收尾,保留错误并等待任务终态/错误 EOF 兜底。
- if (
- !useChatStore.getState().getRuntime(sessionId)?.isLoadingHistory &&
- !(isEnterprise() && getWebTransport() === 'http' && useChatStore.getState().getRuntime(sessionId)?.executionError)
- ) {
- useChatStore.getState().setExecutionError(sessionId, null);
+ // 企业版错误后的 final 只是回复段收尾:保留错误文案,但仍要能清 processing,
+ // 否则空响应等终态错误会一直卡在「处理中」(见 chat.error 收口)。
+ // cron_*:历史回放与 live 重叠时也要能靠 final 收口,否则无护栏快速跑完会一直转圈。
+ const loadingHistoryNow = Boolean(
+ useChatStore.getState().getRuntime(sessionId)?.isLoadingHistory,
+ );
+ const allowFinalProcessingClear =
+ !loadingHistoryNow || sessionId.startsWith('cron_');
+ const keepEnterpriseHttpError = Boolean(
+ isEnterprise() &&
+ getWebTransport() === 'http' &&
+ useChatStore.getState().getRuntime(sessionId)?.executionError,
+ );
+ if (allowFinalProcessingClear) {
+ if (!keepEnterpriseHttpError) {
+ useChatStore.getState().setExecutionError(sessionId, null);
+ }
if (currentMode !== 'team') {
// 有 active Goal 时,普通问答轮和 Goal 后续执行走同一条流;这次 chat.final 可能只是
// 普通问答轮的收尾,Goal 紧接着还要继续跑。此时不能把它当"整段彻底结束"处理——
@@ -2771,6 +2829,16 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
const goalStillActive =
useGoalStore.getState().runtimes[sessionId]?.goal?.status === 'active';
if (!goalStillActive) {
+ // cron live 仍开着时:final 常早于 chat.usage_summary。
+ // 若直接 setProcessing(false) 会让 lifecycle 拆掉 live,token/费用行丢失。
+ // 先进入 awaiting-final 保活,等 usage + processing=false 再拆。
+ if (
+ sessionId.startsWith('cron_') &&
+ isCronSessionLiveWatchActive(sessionId) &&
+ !useChatStore.getState().getRuntime(sessionId)?.pendingQuestion
+ ) {
+ markCronLiveAwaitingFinal(sessionId);
+ }
useChatStore.getState().setProcessing(sessionId, false);
// 正常情况下排空由 chat.processing_status(false) 负责;这里是它丢帧时的兜底
// 重置,同样可能是"目标这一轮真正结束"的那个信号,一并兜底排空一次排队消息
@@ -2778,6 +2846,10 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
drainTaskQueueIfIdle(sessionId);
useChatStore.getState().setThinking(sessionId, false);
useChatStore.getState().clearSubtasks(sessionId);
+ // cron 等审批不会推 final 收口;有正文的 final 说明本轮已结束,清掉残留权限条。
+ if (sessionId.startsWith('cron_') && content) {
+ clearStaleCronPermissionPrompt(sessionId);
+ }
}
} else {
useChatStore.getState().setThinking(sessionId, false);
@@ -2986,6 +3058,43 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
}
return;
}
+ // cron 终稿:仅在本轮仍在执行时覆盖最后一条助手气泡。
+ // 空闲刷新若重放旧 live final,会把最新 follow-up 盖成第一轮正文。
+ const cronRuntime = useChatStore.getState().getRuntime(sessionId);
+ const cronTurnActive = Boolean(
+ streamId || cronRuntime?.isProcessing || cronRuntime?.pendingQuestion,
+ );
+ if (cronRunId && sessionId.startsWith('cron_') && cronTurnActive) {
+ let turnStart = 0;
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
+ if (messages[i].role === 'user') {
+ turnStart = i + 1;
+ break;
+ }
+ }
+ let rewriteId: string | null = streamId ?? null;
+ if (!rewriteId) {
+ for (let i = messages.length - 1; i >= turnStart; i -= 1) {
+ const msg = messages[i];
+ if (msg.role === 'assistant' && typeof msg.content === 'string') {
+ rewriteId = msg.id;
+ break;
+ }
+ }
+ }
+ if (rewriteId) {
+ useChatStore.getState().updateMessage(sessionId, rewriteId, {
+ content,
+ isStreaming: false,
+ completedAt: completedAtIso,
+ });
+ useChatStore.getState().stopStreaming(sessionId);
+ if (!content.includes('MEDIA:')) {
+ handleTtsPlayback(sessionId, rewriteId, content);
+ }
+ return;
+ }
+ }
}
const messageId =
@@ -3474,9 +3583,16 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
if (shouldDropDuplicatedEvent('chat.processing_status', payload)) return;
// 切换模式时忽略处理状态更新
if (useChatStore.getState().getRuntime(sessionId)?.switchingMode) return;
- // 加载历史消息时忽略处理状态更新
- if (useChatStore.getState().getRuntime(sessionId)?.isLoadingHistory) return;
const isProcessingNow = Boolean(payload.is_processing);
+ // 拉历史时忽略 processing=true,避免旧帧把时间线拉回转圈。
+ // 但必须放行 false:cron 立即执行(尤其无护栏、工具自动通过)常在几秒内结束,
+ // false 很容易撞上 isLoadingHistory;丢掉后窗口会永远「处理中」。
+ if (
+ isProcessingNow &&
+ useChatStore.getState().getRuntime(sessionId)?.isLoadingHistory
+ ) {
+ return;
+ }
// 后端确认 processing=true 时清除本地发送标记——新任务已由后端接管
if (isProcessingNow) {
localSendPendingRef.current.delete(sessionId);
@@ -3493,6 +3609,43 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
if (!isProcessingNow) {
flushPendingStreamDelta(sessionId);
}
+ // cron B':非 live 注入的 processing=false(如审批续跑 chat.send)也要先打保活,
+ // 否则 zustand 订阅会在 chat.final 到达前拆掉 live。
+ // HITL 暂停收尾若误补 false:cron 上仍挂权限卡时保持进行中,勿清卡。
+ if (
+ !isProcessingNow &&
+ !errorEof &&
+ shouldRetainCronPermissionOnProcessingFalse(
+ sessionId,
+ useChatStore.getState().getRuntime(sessionId)?.pendingQuestion,
+ )
+ ) {
+ useChatStore.getState().setProcessing(sessionId, true);
+ useChatStore.getState().setThinking(sessionId, false);
+ const retainPatch: Partial<Session> = {
+ is_processing: true,
+ updated_at: new Date().toISOString(),
+ };
+ updateSession(sessionId, retainPatch);
+ useWorkspaceStore.getState().patchSession(sessionId, retainPatch);
+ return;
+ }
+ // cron B':确认会收口后再打 awaiting-final(retain 路径已 return)。
+ // final 常先于 false;保活后若气泡已落地则 microtask 立刻拆 live。
+ if (
+ !isProcessingNow &&
+ !errorEof &&
+ sessionId.startsWith('cron_') &&
+ !useChatStore.getState().getRuntime(sessionId)?.pendingQuestion
+ ) {
+ markCronLiveAwaitingFinal(sessionId);
+ queueMicrotask(() => {
+ const rt = useChatStore.getState().getRuntime(sessionId);
+ if (!rt?.pendingQuestion && !rt?.isProcessing && !rt?.currentStreamId) {
+ noteCronLiveContentFinal(sessionId);
+ }
+ });
+ }
useChatStore.getState().setProcessing(sessionId, isProcessingNow);
const sessionPatch: Partial<Session> = {
is_processing: isProcessingNow,
@@ -3511,6 +3664,21 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
}
useChatStore.getState().settleHistoricalToolExecutions(sessionId);
+ // cron 等审批时不会推 processing=false;false 到达后仍挂权限条 = 过期残留。
+ if (sessionId.startsWith('cron_') && !errorEof) {
+ clearStaleCronPermissionPrompt(sessionId);
+ }
+
+ // cron 审批续跑后,调度器不再推 chat.final;SSE 若丢了正文,
+ // 用历史补齐(此时 isProcessing=false,走完整 replace+reasoning 回放)。
+ if (sessionId.startsWith('cron_') && !errorEof) {
+ const hasAssistant = (useChatStore.getState().getRuntime(sessionId)?.messages ?? [])
+ .some((m) => m.role === 'assistant' && String(m.content || '').trim());
+ if (!hasAssistant) {
+ useCronStore.getState().requestActiveHistoryRefresh(sessionId);
+ }
+ }
+
// EOF 不是后端任务完成确认,只复用展示收尾,不触发队列发送。
if (errorEof) return;
@@ -3673,6 +3841,19 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
content: t('network.errorPrefix', { message: errorMsg }),
timestamp: new Date().toISOString(),
});
+ // 终态错误必须收口:否则企业版 HTTP 在 processing_status=false 丢帧时
+ // 会一直「处理中」,且 chat.final 因 executionError 不敢清 processing。
+ // cron_* 无护栏跑完后续聊「好的」触发空响应时即此现象。
+ flushPendingStreamDelta(sessionId);
+ useChatStore.getState().setProcessing(sessionId, false);
+ useChatStore.getState().clearSubtasks(sessionId);
+ useChatStore.getState().stopStreaming(sessionId);
+ if (isEnterprise()) {
+ useChatStore.getState().settlePendingToolExecutions(sessionId);
+ }
+ useChatStore.getState().settleHistoricalToolExecutions(sessionId);
+ activeRequestIdRef.current = undefined;
+ drainTaskQueueIfIdle(sessionId);
}),
webClient.on('security.alert', ({ payload }) => {
const sessionId = resolveEventSessionId(payload);
@@ -3913,8 +4094,24 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
webClient.on('chat.ask_user_question', ({ payload }) => {
const sessionId = resolveEventSessionId(payload);
if (!sessionId) return;
+ const cronMeta = payload.cron as Record<string, unknown> | undefined;
+ if (cronMeta && typeof cronMeta === 'object') {
+ const cronJobId = typeof cronMeta.job_id === 'string' ? cronMeta.job_id.trim() : '';
+ if (cronJobId) {
+ useCronStore.getState().markCronJobUnread(cronJobId);
+ }
+ }
const normalizedPayload = normalizeAskUserQuestionPayload(payload);
if (!normalizedPayload) return;
+ // chat.send SSE 不经 live shouldInject;已结束 cron 上的 stale permission 直接丢。
+ if (
+ !shouldAcceptCronAskUserQuestion(sessionId, {
+ request_id: normalizedPayload.request_id,
+ source: normalizedPayload.source,
+ })
+ ) {
+ return;
+ }
// 计划正文走对话气泡,不再塞进审批卡片:审批栏只保留「执行」和
// 「改进意见 + 下一步/跳过」。修订后再次提交会是新的 request_id,
// 所以每一版计划都会留下自己的气泡。
@@ -3933,6 +4130,11 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
});
}
useChatStore.getState().setPendingQuestion(sessionId, normalizedPayload);
+ // 等审批仍算进行中。cron 首轮没有本地 sendMessage,不设 true 会显示「已完成」。
+ if (sessionId.startsWith('cron_') || (cronMeta && typeof cronMeta === 'object')) {
+ useChatStore.getState().setProcessing(sessionId, true);
+ useChatStore.getState().setThinking(sessionId, false);
+ }
}),
webClient.on('chat.ask_user_question_expired', ({ payload }) => {
const sessionId = resolveEventSessionId(payload);
@@ -3940,6 +4142,13 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
const pendingQuestion = useChatStore.getState().getRuntime(sessionId)?.pendingQuestion;
// 子 Agent 委托审批超时/取消:仅当 expired 与当前挂起问题严格匹配时收起卡片
if (!isMatchingSubagentApprovalExpiry(pendingQuestion, payload)) return;
+ const expiredRid =
+ (typeof payload.request_id === 'string' && payload.request_id.trim()) ||
+ pendingQuestion?.request_id ||
+ '';
+ if (sessionId.startsWith('cron_') && expiredRid) {
+ dismissCronAskUser(sessionId, expiredRid);
+ }
useChatStore.getState().setPendingQuestion(sessionId, null);
if (payload.reason === 'timeout') {
// timeout 后子 Agent 仍会继续加载或获得一次模型恢复机会
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 19017b4515..1733aa3cc6 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -1813,7 +1813,8 @@
"updated": "Task updated successfully",
"deleted": "Task deleted successfully",
"statusUpdated": "Task status updated successfully",
- "runNow": "Task triggered successfully"
+ "runNow": "Task triggered successfully",
+ "runNowPendingApproval": "Previous tool approval is still pending; opened the waiting session"
},
"preview": {
"loading": "Loading next runs...",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 014d30eb89..83e2137686 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -1800,7 +1800,8 @@
"updated": "任务更新成功",
"deleted": "任务删除成功",
"statusUpdated": "任务状态更新成功",
- "runNow": "任务已触发立即执行"
+ "runNow": "任务已触发立即执行",
+ "runNowPendingApproval": "上一轮工具审批未完成,已打开待确认窗口"
},
"preview": {
"loading": "正在加载下次触发时间...",
diff --git a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webClient.ts
index 67b2b14fc9..508c4501a8 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts
+++ b/jiuwenswarm/channels/web/frontend/src/services/webClient.ts
@@ -158,6 +158,11 @@ class WebClient {
this.dispatchEventToHandlers(event);
}
+ /** 把定时任务监听流上的帧送进现有 chat.* 处理。 */
+ injectEvent(event: WsEvent): void {
+ this.dispatchEvent(event);
+ }
+
async connect(options: WebConnectOptions = {}): Promise<void> {
if (this.ws?.readyState === WebSocket.OPEN) {
return;
diff --git a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
index af9f8376bd..c92086ead4 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
+++ b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
@@ -1047,6 +1047,11 @@ export class WebHttpClient {
return fetch(input, init);
}
+ /** 把定时任务监听流上的帧送进现有 chat.* 处理。 */
+ injectEvent(event: WsEvent): void {
+ this.dispatchEvent(event);
+ }
+
private dispatchEvent(event: WsEvent): void {
if (this.streamEventFilter && !this.streamEventFilter(event)) {
return;
diff --git a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts
index 41bc445cd4..e811c5723d 100644
--- a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts
+++ b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts
@@ -213,6 +213,8 @@ interface ChatState {
addMessage: (sessionId: string, message: Message) => void;
replaceHistoryMessages: (sessionId: string, messages: Message[]) => void;
+ /** 只替换消息列表,保留思考/工具/审批卡等实时态(cron 监听流进行中用)。 */
+ applyHistoryMessagesKeepLive: (sessionId: string, messages: Message[]) => void;
updateMessage: (sessionId: string, id: string, updates: Partial<Message>) => void;
appendStreamContent: (sessionId: string, content: string, streamKey?: string) => void;
appendReasoning: (sessionId: string, content: string, options?: { atMs?: number }) => void;
@@ -381,6 +383,41 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)
});
},
+ applyHistoryMessagesKeepLive: (sessionId, messages) => {
+ set((state) => {
+ const runtime = state.runtimes[sessionId];
+ if (!runtime) return state;
+ // Keep the in-flight streaming bubble: a mid-run history refresh must not
+ // drop currentStreamId's message, or later deltas append into a void and
+ // the visible text can diverge from the authoritative final.
+ const liveTail: Message[] = [];
+ if (runtime.currentStreamId) {
+ const streaming = runtime.messages.find((m) => m.id === runtime.currentStreamId);
+ if (streaming && !messages.some((m) => m.id === streaming.id)) {
+ liveTail.push(streaming);
+ }
+ }
+ for (const msg of runtime.messages) {
+ if (msg.isStreaming && msg.id !== runtime.currentStreamId) {
+ if (!messages.some((m) => m.id === msg.id) && !liveTail.some((m) => m.id === msg.id)) {
+ liveTail.push(msg);
+ }
+ }
+ }
+ const assigned = assignMessageRenderKeys(runtime, messages.concat(liveTail));
+ return {
+ runtimes: {
+ ...state.runtimes,
+ [sessionId]: {
+ ...runtime,
+ messages: assigned.messages,
+ messageRenderKeySeq: assigned.messageRenderKeySeq,
+ },
+ },
+ };
+ });
+ },
+
updateMessage: (sessionId, id, updates) => {
set((state) => {
const runtime = state.runtimes[sessionId];
diff --git a/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts
index 537da7d04e..2512709ffc 100644
--- a/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts
+++ b/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts
@@ -2,12 +2,15 @@ import { create } from 'zustand';
import {
buildCronJobFingerprintMap,
detectCronJobRunUpdates,
+ resolveOpenCronHistoryRefresh,
type CronJobRunFingerprint,
} from '../features/cron/cronJobSync';
+import { settleCronSessionRuntime } from '../features/cron/cronLiveWatch';
import { projectRegistryClient } from '../features/workspace/projectRegistryClient';
import { webRequest } from '../services/webClient';
import type { Session } from '../types';
import { useChatStore } from './chatStore';
+import { useSessionStore } from './sessionStore';
export interface SidebarCronJob {
id: string;
@@ -45,9 +48,8 @@ interface CronState {
// job_id → 最近"立即执行"返回的 session_id,用于广播消息路由
lastRunSessionId: Record<string, string>;
setLastRunSessionId: (jobId: string, sessionId: string) => void;
- // 轮询检测到「当前正打开会话 == 某 job 新 last_session_id」时,投递一次历史刷新请求。
- // 企业版 HTTP 无 cron 结果 push,立即执行跳转后 skipHistoryLoad,消息两头落空;
- // 这里用 30s 轮询作为兜底:命中就把 session_id 交给 App.tsx 触发 startHistoryRestore。
+ // 企业版 HTTP 无 cron 结果 push。30s 轮询发现任务跑完后,若当前窗口属于这次任务
+ // (含连续执行时已被下一次盖住的上一个 cron_*),投递一次历史刷新。
pendingActiveHistoryRefresh: string | null;
requestActiveHistoryRefresh: (sessionId: string) => void;
consumeActiveHistoryRefresh: () => string | null;
@@ -78,6 +80,20 @@ function persistCronUnread(state: Record<string, boolean>) {
});
}
+function cronIdOfSession(sessionId: string): string {
+ const sid = sessionId.trim();
+ if (!sid) {
+ return '';
+ }
+ const sessionState = useSessionStore.getState();
+ const current = sessionState.currentSession;
+ if (current?.session_id === sid) {
+ return (current.cron_id || '').trim();
+ }
+ const listed = sessionState.sessions.find((item) => item.session_id === sid);
+ return (listed?.cron_id || '').trim();
+}
+
async function fetchWebCronJobs(): Promise<SidebarCronJob[]> {
const payload = await webRequest<{ jobs: SidebarCronJob[] }>('cron.job.list');
return (payload.jobs || []).filter((job) => isWebChannelJob(job.targets));
@@ -137,6 +153,15 @@ export const useCronStore = create<CronState>((set, get) => ({
isLoading: false,
runSyncFingerprints: buildCronJobFingerprintMap(webJobs),
});
+ // CronPanel 约 5s 静默刷新会走这里;比 30s syncJobRuns 更快收口漏掉的 processing。
+ const activeSid = (useChatStore.getState().activeSessionId || '').trim();
+ for (const job of webJobs) {
+ const lastSid = (job.last_session_id ?? '').trim();
+ if (!lastSid) continue;
+ if (settleCronSessionRuntime(lastSid) && lastSid === activeSid) {
+ get().requestActiveHistoryRefresh(lastSid);
+ }
+ }
} catch {
set({ jobs: [], isLoading: false, runSyncFingerprints: {} });
}
@@ -153,28 +178,55 @@ export const useCronStore = create<CronState>((set, get) => ({
runSyncFingerprints: nextFingerprints,
});
- const activeSessionId = useChatStore.getState().activeSessionId;
+ const activeSessionId = (useChatStore.getState().activeSessionId || '').trim();
const projectIdsToRefresh = new Set<string>();
+ // last_session_id 在 agent stream 返回后回写 = 该趟已结束/进审批。
+ // 连点立即执行切走时 live 可能漏收尾;这里收口仍标 processing 的 UI
+ // (pendingQuestion 时 settle 内部会跳过)。
+ for (const job of webJobs) {
+ const lastSid = (job.last_session_id ?? '').trim();
+ if (!lastSid) continue;
+ if (settleCronSessionRuntime(lastSid) && lastSid === activeSessionId) {
+ get().requestActiveHistoryRefresh(lastSid);
+ }
+ }
+
for (const jobId of updatedJobIds) {
const job = webJobs.find((item) => item.id === jobId);
const lastSid = (job?.last_session_id ?? '').trim();
const projectId = job?.project_id || 'default';
+ const prevLastSid = (previous[jobId]?.lastSessionId || '').trim();
+ const rememberedSid = (get().lastRunSessionId[jobId] || '').trim();
+ // 上一趟会话也可能卡在 processing(指纹已从旧 sid 跳到新 sid)。
+ if (prevLastSid && prevLastSid !== lastSid) {
+ settleCronSessionRuntime(prevLastSid);
+ }
+ if (rememberedSid && rememberedSid !== lastSid) {
+ settleCronSessionRuntime(rememberedSid);
+ }
// 侧栏会话组读 projectCronSessions。本函数只挂在企业版 HTTP 的 30s 轮询上,
// 个人版 WS 推送不走这里。
projectIdsToRefresh.add(projectId);
- // 当前正打开的会话恰好是这次新产生的 cron 会话:企业版 HTTP 无 push,
- // 立即执行跳转后 skipHistoryLoad,消息两头落空。这里用轮询兜底——
- // 投递一次历史刷新请求,并直接清掉蓝点(消息即将实打实显示出来)。
- if (lastSid && activeSessionId && lastSid === activeSessionId) {
+ // 正看着的 cron_* 属于这个任务时再读一次历史。最新会话被下一次执行盖住时,
+ // 仍刷新当前窗口,避免必须手动刷新才看得到已落盘的回复。
+ const refreshSid = resolveOpenCronHistoryRefresh({
+ jobId,
+ lastSessionId: lastSid,
+ activeSessionId,
+ activeCronId: cronIdOfSession(activeSessionId),
+ rememberedRunSessionId: rememberedSid,
+ });
+ const viewingLatest = Boolean(lastSid && activeSessionId && lastSid === activeSessionId);
+ if (viewingLatest) {
get().clearCronJobUnread(jobId);
- get().requestActiveHistoryRefresh(lastSid);
- if (job) {
- void get().loadCronSessions(projectId, jobId);
- }
- continue;
+ } else {
+ get().markCronJobUnread(jobId);
+ }
+ // cron 进行中 restore 会 keep-live,可安全补任务内容 user 消息。
+ if (refreshSid) {
+ get().requestActiveHistoryRefresh(refreshSid);
}
- get().markCronJobUnread(jobId);
if (job) {
void get().loadCronSessions(projectId, jobId);
}
diff --git a/jiuwenswarm/channels/web/frontend/tests/cronJobSync.test.mjs b/jiuwenswarm/channels/web/frontend/tests/cronJobSync.test.mjs
index ff31f1e91d..903dd04bdc 100644
--- a/jiuwenswarm/channels/web/frontend/tests/cronJobSync.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/cronJobSync.test.mjs
@@ -5,6 +5,7 @@ import {
buildCronJobFingerprintMap,
detectCronJobRunUpdates,
fingerprintFromCronJob,
+ resolveOpenCronHistoryRefresh,
} from '../node_modules/.cache/cron-job-sync/cronJobSync.mjs';
test('fingerprintFromCronJob normalizes last_session_id (ignores last_run_at)', () => {
@@ -49,6 +50,45 @@ test('detectCronJobRunUpdates ignores last_run_at-only changes', () => {
assert.deepEqual(result.updatedJobIds, []);
});
+test('resolveOpenCronHistoryRefresh reloads the open window of the same job', () => {
+ assert.equal(
+ resolveOpenCronHistoryRefresh({
+ jobId: 'job-1',
+ lastSessionId: 'cron_latest',
+ activeSessionId: 'cron_watching',
+ activeCronId: 'job-1',
+ rememberedRunSessionId: '',
+ }),
+ 'cron_watching',
+ );
+});
+
+test('resolveOpenCronHistoryRefresh keeps the run-now window after a later run finishes', () => {
+ assert.equal(
+ resolveOpenCronHistoryRefresh({
+ jobId: 'job-1',
+ lastSessionId: 'cron_later',
+ activeSessionId: 'cron_clicked',
+ activeCronId: '',
+ rememberedRunSessionId: 'cron_clicked',
+ }),
+ 'cron_clicked',
+ );
+});
+
+test('resolveOpenCronHistoryRefresh skips unrelated sessions', () => {
+ assert.equal(
+ resolveOpenCronHistoryRefresh({
+ jobId: 'job-1',
+ lastSessionId: 'cron_latest',
+ activeSessionId: 'sess_chat',
+ activeCronId: '',
+ rememberedRunSessionId: 'cron_other',
+ }),
+ '',
+ );
+});
+
test('detectCronJobRunUpdates ignores unchanged snapshots', () => {
const jobs = [{ id: 'job-1', last_run_at: 100, last_session_id: 'cron_a' }];
const previous = buildCronJobFingerprintMap(jobs);
diff --git a/jiuwenswarm/channels/web/frontend/tests/cronLiveSkipReplayUpgrade.test.mjs b/jiuwenswarm/channels/web/frontend/tests/cronLiveSkipReplayUpgrade.test.mjs
new file mode 100644
index 0000000000..5c7233344b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/cronLiveSkipReplayUpgrade.test.mjs
@@ -0,0 +1,40 @@
+/**
+ * Mirrors src/features/cron/cronLiveSkipReplayPolicy.ts
+ * (no tsc/esbuild required in minimal CI images).
+ */
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+function shouldDeferCronLiveSkipReplayUpgrade(runtime) {
+ if (!runtime) return false;
+ return Boolean(
+ runtime.isProcessing || runtime.currentStreamId || runtime.pendingQuestion,
+ );
+}
+
+test('shouldDeferCronLiveSkipReplayUpgrade: streaming / processing / ask', () => {
+ assert.equal(shouldDeferCronLiveSkipReplayUpgrade(null), false);
+ assert.equal(shouldDeferCronLiveSkipReplayUpgrade({}), false);
+ assert.equal(
+ shouldDeferCronLiveSkipReplayUpgrade({ isProcessing: true }),
+ true,
+ );
+ assert.equal(
+ shouldDeferCronLiveSkipReplayUpgrade({ currentStreamId: 'assistant-1' }),
+ true,
+ );
+ assert.equal(
+ shouldDeferCronLiveSkipReplayUpgrade({
+ pendingQuestion: { request_id: 'ask-1' },
+ }),
+ true,
+ );
+ assert.equal(
+ shouldDeferCronLiveSkipReplayUpgrade({
+ isProcessing: false,
+ currentStreamId: null,
+ pendingQuestion: null,
+ }),
+ false,
+ );
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/cronPermissionRetain.test.mjs b/jiuwenswarm/channels/web/frontend/tests/cronPermissionRetain.test.mjs
new file mode 100644
index 0000000000..d838f3477e
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/cronPermissionRetain.test.mjs
@@ -0,0 +1,50 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+/**
+ * Mirrors shouldRetainCronPermissionOnProcessingFalse in cronLiveWatch.ts.
+ * Keep in sync when changing retain rules for cron HITL + spurious processing=false.
+ */
+function isCronPermissionPromptSource(source) {
+ const src = String(source || '').trim();
+ return !src || src === 'permission_interrupt' || src === 'confirm_interrupt';
+}
+
+function shouldRetainCronPermissionOnProcessingFalse(sessionId, pending) {
+ const sid = String(sessionId || '').trim();
+ if (!sid.startsWith('cron_')) return false;
+ if (!pending) return false;
+ return isCronPermissionPromptSource(pending.source);
+}
+
+test('retain only on cron_* with permission/confirm pending', () => {
+ assert.equal(
+ shouldRetainCronPermissionOnProcessingFalse('cron_abc', {
+ source: 'permission_interrupt',
+ }),
+ true,
+ );
+ assert.equal(
+ shouldRetainCronPermissionOnProcessingFalse('cron_abc', {
+ source: 'confirm_interrupt',
+ }),
+ true,
+ );
+ assert.equal(
+ shouldRetainCronPermissionOnProcessingFalse('cron_abc', { source: '' }),
+ true,
+ );
+ assert.equal(
+ shouldRetainCronPermissionOnProcessingFalse('chat_abc', {
+ source: 'permission_interrupt',
+ }),
+ false,
+ );
+ assert.equal(
+ shouldRetainCronPermissionOnProcessingFalse('cron_abc', {
+ source: 'ask_user_interrupt',
+ }),
+ false,
+ );
+ assert.equal(shouldRetainCronPermissionOnProcessingFalse('cron_abc', null), false);
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/historyRestoreSourceSkill.test.mjs b/jiuwenswarm/channels/web/frontend/tests/historyRestoreSourceSkill.test.mjs
index 109481b601..36883a5e24 100644
--- a/jiuwenswarm/channels/web/frontend/tests/historyRestoreSourceSkill.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/historyRestoreSourceSkill.test.mjs
@@ -87,3 +87,74 @@ test('history replay without source_skill stays undefined (no fake value)', () =
assert.ok(execution);
assert.equal(execution.toolCall.source_skill, undefined);
});
+
+const PERMISSION_ASK = {
+ role: 'assistant',
+ request_id: 'tool-call-1#1',
+ channel_id: 'web',
+ timestamp: 1757800100,
+ event_type: 'chat.ask_user_question',
+ content: '',
+ source: 'permission_interrupt',
+ questions: [
+ {
+ question: '工具 read_file 需要授权才能执行',
+ options: [{ label: '本次允许' }],
+ },
+ ],
+};
+
+test('answered with stripped hitl suffix clears pending permission card', () => {
+ const { pendingAskUser } = parseHistoryJsonFileToTimelinePreview(
+ [
+ PERMISSION_ASK,
+ {
+ role: 'assistant',
+ request_id: 'tool-call-1',
+ channel_id: 'web',
+ timestamp: 1757800101,
+ event_type: 'chat.ask_user_answered',
+ content: '',
+ status: 'answered',
+ },
+ {
+ role: 'assistant',
+ request_id: 'tool-call-1',
+ channel_id: 'web',
+ timestamp: 1757800102,
+ event_type: 'chat.final',
+ content: '验证完成:read_file 工具可以正常执行。',
+ },
+ ],
+ 'cron_perm_1',
+ );
+ assert.equal(pendingAskUser, null);
+});
+
+test('permission ask without answer but with later final does not revive card', () => {
+ const { pendingAskUser } = parseHistoryJsonFileToTimelinePreview(
+ [
+ PERMISSION_ASK,
+ {
+ role: 'assistant',
+ request_id: 'cron-rid',
+ channel_id: 'web',
+ timestamp: 1757800105,
+ event_type: 'chat.final',
+ content: '验证完成:read_file 工具可以正常执行。',
+ },
+ ],
+ 'cron_perm_2',
+ );
+ assert.equal(pendingAskUser, null);
+});
+
+test('unanswered permission ask stays pending when run did not continue', () => {
+ const { pendingAskUser } = parseHistoryJsonFileToTimelinePreview(
+ [PERMISSION_ASK],
+ 'cron_perm_3',
+ );
+ assert.ok(pendingAskUser);
+ assert.equal(pendingAskUser.request_id, 'tool-call-1#1');
+ assert.equal(pendingAskUser.source, 'permission_interrupt');
+});
diff --git a/jiuwenswarm/extensions/redis/__init__.py b/jiuwenswarm/extensions/redis/__init__.py
index 2ce726f84e..a695aec1d1 100644
--- a/jiuwenswarm/extensions/redis/__init__.py
+++ b/jiuwenswarm/extensions/redis/__init__.py
@@ -5,6 +5,9 @@ from jiuwenswarm.extensions.redis.redis_client import RedisClient, RedisConfig
from jiuwenswarm.extensions.redis.redis_keys import (
cron_jobs_hash_key,
cron_jobs_hash_rel,
+ cron_live_channel_rel,
+ cron_live_replay_key_rel,
+ cron_permission_hold_rel,
leader_lock_key,
session_map_hash_key,
)
@@ -13,6 +16,7 @@ from jiuwenswarm.extensions.redis.redis_runtime import (
get_effective_distributed_redis_active,
get_gateway_instance_id,
get_gateway_redis_client,
+ get_gateway_redis_client_if_open,
init_gateway_redis_from_config,
is_redis_degraded,
shutdown_gateway_redis,
@@ -23,10 +27,14 @@ __all__ = [
"RedisConfig",
"cron_jobs_hash_key",
"cron_jobs_hash_rel",
+ "cron_live_channel_rel",
+ "cron_live_replay_key_rel",
+ "cron_permission_hold_rel",
"get_declared_deployment_mode",
"get_effective_distributed_redis_active",
"get_gateway_instance_id",
"get_gateway_redis_client",
+ "get_gateway_redis_client_if_open",
"init_gateway_redis_from_config",
"is_redis_degraded",
"leader_lock_key",
diff --git a/jiuwenswarm/extensions/redis/redis_client.py b/jiuwenswarm/extensions/redis/redis_client.py
index b0cb8655d5..a3cdd7b3a5 100644
--- a/jiuwenswarm/extensions/redis/redis_client.py
+++ b/jiuwenswarm/extensions/redis/redis_client.py
@@ -234,6 +234,38 @@ class RedisClient:
r = self._connection()
return bool(await r.expire(self._cfg.effective_key(key), int(ttl_seconds)))
+ async def rpush(self, key: str, *values: Any) -> int:
+ r = self._connection()
+ if not values:
+ return 0
+ encoded = [v if isinstance(v, str) else str(v) for v in values]
+ return int(await r.rpush(self._cfg.effective_key(key), *encoded))
+
+ @staticmethod
+ def _as_text(value: Any) -> str:
+ if value is None:
+ return ""
+ if isinstance(value, str):
+ return value
+ if isinstance(value, (bytes, bytearray)):
+ return bytes(value).decode("utf-8", errors="replace")
+ return str(value)
+
+ async def lrange(self, key: str, start: int, stop: int) -> list[str]:
+ r = self._connection()
+ raw = await r.lrange(self._cfg.effective_key(key), int(start), int(stop))
+ out: list[str] = []
+ for item in raw or []:
+ if item is None:
+ continue
+ out.append(self._as_text(item))
+ return out
+
+ async def ltrim(self, key: str, start: int, stop: int) -> bool:
+ r = self._connection()
+ await r.ltrim(self._cfg.effective_key(key), int(start), int(stop))
+ return True
+
async def delete(self, key: str) -> bool:
r = self._connection()
n = int(await r.delete(self._cfg.effective_key(key)))
@@ -332,8 +364,9 @@ class RedisClient:
continue
if msg.get("type") != "message":
continue
- data = msg.get("data")
- yield data if isinstance(data, str) else str(data)
+ text = self._as_text(msg.get("data"))
+ if text:
+ yield text
finally:
try:
await pubsub.unsubscribe(ch)
diff --git a/jiuwenswarm/extensions/redis/redis_keys.py b/jiuwenswarm/extensions/redis/redis_keys.py
index c8af8257b4..29fd23c6dd 100644
--- a/jiuwenswarm/extensions/redis/redis_keys.py
+++ b/jiuwenswarm/extensions/redis/redis_keys.py
@@ -35,3 +35,35 @@ def cron_jobs_hash_key(key_prefix: str, gateway_instance_id: str) -> str:
def leader_lock_key(key_prefix: str, channel_id: str) -> str:
"""``{key_prefix}gateway:leader:{channel_id}`` String(带 TTL)。"""
return f"{_normalize_prefix(key_prefix)}gateway:leader:{channel_id}"
+
+
+def cron_live_channel_rel(session_id: str) -> str:
+ """``gateway:cron_live:{session_id}`` Pub/Sub 频道(相对名,经 RedisClient 加 prefix)。"""
+ sid = str(session_id or "").strip()
+ if not sid:
+ raise ValueError("session_id is required")
+ return f"gateway:cron_live:{sid}"
+
+
+def cron_live_replay_key_rel(session_id: str) -> str:
+ """``gateway:cron_live_replay:{session_id}`` List(相对名;短 TTL 晚订回放)。"""
+ sid = str(session_id or "").strip()
+ if not sid:
+ raise ValueError("session_id is required")
+ return f"gateway:cron_live_replay:{sid}"
+
+
+def cron_permission_hold_rel(job_id: str) -> str:
+ """``gateway:cron_permission_hold:{job_id}`` String(相对名;TTL=审批窗口)。"""
+ jid = str(job_id or "").strip()
+ if not jid:
+ raise ValueError("job_id is required")
+ return f"gateway:cron_permission_hold:{jid}"
+
+
+def cron_permission_hold_by_session_rel(session_id: str) -> str:
+ """``gateway:cron_permission_hold_by_session:{session_id}`` → job_id(跨进程释放)。"""
+ sid = str(session_id or "").strip()
+ if not sid:
+ raise ValueError("session_id is required")
+ return f"gateway:cron_permission_hold_by_session:{sid}"
diff --git a/jiuwenswarm/extensions/redis/redis_runtime.py b/jiuwenswarm/extensions/redis/redis_runtime.py
index 9b70505c2e..eca278fadc 100644
--- a/jiuwenswarm/extensions/redis/redis_runtime.py
+++ b/jiuwenswarm/extensions/redis/redis_runtime.py
@@ -92,6 +92,18 @@ def get_gateway_redis_client() -> Any | None:
return _redis_client
+def get_gateway_redis_client_if_open() -> Any | None:
+ """返回已 ``open`` 成功的 Redis 客户端(最佳努力)。
+
+ 与 :func:`get_gateway_redis_client` 的差异:不要求
+ ``get_effective_distributed_redis_active()``(健康检查 degraded 时仍可用)。
+ ``deployment_mode=standalone`` 未初始化 Redis 时仍为 ``None``。
+
+ 供 cron live 跨副本扇出等「有则用、无则本机降级」的路径。
+ """
+ return _redis_client
+
+
async def _ping_with_retries(client: Any, *, attempts: int) -> bool:
for i in range(attempts):
if await client.ping():
@@ -161,12 +173,15 @@ async def init_gateway_redis_from_config(full_cfg: dict[str, Any] | None) -> Non
# 仅 standalone 跳过 Redis init;active-standby / distributed 都需要连 Redis
if _declared_deployment_mode == "standalone":
- logger.debug("[GatewayRedis] deployment_mode=standalone; skip Redis init (§3.3.4)")
+ logger.info(
+ "[GatewayRedis] deployment_mode=standalone; skip Redis init (§3.3.4) "
+ "(multi-replica cron live fanout requires distributed|active-standby)"
+ )
return
# 企业版特性:仅企业版开启时启用主备 Redis
if not is_enterprise():
- logger.debug(
+ logger.warning(
"[GatewayRedis] deployment_mode=%s but not enterprise edition; skip Redis init",
_declared_deployment_mode,
)
diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_connect.py
index a1f3f0890e..4f16569486 100644
--- a/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_connect.py
@@ -2596,9 +2596,22 @@ class FeishuChannel(BaseChannel):
options = question.get("options", [])
if options:
actions = []
+ cron_exec_session_id = str(
+ payload.get("exec_session_id") or payload.get("session_id") or ""
+ ).strip()
+ card_meta = msg.metadata if isinstance(getattr(msg, "metadata", None), dict) else {}
for option in options:
label = option.get("label", "")
- # value = json.dumps({"label": label}, ensure_ascii=False)
+ button_value = {"label": label, "request_id": request_id}
+ # 只有定时任务卡片带回 cron_*,回调才改走 chat.send 续跑。
+ if cron_exec_session_id.startswith("cron_"):
+ button_value["exec_session_id"] = cron_exec_session_id
+ feishu_chat_id = str(card_meta.get("feishu_chat_id") or "").strip()
+ feishu_open_id = str(card_meta.get("feishu_open_id") or "").strip()
+ if feishu_chat_id:
+ button_value["feishu_chat_id"] = feishu_chat_id
+ if feishu_open_id:
+ button_value["feishu_open_id"] = feishu_open_id
button_element = {
"tag": "button",
"text": {
@@ -2606,7 +2619,7 @@ class FeishuChannel(BaseChannel):
"content": label
},
"type": "primary",
- "value": {"label": label, "request_id": request_id}
+ "value": button_value
}
actions.append(button_element)
@@ -2989,15 +3002,58 @@ class FeishuChannel(BaseChannel):
request_id = action_value.pop("request_id", "")
if not request_id:
raise ValueError("missing request_id")
- # 构建用户响应(符合 evolution service 期望的格式)
- answers = [{"selected_options": list(action_value.values())}] if action_value else []
+ exec_session_id = str(action_value.pop("exec_session_id", "") or "").strip()
+ feishu_chat_id = str(action_value.pop("feishu_chat_id", "") or "").strip()
+ feishu_open_id = str(action_value.pop("feishu_open_id", "") or "").strip()
+ selected_label = str(action_value.get("label") or "").strip()
+ if selected_label:
+ answers = [{"selected_options": [selected_label]}]
+ elif action_value:
+ answers = [{"selected_options": list(action_value.values())}]
+ else:
+ answers = []
logger.info(
"[FeishuChannel] 发送用户答案: token=%s, answer=%s",
token,
action_value,
)
- msg = Message(
+ if exec_session_id.startswith("cron_"):
+ resume_meta = {
+ "request_id": token,
+ "answers": answers,
+ }
+ if feishu_chat_id:
+ resume_meta["feishu_chat_id"] = feishu_chat_id
+ if feishu_open_id or operator_id:
+ resume_meta["feishu_open_id"] = feishu_open_id or operator_id
+ msg = Message(
+ id=token,
+ type="req",
+ channel_id=self.channel_id,
+ session_id=exec_session_id,
+ params={
+ "query": "",
+ "content": "",
+ "answers": answers,
+ "request_id": request_id,
+ "source": "permission_interrupt",
+ "session_id": exec_session_id,
+ },
+ timestamp=time.time(),
+ ok=True,
+ req_method=ReqMethod.CHAT_SEND,
+ is_stream=True,
+ enable_streaming=True,
+ provider=self.name,
+ chat_id=feishu_chat_id or operator_id,
+ user_id=operator_id,
+ bot_id=self.config.app_id,
+ event_type=None,
+ metadata=resume_meta,
+ )
+ else:
+ msg = Message(
id=token,
type="event",
channel_id=self.channel_id,
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index bf03ab22dc..4b3f7cba6f 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -7439,13 +7439,17 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
run_info = await cc.run_now_with_session(
job_id, group_id=g, bot_id=b, user_id=u
)
+ payload = {
+ "accepted": True,
+ "run_id": run_info.get("run_id", ""),
+ "session_id": run_info.get("session_id", ""),
+ }
+ if run_info.get("reused_pending_session") or run_info.get("awaiting_approval"):
+ payload["awaiting_approval"] = True
+ payload["reused_pending_session"] = True
await channel.send_response(
ws, req_id, ok=True,
- payload={
- "accepted": True,
- "run_id": run_info.get("run_id", ""),
- "session_id": run_info.get("session_id", ""),
- },
+ payload=payload,
)
except KeyError:
await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
index 5e08c3e120..37d594cac6 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
@@ -59,6 +59,97 @@ def _request_client_host(request: Request) -> str | None:
host = str(getattr(client, "host", "") or "").strip()
return host or None
+
+async def _authorize_cron_session_live(
+ request: Request, session_id: str,
+) -> JSONResponse | None:
+ """Gate ``/sessions/{cron_*}/live`` with the same identity scope as history.
+
+ Returns an error response when denied; ``None`` when the subscribe may proceed.
+ Non-remote (personal / local file) deployments skip the PG ownership check.
+ Remote/enterprise: fail-closed on store errors; missing/foreign session → 404.
+ """
+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage
+
+ # Personal / local-file history: no shared multi-tenant store to consult.
+ if not is_remote_storage():
+ return None
+
+ uid = (request.headers.get("x-user-id") or "").strip() or "guest"
+ group_id = (request.headers.get("x-group-id") or "").strip() or None
+ bot_id = (request.headers.get("x-bot-id") or "").strip() or None
+ try:
+ from jiuwenswarm.channels.web.history_store.api import get_session_detail_sync
+
+ detail = await asyncio.to_thread(
+ get_session_detail_sync,
+ session_id,
+ None,
+ user=uid,
+ group_id=group_id,
+ bot_id=bot_id,
+ )
+ except Exception: # noqa: BLE001
+ logger.exception(
+ "[WebHTTP] cron live auth store error session_id=%s", session_id,
+ )
+ return JSONResponse({"error": "auth_unavailable"}, status_code=503)
+
+ if detail is None:
+ # Brand-new cron_* may not be in PG yet (run_now race). Allow only when
+ # this gateway already has an in-flight hold / live buffer for the sid.
+ if _cron_live_inflight_locally(session_id):
+ return None
+ return JSONResponse({"error": "forbidden"}, status_code=404)
+ return None
+
+
+def _cron_live_inflight_locally(session_id: str) -> bool:
+ """True when this process already tracks the cron session (hold / run / live bus)."""
+ sid = str(session_id or "").strip()
+ if not sid:
+ return False
+ try:
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus
+
+ if sid in getattr(cron_live_bus, "_replay", {}) or sid in getattr(
+ cron_live_bus, "_subscribers", {},
+ ):
+ return True
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ from jiuwenswarm.gateway.cron.tenant_registry import CronTenantRegistry
+
+ registry = CronTenantRegistry.try_get_instance()
+ if registry is None:
+ return False
+ for controller in list(getattr(registry, "_controllers", {}).values()):
+ scheduler = getattr(controller, "_scheduler", None)
+ if scheduler is None:
+ continue
+ holds = getattr(scheduler, "_permission_hold", None)
+ if isinstance(holds, dict):
+ for item in list(holds.values()):
+ if not item:
+ continue
+ held_sid = item[1] if isinstance(item, tuple) and len(item) > 1 else ""
+ if str(held_sid or "").strip() == sid:
+ return True
+ runs = getattr(scheduler, "_runs", None)
+ if isinstance(runs, dict):
+ for state in runs.values():
+ if str(getattr(state, "exec_session_id", "") or "").strip() != sid:
+ continue
+ if str(getattr(state, "status", "") or "") in {
+ "running",
+ "awaiting_approval",
+ }:
+ return True
+ except Exception: # noqa: BLE001
+ return False
+ return False
+
_STREAM_RPC_METHODS = frozenset({"chat.send", "history.get"})
# AgentServer 本地历史缺失(mnt pod 回收后按需重新拉起为空目录)时其 history.get
@@ -504,6 +595,57 @@ def create_web_http_app(channel: Any) -> FastAPI:
return await _stream(request, channel, "history.get", params)
return await _history_json(request, channel, params)
+ @app.get(
+ "/api/v1/sessions/{session_id}/live",
+ tags=["sessions"],
+ summary="订阅正在执行的 cron_* 窗口(思考、正文、审批卡)",
+ )
+ async def session_live(session_id: str, request: Request) -> Response:
+ sid = str(session_id or "").strip()
+ if not sid.startswith("cron_"):
+ return JSONResponse({"error": "not_cron_session"}, status_code=404)
+
+ # Same ownership bar as history/session reads: knowing cron_* must not
+ # be enough to subscribe to thinking / tool args / permission cards.
+ auth_error = await _authorize_cron_session_live(request, sid)
+ if auth_error is not None:
+ return auth_error
+
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus
+
+ # History-first refresh passes skip_replay=1 so buffered thinking /
+ # ask_user from a finished (or already-restored) run cannot rebuild UI.
+ skip_replay = str(request.query_params.get("skip_replay") or "").strip() in {
+ "1",
+ "true",
+ "yes",
+ }
+ queue = cron_live_bus.subscribe(sid, replay=not skip_replay)
+
+ async def _frames() -> AsyncIterator[str]:
+ try:
+ while True:
+ if await request.is_disconnected():
+ return
+ try:
+ frame = await asyncio.wait_for(queue.get(), timeout=15.0)
+ except asyncio.TimeoutError:
+ yield ": keepalive\n\n"
+ continue
+ event_name = str(frame.get("event") or "message")
+ yield _sse_pack(sid, event_name, frame)
+ finally:
+ cron_live_bus.unsubscribe(sid, queue)
+
+ return StreamingResponse(
+ _frames(),
+ media_type="text/event-stream",
+ headers={
+ "Cache-Control": "no-cache",
+ "X-Accel-Buffering": "no",
+ },
+ )
+
@app.post(
"/api/v1/chat/completions",
tags=["chat"],
diff --git a/jiuwenswarm/gateway/cron/controller.py b/jiuwenswarm/gateway/cron/controller.py
index 917ffb90fd..46545ea8e2 100644
--- a/jiuwenswarm/gateway/cron/controller.py
+++ b/jiuwenswarm/gateway/cron/controller.py
@@ -534,7 +534,7 @@ class CronController:
run_id = await self._scheduler.trigger_run_now(job_id)
return run_id
- async def run_now_info(self, job_id: str) -> dict[str, str]:
+ async def run_now_info(self, job_id: str) -> dict[str, Any]:
return await self._scheduler.trigger_run_now_info(job_id)
async def run_now_with_session(
@@ -544,12 +544,15 @@ class CronController:
group_id: str | None = None,
bot_id: str | None = None,
user_id: str | None = None,
- ) -> dict[str, str]:
+ ) -> dict[str, Any]:
"""web「立即执行」:校验归属并提前创建真实执行会话,返回给前端跳转。
与 ``run_now`` 的差异仅在返回真实 session_id(非 team 模式预分配会话),
避免前端跳到占位 ``cron_<ts>_<job.id>`` 空会话。预分配失败降级为占位,
执行阶段仍会兜底创建。
+
+ 若该任务仍有未完成的工具审批 hold,直接复用旧 ``cron_*``(
+ ``reused_pending_session=True``),不再新建空会话。
"""
job = await self._store.get_job(job_id)
if job is None:
diff --git a/jiuwenswarm/gateway/cron/live_bus.py b/jiuwenswarm/gateway/cron/live_bus.py
new file mode 100644
index 0000000000..f5ac3a1b7c
--- /dev/null
+++ b/jiuwenswarm/gateway/cron/live_bus.py
@@ -0,0 +1,495 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.
+
+"""Fanout for cron execution frames (local + optional Redis).
+
+Enterprise HTTP pages are not gateway WebSocket clients, so a cron run's
+reasoning and deltas never reach the open ``cron_*`` window through
+``WebChannel`` broadcast. The scheduler mirrors those frames here, and the
+session live SSE subscribes while that window is open.
+
+``run_now`` often returns the session id *after* the agent has already
+streamed the first reasoning tokens. Without a short replay buffer those
+frames are gone by the time the browser opens ``/sessions/{cron_*}/live``,
+so the UI jumps straight to the permission card and only shows thinking
+after approve (via the resume ``chat.send`` SSE).
+
+Multi-replica gateways: the scheduler publishes on one pod while the browser
+``GET .../live`` may land on another. When Gateway Redis is active we also
+PUBLISH frames and keep a short Redis list for late joiners, so any pod can
+serve the live SSE.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import os
+import time
+import uuid
+from collections import deque
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+def _process_unique_suffix() -> str:
+ """Per-pod / per-process id so Redis echo-skip cannot drop cross-replica frames.
+
+ Enterprise deploy sets the same ``GATEWAY_INSTANCE_ID`` on every Gateway
+ replica (``<<GATEWAY_NAME>>-<<NAMESPACE>>``). Using that alone as the wire
+ ``origin`` makes every pod treat every other pod's PUBLISH as a local echo
+ and drop it — live SSE on a non-publisher replica stays empty even when
+ Redis fanout is healthy.
+ """
+ for key in ("POD_IP", "HOSTNAME"):
+ raw = str(os.environ.get(key) or "").strip()
+ if raw:
+ return raw
+ return uuid.uuid4().hex[:12]
+
+
+def _gateway_origin_id() -> str:
+ base = ""
+ try:
+ from jiuwenswarm.extensions.redis.redis_runtime import get_gateway_instance_id
+
+ iid = get_gateway_instance_id()
+ if iid:
+ base = str(iid).strip()
+ except Exception: # noqa: BLE001
+ base = ""
+ suffix = _process_unique_suffix()
+ if base:
+ return f"{base}:{suffix}"
+ return f"local-{suffix}"
+
+
+_warned_no_redis = False
+
+
+def _redis_client() -> Any | None:
+ """Best-effort Redis for cross-pod live; warn once when unavailable."""
+ global _warned_no_redis
+ client: Any | None = None
+ try:
+ from jiuwenswarm.extensions.redis.redis_runtime import (
+ get_declared_deployment_mode,
+ get_gateway_redis_client_if_open,
+ )
+
+ client = get_gateway_redis_client_if_open()
+ if client is None and not _warned_no_redis:
+ _warned_no_redis = True
+ mode = ""
+ try:
+ mode = str(get_declared_deployment_mode() or "")
+ except Exception: # noqa: BLE001
+ mode = "?"
+ logger.warning(
+ "[CronLiveBus] Gateway Redis unavailable; cron live stays process-local "
+ "(multi-replica subscribers will miss frames). "
+ "deployment_mode=%s — need distributed|active-standby with "
+ "[GatewayRedis] connected",
+ mode,
+ )
+ except Exception: # noqa: BLE001
+ if not _warned_no_redis:
+ _warned_no_redis = True
+ logger.warning(
+ "[CronLiveBus] Gateway Redis lookup failed; cron live stays process-local",
+ exc_info=True,
+ )
+ return None
+ return client
+
+
+def _channel_rel(session_id: str) -> str:
+ from jiuwenswarm.extensions.redis.redis_keys import cron_live_channel_rel
+
+ return cron_live_channel_rel(session_id)
+
+
+def _replay_key_rel(session_id: str) -> str:
+ from jiuwenswarm.extensions.redis.redis_keys import cron_live_replay_key_rel
+
+ return cron_live_replay_key_rel(session_id)
+
+
+def _encode_wire(*, origin: str, frame: dict[str, Any]) -> str:
+ return json.dumps({"o": origin, "f": frame}, ensure_ascii=False, separators=(",", ":"))
+
+
+def _decode_wire(raw: str) -> tuple[str, dict[str, Any]] | None:
+ try:
+ parsed = json.loads(raw)
+ except (TypeError, ValueError):
+ return None
+ if not isinstance(parsed, dict):
+ return None
+ frame = parsed.get("f")
+ if not isinstance(frame, dict):
+ return None
+ origin = str(parsed.get("o") or "")
+ return origin, frame
+
+
+def _frame_fingerprint(frame: dict[str, Any]) -> str:
+ """Stable dedupe key for live fanout / Redis echo.
+
+ Cron push attaches a large ``cron`` blob to every payload. Dumping the whole
+ payload and truncating to 240 chars often cuts off ``is_processing`` and
+ other discriminators, so ``processing_status=true`` and ``=false`` collide
+ and the terminal false is dropped — UI stays「处理中」after a fast auto-approve run.
+
+ ``live_seq`` must be part of the key: char-level LLM deltas often repeat the
+ same token (「的」「,」「\\n」). Fingerprinting only ``content`` then drops the
+ second copy → browser sees ``live_seq`` gaps and garbled CJK (e.g. 令命).
+ """
+ event = str(frame.get("event") or "")
+ payload = frame.get("payload") if isinstance(frame.get("payload"), dict) else {}
+ rid = str(payload.get("request_id") or "")
+ proc = payload.get("is_processing")
+ proc_part = "" if proc is None else f"|p={proc}"
+ seq = payload.get("live_seq")
+ seq_part = "" if seq is None else f"|s={seq}"
+ content = payload.get("content")
+ if isinstance(content, str) and content:
+ body = content[:240]
+ else:
+ compact: dict[str, Any] = {}
+ for key in (
+ "event_type",
+ "is_processing",
+ "current_task",
+ "tool_call_id",
+ "name",
+ "status",
+ "request_id",
+ ):
+ if key in payload:
+ compact[key] = payload.get(key)
+ try:
+ body = json.dumps(
+ compact or {"_": str(payload)[:120]},
+ ensure_ascii=False,
+ sort_keys=True,
+ default=str,
+ )[:240]
+ except Exception: # noqa: BLE001
+ body = str(payload)[:240]
+ return f"{event}|{rid}{proc_part}{seq_part}|{body}"
+
+
+def _queue_put(queue: asyncio.Queue[dict[str, Any]], frame: dict[str, Any]) -> bool:
+ """Enqueue ``frame``; on full drop the oldest slot so the newest is kept."""
+ try:
+ queue.put_nowait(frame)
+ return True
+ except asyncio.QueueFull:
+ try:
+ queue.get_nowait()
+ except asyncio.QueueEmpty:
+ return False
+ try:
+ queue.put_nowait(frame)
+ return True
+ except asyncio.QueueFull:
+ return False
+
+
+class CronLiveBus:
+ """Session-keyed queues with local + optional Redis replay/fanout."""
+
+ def __init__(
+ self,
+ *,
+ replay_size: int = 1024,
+ replay_ttl_seconds: float = 120.0,
+ queue_size: int = 4096,
+ ) -> None:
+ self._subscribers: dict[str, set[asyncio.Queue[dict[str, Any]]]] = {}
+ self._replay: dict[str, deque[dict[str, Any]]] = {}
+ self._replay_deadline: dict[str, float] = {}
+ self._replay_size = max(1, int(replay_size))
+ self._replay_ttl_seconds = max(0.01, float(replay_ttl_seconds))
+ self._queue_size = max(1, int(queue_size))
+ self._origin = _gateway_origin_id()
+ self._bridge_tasks: dict[str, asyncio.Task[None]] = {}
+ self._seen: dict[str, deque[str]] = {}
+ # Track fingerprints for a full replay window (plus headroom for in-flight).
+ self._seen_size = max(256, self._replay_size * 2)
+
+ def publish(self, session_id: str, frame: dict[str, Any]) -> None:
+ sid = str(session_id or "").strip()
+ if not sid or not isinstance(frame, dict):
+ return
+ self._prune_expired_replay()
+ buf = self._replay.setdefault(sid, deque(maxlen=self._replay_size))
+ buf.append(frame)
+ if self._subscribers.get(sid):
+ self._replay_deadline.pop(sid, None)
+ # Mark seen so the Redis echo on this pod is dropped; do not mark when
+ # nobody is subscribed yet or late local replay would be skipped.
+ self._fanout_local(sid, frame, mark_seen=True)
+ else:
+ # Nobody watching yet (typical run-now race): TTL the buffer.
+ self._replay_deadline[sid] = time.monotonic() + self._replay_ttl_seconds
+ self._schedule(self._redis_publish(sid, frame))
+
+ def subscribe(
+ self,
+ session_id: str,
+ *,
+ replay: bool = True,
+ ) -> asyncio.Queue[dict[str, Any]]:
+ """Subscribe to live frames for ``session_id``.
+
+ ``replay=False`` skips the buffered backlog (local + Redis). Use after
+ history restore so a page refresh cannot rebuild the previous run's
+ thinking / permission card on top of the finished timeline.
+ """
+ sid = str(session_id or "").strip()
+ queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=self._queue_size)
+ if not sid:
+ return queue
+ self._prune_expired_replay()
+ if replay:
+ # Same-pod late join: fill immediately from the in-process buffer.
+ for frame in list(self._replay.get(sid, ())):
+ self._enqueue(queue, frame, sid=sid, mark_seen=True)
+ # Cross-pod late join: Redis list may hold frames this process never saw.
+ # Dedup fingerprints drop overlap with the local buffer above.
+ if _redis_client() is not None:
+ self._schedule(self._redis_replay_into(sid, queue))
+ self._subscribers.setdefault(sid, set()).add(queue)
+ self._replay_deadline.pop(sid, None)
+ self._schedule(self._ensure_redis_bridge(sid))
+ return queue
+
+ def unsubscribe(self, session_id: str, queue: asyncio.Queue[dict[str, Any]]) -> None:
+ sid = str(session_id or "").strip()
+ bucket = self._subscribers.get(sid)
+ if bucket is None:
+ return
+ bucket.discard(queue)
+ if not bucket:
+ self._subscribers.pop(sid, None)
+ # Keep replay briefly so a reconnect / slow run-now still catches up.
+ if sid in self._replay:
+ self._replay_deadline[sid] = time.monotonic() + self._replay_ttl_seconds
+ self._stop_redis_bridge(sid)
+
+ def clear_session(self, session_id: str) -> None:
+ """Drop local + Redis replay after a run settles.
+
+ Follow-up chat on ``cron_*`` does not use this bus. Leaving the finished
+ run's deltas/finals buffered makes the next page refresh replay them on
+ top of history and overwrite the latest assistant turn with the first
+ run's answer.
+ """
+ sid = str(session_id or "").strip()
+ if not sid:
+ return
+ self._replay.pop(sid, None)
+ self._replay_deadline.pop(sid, None)
+ self._seen.pop(sid, None)
+ self._schedule(self._redis_clear(sid))
+
+ def _fanout_local(self, sid: str, frame: dict[str, Any], *, mark_seen: bool) -> None:
+ # Dedup once per frame, then deliver to every local subscriber.
+ if mark_seen and self._frame_already_seen(sid, frame):
+ return
+ delivered = False
+ for queue in list(self._subscribers.get(sid, ())):
+ if _queue_put(queue, frame):
+ delivered = True
+ # Only remember after a successful put — otherwise QueueFull + mark_seen
+ # would permanently erase the frame (Redis same-origin echo is skipped too).
+ if mark_seen and delivered:
+ self._remember_frame(sid, frame)
+ elif mark_seen and not delivered and self._subscribers.get(sid):
+ logger.warning(
+ "[CronLiveBus] drop frame: all subscriber queues full session_id=%s event=%s",
+ sid,
+ frame.get("event"),
+ )
+
+ def _enqueue(
+ self,
+ queue: asyncio.Queue[dict[str, Any]],
+ frame: dict[str, Any],
+ *,
+ sid: str,
+ mark_seen: bool,
+ ) -> None:
+ if mark_seen and self._frame_already_seen(sid, frame):
+ return
+ if not _queue_put(queue, frame):
+ return
+ if mark_seen:
+ self._remember_frame(sid, frame)
+
+ def _frame_already_seen(self, sid: str, frame: dict[str, Any]) -> bool:
+ fp = _frame_fingerprint(frame)
+ bucket = self._seen.get(sid)
+ return bool(bucket is not None and fp in bucket)
+
+ def _remember_frame(self, sid: str, frame: dict[str, Any]) -> None:
+ """Record fingerprint after a frame was successfully queued."""
+ fp = _frame_fingerprint(frame)
+ bucket = self._seen.setdefault(sid, deque(maxlen=self._seen_size))
+ if fp not in bucket:
+ bucket.append(fp)
+
+ @staticmethod
+ def _schedule(coro: Any) -> None:
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ # Caller already created the coroutine; close it when no loop (sync tests).
+ close = getattr(coro, "close", None)
+ if callable(close):
+ close()
+ return
+ loop.create_task(coro)
+
+ async def _redis_publish(self, sid: str, frame: dict[str, Any]) -> None:
+ client = _redis_client()
+ if client is None:
+ return
+ wire = _encode_wire(origin=self._origin, frame=frame)
+ try:
+ replay_key = _replay_key_rel(sid)
+ await client.rpush(replay_key, wire)
+ await client.ltrim(replay_key, -self._replay_size, -1)
+ await client.expire(replay_key, max(1, int(self._replay_ttl_seconds)))
+ await client.publish(_channel_rel(sid), wire)
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[CronLiveBus] redis publish failed session_id=%s",
+ sid,
+ exc_info=True,
+ )
+
+ async def _redis_clear(self, sid: str) -> None:
+ client = _redis_client()
+ if client is None:
+ return
+ try:
+ await client.delete(_replay_key_rel(sid))
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[CronLiveBus] redis clear failed session_id=%s",
+ sid,
+ exc_info=True,
+ )
+
+ async def _redis_replay_into(self, sid: str, queue: asyncio.Queue[dict[str, Any]]) -> None:
+ client = _redis_client()
+ if client is None:
+ return
+ try:
+ items = await client.lrange(_replay_key_rel(sid), 0, -1)
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[CronLiveBus] redis replay failed session_id=%s",
+ sid,
+ exc_info=True,
+ )
+ # Fall back to whatever this pod buffered locally.
+ for frame in list(self._replay.get(sid, ())):
+ self._enqueue(queue, frame, sid=sid, mark_seen=True)
+ return
+ for raw in items:
+ decoded = _decode_wire(raw)
+ if decoded is None:
+ continue
+ _origin, frame = decoded
+ self._enqueue(queue, frame, sid=sid, mark_seen=True)
+
+ async def _ensure_redis_bridge(self, sid: str) -> None:
+ existing = self._bridge_tasks.get(sid)
+ if existing is not None and not existing.done():
+ return
+ if _redis_client() is None:
+ logger.warning(
+ "[CronLiveBus] redis bridge skip session_id=%s; Gateway Redis unavailable "
+ "(live stays process-local)",
+ sid,
+ )
+ return
+
+ async def _listen() -> None:
+ backoff = 0.5
+ logger.info(
+ "[CronLiveBus] redis bridge started session_id=%s origin=%s",
+ sid,
+ self._origin,
+ )
+ try:
+ while self._subscribers.get(sid):
+ client = _redis_client()
+ if client is None:
+ await asyncio.sleep(1.0)
+ continue
+ try:
+ async for raw in client.subscribe(_channel_rel(sid)):
+ if not self._subscribers.get(sid):
+ return
+ decoded = _decode_wire(raw)
+ if decoded is None:
+ logger.debug(
+ "[CronLiveBus] skip undecodable redis frame session_id=%s head=%r",
+ sid,
+ (raw or "")[:120],
+ )
+ continue
+ origin, frame = decoded
+ # Same process already delivered on publish; skip echo.
+ if origin and origin == self._origin:
+ continue
+ self._fanout_local(sid, frame, mark_seen=True)
+ # Generator ended cleanly; retry while viewers remain.
+ backoff = 0.5
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[CronLiveBus] redis bridge error session_id=%s; retry in %.1fs",
+ sid,
+ backoff,
+ exc_info=True,
+ )
+ await asyncio.sleep(backoff)
+ backoff = min(backoff * 2.0, 8.0)
+ finally:
+ current = self._bridge_tasks.get(sid)
+ if current is asyncio.current_task():
+ self._bridge_tasks.pop(sid, None)
+ logger.info(
+ "[CronLiveBus] redis bridge stopped session_id=%s",
+ sid,
+ )
+
+ self._bridge_tasks[sid] = asyncio.create_task(
+ _listen(),
+ name=f"cron-live-bridge-{sid}",
+ )
+
+ def _stop_redis_bridge(self, sid: str) -> None:
+ task = self._bridge_tasks.pop(sid, None)
+ if task is not None and not task.done():
+ task.cancel()
+
+ def _prune_expired_replay(self) -> None:
+ now = time.monotonic()
+ for sid, deadline in list(self._replay_deadline.items()):
+ if sid in self._subscribers:
+ self._replay_deadline.pop(sid, None)
+ continue
+ if now >= deadline:
+ self._replay.pop(sid, None)
+ self._replay_deadline.pop(sid, None)
+ self._seen.pop(sid, None)
+
+
+cron_live_bus = CronLiveBus()
diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.py
index a764dfa10d..b0974c5362 100644
--- a/jiuwenswarm/gateway/cron/scheduler.py
+++ b/jiuwenswarm/gateway/cron/scheduler.py
@@ -46,6 +46,27 @@ logger = logging.getLogger(__name__)
# run-trace:定位 session.create 与 chat.send 之间断点(phase 见 _log_cron_run_phase)
_CRON_RUN_TRACE_PREFIX = "[Cron][run-trace]"
+# 调度器自己消费 Agent 流时,这些帧要进正在看的 cron_* 窗口。
+# chat.final:live 阶段也要先推一帧,让前端在 processing=false 拆线前用终稿
+# 覆盖字级 delta 拼接;_on_push 仍会再推一次(前端去重/同文覆盖)。
+_CRON_LIVE_FORWARD_EVENTS = frozenset({
+ "chat.reasoning",
+ "chat.delta",
+ "chat.tool_call",
+ "chat.tool_update",
+ "chat.tool_result",
+ "chat.processing_status",
+ "chat.ask_user_question",
+ # Token/cost 行依赖此帧;不转发则 live 气泡无 usage,刷新 history 才出现。
+ "chat.usage_summary",
+})
+_CRON_LIVE_MIRROR_EVENTS = _CRON_LIVE_FORWARD_EVENTS | frozenset({"chat.final"})
+_CRON_QUIET_PUSH_EVENTS = frozenset({
+ EventType.CHAT_DELTA,
+ EventType.CHAT_REASONING,
+ EventType.CHAT_PROCESSING_STATUS,
+})
+
def _log_cron_run_phase(
phase: str,
@@ -170,8 +191,15 @@ def _touch_remote_cron_session_catalog(session_id: str, *, now_ts: float) -> Non
async def _persist_remote_cron_history(job: CronJob, state: CronRunState) -> None:
- """Save the execution body independently of Pod-local files and push delivery."""
- if not is_remote_storage() or not state.exec_session_id or not state.result_text:
+ """Save the execution body independently of Pod-local files and push delivery.
+
+ ``awaiting_approval`` has no assistant body yet, but the user/task prompt must
+ still land in PG so refresh can restore the cron_* window content.
+ """
+ if not is_remote_storage() or not state.exec_session_id:
+ return
+ awaiting = state.status == "awaiting_approval"
+ if not awaiting and not state.result_text:
return
try:
from jiuwenswarm.channels.web.history_store.api import get_default_store
@@ -192,6 +220,8 @@ async def _persist_remote_cron_history(job: CronJob, state: CronRunState) -> Non
cron_id=job.id,
work_mode=job.work_mode or DEFAULT_WEB_WORK_MODE,
)
+ if awaiting:
+ return
await store.record_assistant(
request_id=request_id,
session_id=state.exec_session_id,
@@ -398,6 +428,340 @@ class CronSchedulerService:
self._claimed_run_ids: set[str] = set()
# active-standby 下由 LeaderElection 控制:STANDBY 期间 loop 自旋但不消费事件
self._active: bool = True
+ # job_id -> (deadline_ts, exec_session_id)。审批卡未回复时跳过下一次触发。
+ # 多副本时另写 Redis(见 _hold_job_for_permission);读失败偏安全(当仍 hold)。
+ self._permission_hold: dict[str, tuple[float, str]] = {}
+
+ @staticmethod
+ def _redis_hold_required() -> bool:
+ """distributed / active-standby 下 hold 必须以 Redis 为准;不可用则 fail-closed。"""
+ try:
+ from jiuwenswarm.extensions.redis.redis_runtime import get_declared_deployment_mode
+
+ mode = str(get_declared_deployment_mode() or "").strip().lower()
+ return mode in {"distributed", "active-standby"}
+ except Exception: # noqa: BLE001
+ return False
+
+ def _get_active_permission_hold(self, job_id: str) -> tuple[float, str] | None:
+ item = self._permission_hold.get(job_id)
+ if item is None:
+ return None
+ until, session_id = item
+ if self._now_fn() >= until:
+ self._permission_hold.pop(job_id, None)
+ return None
+ return until, str(session_id or "").strip()
+
+ def _permission_hold_active(self, job_id: str) -> bool:
+ return self._get_active_permission_hold(job_id) is not None
+
+ def _permission_hold_session(self, job_id: str) -> str:
+ held = self._get_active_permission_hold(job_id)
+ return held[1] if held is not None else ""
+
+ async def _permission_hold_session_async(self, job_id: str) -> tuple[str, str]:
+ """返回 ``(session_id, source)``。
+
+ ``source`` ∈ ``{'', 'local', 'redis', '__hold_unknown__'}``。
+ Local hold first; then Redis. Redis required+unusable → sentinel
+ ``__hold_unknown__``(sid 与 source 同为该哨兵)。
+ """
+ local = self._permission_hold_session(job_id)
+ if local:
+ return local, "local"
+ if not self._redis_hold_required():
+ return "", ""
+ try:
+ from jiuwenswarm.extensions.redis.redis_keys import cron_permission_hold_rel
+ from jiuwenswarm.extensions.redis.redis_runtime import (
+ get_gateway_redis_client_if_open,
+ )
+
+ client = get_gateway_redis_client_if_open()
+ if client is None:
+ logger.warning(
+ "[Cron] permission hold redis unavailable (fail-closed) job=%s",
+ job_id,
+ )
+ return "__hold_unknown__", "__hold_unknown__"
+ raw = await client.get(cron_permission_hold_rel(job_id))
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[Cron] permission hold redis read failed (fail-closed) job=%s",
+ job_id,
+ exc_info=True,
+ )
+ return "__hold_unknown__", "__hold_unknown__"
+ if raw is None:
+ return "", ""
+ if isinstance(raw, (bytes, bytearray)):
+ text = bytes(raw).decode("utf-8", errors="replace").strip()
+ else:
+ text = str(raw or "").strip()
+ if not text:
+ return "", ""
+ return text, "redis"
+
+ async def _permission_hold_blocks_new_run(self, job_id: str) -> bool:
+ """Whether wake / new run_now must not start a fresh execution."""
+ sid, source = await self._permission_hold_session_async(job_id)
+ if not sid:
+ return False
+ if sid == "__hold_unknown__":
+ return True
+ # 本机孤儿判定只适用于 local hold。Redis hold 可能是别的副本写入的,
+ # 本机 _runs 看不到 awaiting_approval 时不得误清全局 hold(靠 TTL 回收)。
+ if source == "local" and self._is_orphan_permission_hold(job_id, sid):
+ self._clear_permission_hold_for_job(
+ job_id, session_id=sid, reason="wake_orphan_hold",
+ )
+ return False
+ return True
+
+ def _find_awaiting_approval_run_id(self, job_id: str, session_id: str = "") -> str:
+ sid = str(session_id or "").strip()
+ for run_id, state in self._runs.items():
+ if state.job_id != job_id or state.status != "awaiting_approval":
+ continue
+ if sid and str(state.exec_session_id or "").strip() != sid:
+ continue
+ return run_id
+ return f"{job_id}:awaiting_approval"
+
+ def _is_orphan_permission_hold(self, job_id: str, held_session_id: str) -> bool:
+ """Hold 仍在,但已无真实 awaiting_approval / running 执行可续跑。
+
+ 典型:续跑 UI 已完成,但 Redis/本地 hold 未清;``run_now`` 只能复用旧
+ 会话(合成 ``job_id:awaiting_approval``),表现为卡住。真 HITL 时本机
+ 必有 ``awaiting_approval`` run,不得当孤儿清掉。
+ """
+ sid = str(held_session_id or "").strip()
+ jid = str(job_id or "").strip()
+ if not jid or not sid:
+ return False
+ for state in self._runs.values():
+ if str(getattr(state, "job_id", "") or "").strip() != jid:
+ continue
+ status = str(getattr(state, "status", "") or "")
+ exec_sid = str(getattr(state, "exec_session_id", "") or "").strip()
+ if status == "awaiting_approval" and (not sid or exec_sid == sid):
+ return False
+ if exec_sid == sid and status == "running":
+ return False
+ return True
+
+ def _clear_permission_hold_for_job(
+ self, job_id: str, *, session_id: str = "", reason: str = "",
+ ) -> None:
+ jid = str(job_id or "").strip()
+ if not jid:
+ return
+ self._permission_hold.pop(jid, None)
+ self._schedule_hold_redis_clear(jid, session_id=session_id)
+ sid = str(session_id or "").strip()
+ if sid:
+ try:
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus
+
+ cron_live_bus.clear_session(sid)
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[Cron] clear live after hold clear failed session=%s",
+ sid,
+ exc_info=True,
+ )
+ if reason:
+ logger.info(
+ "[Cron] cleared permission hold job=%s session=%s reason=%s",
+ jid, sid or "-", reason,
+ )
+
+ def _hold_job_for_permission(self, job: CronJob, exec_session_id: str) -> None:
+ timeout = float(resolve_cron_job_timeout_seconds(job))
+ sid = str(exec_session_id or "")
+ self._permission_hold[job.id] = (self._now_fn() + timeout, sid)
+ self._schedule_hold_redis_write(job.id, sid, int(max(1, timeout)))
+
+ def _schedule_hold_redis_write(self, job_id: str, session_id: str, ttl: int) -> None:
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ return
+ loop.create_task(self._redis_write_permission_hold(job_id, session_id, ttl))
+
+ async def _redis_write_permission_hold(
+ self, job_id: str, session_id: str, ttl: int,
+ ) -> None:
+ if not self._redis_hold_required():
+ return
+ try:
+ from jiuwenswarm.extensions.redis.redis_keys import (
+ cron_permission_hold_by_session_rel,
+ cron_permission_hold_rel,
+ )
+ from jiuwenswarm.extensions.redis.redis_runtime import (
+ get_gateway_redis_client_if_open,
+ )
+
+ client = get_gateway_redis_client_if_open()
+ if client is None:
+ logger.warning(
+ "[Cron] permission hold redis write skipped (no client) job=%s",
+ job_id,
+ )
+ return
+ await client.set(
+ cron_permission_hold_rel(job_id),
+ session_id,
+ ttl_seconds=ttl,
+ )
+ if session_id:
+ await client.set(
+ cron_permission_hold_by_session_rel(session_id),
+ job_id,
+ ttl_seconds=ttl,
+ )
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[Cron] permission hold redis write failed job=%s",
+ job_id,
+ exc_info=True,
+ )
+
+ def _schedule_hold_redis_clear(
+ self, job_id: str, *, session_id: str = "",
+ ) -> None:
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ return
+ loop.create_task(
+ self._redis_clear_permission_hold(job_id, session_id=session_id)
+ )
+
+ async def _redis_clear_permission_hold(
+ self, job_id: str, *, session_id: str = "",
+ ) -> None:
+ if not self._redis_hold_required():
+ return
+ try:
+ from jiuwenswarm.extensions.redis.redis_keys import (
+ cron_permission_hold_by_session_rel,
+ cron_permission_hold_rel,
+ )
+ from jiuwenswarm.extensions.redis.redis_runtime import (
+ get_gateway_redis_client_if_open,
+ )
+
+ client = get_gateway_redis_client_if_open()
+ if client is None:
+ logger.warning(
+ "[Cron] permission hold redis clear skipped (no client) job=%s",
+ job_id,
+ )
+ return
+ await client.delete(cron_permission_hold_rel(job_id))
+ sid = str(session_id or "").strip()
+ if sid:
+ await client.delete(cron_permission_hold_by_session_rel(sid))
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[Cron] permission hold redis clear failed job=%s",
+ job_id,
+ exc_info=True,
+ )
+
+ def _schedule_hold_redis_clear_by_session(self, session_id: str) -> None:
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ return
+ loop.create_task(self._redis_clear_permission_hold_by_session(session_id))
+
+ async def _redis_clear_permission_hold_by_session(self, session_id: str) -> None:
+ if not self._redis_hold_required():
+ return
+ sid = str(session_id or "").strip()
+ if not sid:
+ return
+ try:
+ from jiuwenswarm.extensions.redis.redis_keys import (
+ cron_permission_hold_by_session_rel,
+ cron_permission_hold_rel,
+ )
+ from jiuwenswarm.extensions.redis.redis_runtime import (
+ get_gateway_redis_client_if_open,
+ )
+
+ client = get_gateway_redis_client_if_open()
+ if client is None:
+ return
+ raw = await client.get(cron_permission_hold_by_session_rel(sid))
+ if raw is None:
+ return
+ if isinstance(raw, (bytes, bytearray)):
+ job_id = bytes(raw).decode("utf-8", errors="replace").strip()
+ else:
+ job_id = str(raw or "").strip()
+ if job_id:
+ await client.delete(cron_permission_hold_rel(job_id))
+ await client.delete(cron_permission_hold_by_session_rel(sid))
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[Cron] permission hold redis clear-by-session failed session=%s",
+ sid,
+ exc_info=True,
+ )
+
+ def release_permission_hold_for_session(self, session_id: str) -> None:
+ """审批续跑成功后调用:放开调度,并清 live replay。"""
+ sid = str(session_id or "").strip()
+ if not sid:
+ return
+ released_jobs: list[str] = []
+ for job_id, (_until, held_sid) in list(self._permission_hold.items()):
+ if held_sid == sid:
+ self._permission_hold.pop(job_id, None)
+ released_jobs.append(job_id)
+ for job_id in released_jobs:
+ self._schedule_hold_redis_clear(job_id, session_id=sid)
+ if not released_jobs:
+ # Local miss:按 session 匹配任意 run 取 job_id,或走 session 反查键。
+ for _run_id, state in list(self._runs.items()):
+ if str(getattr(state, "exec_session_id", "") or "").strip() != sid:
+ continue
+ self._schedule_hold_redis_clear(state.job_id, session_id=sid)
+ released_jobs.append(state.job_id)
+ if not released_jobs:
+ self._schedule_hold_redis_clear_by_session(sid)
+ if not released_jobs and not self._redis_hold_required():
+ return
+ # 审批续跑改走 chat.send SSE;调度器已停读。清掉含 ask_user 的 live
+ # replay,避免 /live 重订时把已答过的权限卡再弹出来。
+ try:
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus
+
+ cron_live_bus.clear_session(sid)
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[Cron] clear live replay after permission release failed session=%s",
+ sid,
+ exc_info=True,
+ )
+
+ def mark_permission_resume_succeeded(self, session_id: str) -> None:
+ """Resume ``chat.final`` arrived: leave awaiting_approval and release hold."""
+ sid = str(session_id or "").strip()
+ if not sid:
+ return
+ for state in list(self._runs.values()):
+ if str(getattr(state, "exec_session_id", "") or "").strip() != sid:
+ continue
+ if state.status == "awaiting_approval":
+ state.status = "succeeded"
+ state.finished_at = self._now_fn()
+ self.release_permission_hold_for_session(sid)
def _cancel_run_task(self, run_id: str, task: asyncio.Task, *, reason: str) -> None:
"""取消 in-flight run 并记录来源,便于关联 session.create 后未 chat.send。"""
@@ -610,6 +974,8 @@ class CronSchedulerService:
主动 cancel,AgentServer 端的 task 会继续跑到完成——飞书等渠道
会先收到"超时"文案,但任务实际仍在后台正常完成,结果到达 gateway
时已无人接收而被丢弃(用户反馈"超时但结果正常完成"的矛盾现象)。
+ - ``reason="error"``: agent 流处理抛出非超时异常时,同样停掉
+ AgentServer 上还在跑的那一轮;日志原因与超时分开。
session_id 必须用真实执行会话 ``state.exec_session_id``(格式
``cron_{ts}_{job.id}``)。AgentServer 的 ``_stop_session_interrupt_work``
@@ -805,7 +1171,7 @@ class CronSchedulerService:
existing = self._runs.get(run_id)
already_active = (
existing is not None
- and existing.status in ("running", "succeeded", "failed")
+ and existing.status in ("running", "succeeded", "failed", "awaiting_approval")
) or (
run_id in self._run_tasks
and not self._run_tasks[run_id].done()
@@ -846,8 +1212,43 @@ class CronSchedulerService:
async def trigger_run_now_info(
self, job_id: str, *, preallocate: bool = False
- ) -> dict[str, str]:
+ ) -> dict[str, Any]:
job_id = str(job_id or "").strip()
+ # 上一轮工具审批未完成:立即执行复用旧 cron_*,勿再开空会话(否则前端转圈、Agent 不跑)。
+ # hold 按 job_id 索引(本地 + Redis);Redis 不可用时 fail-closed 拒绝新开跑。
+ held_sid, hold_source = await self._permission_hold_session_async(job_id)
+ if held_sid == "__hold_unknown__":
+ raise RuntimeError(
+ "cron permission hold state unavailable; refusing new run (fail-closed)"
+ )
+ if held_sid:
+ # 仅本机 hold 可做孤儿清理;Redis hold 视为仍有效(多副本 fail-safe)。
+ if hold_source == "local" and self._is_orphan_permission_hold(
+ job_id, held_sid,
+ ):
+ # UI 已跑完但本机 hold 残留 → 清掉后走新建。
+ # 真待审批时本机必有 awaiting_approval run,不会进此分支。
+ self._clear_permission_hold_for_job(
+ job_id,
+ session_id=held_sid,
+ reason="run_now_orphan_hold",
+ )
+ else:
+ held_run_id = self._find_awaiting_approval_run_id(job_id, held_sid)
+ logger.info(
+ "[Cron] run_now reuses pending approval session job=%s "
+ "run_id=%s session_id=%s source=%s",
+ job_id,
+ held_run_id,
+ held_sid,
+ hold_source,
+ )
+ return {
+ "run_id": held_run_id,
+ "session_id": held_sid,
+ "awaiting_approval": True,
+ "reused_pending_session": True,
+ }
job = self._jobs.get(job_id) or await self._store.get_job(job_id)
if job is None:
raise KeyError("job not found")
@@ -1535,7 +1936,7 @@ class CronSchedulerService:
# 幂等保护:reload 可能对同一 run_id 重复排入 wake 事件。
# 如果该 run 已完成(succeeded/failed)或已有结果文本,不再重复执行 agent。
- if state.status in ("succeeded", "failed"):
+ if state.status in ("succeeded", "failed", "awaiting_approval"):
logger.info(
"[Cron] _on_wake skipped: already %s run_id=%s job=%s",
state.status, run_id, job.id,
@@ -1556,12 +1957,31 @@ class CronSchedulerService:
)
return
+ if await self._permission_hold_blocks_new_run(job.id):
+ # 定时触发:跳过,避免未审批又开一轮。立即执行应在 trigger_run_now_info 已复用旧会话;
+ # 若仍进到这里(竞态/旧事件),也只标 skipped,禁止假成功。
+ # Redis 不可用时同样 skip(fail-closed,避免双跑)。
+ state.status = "skipped"
+ state.finished_at = self._now_fn()
+ held_sid, hold_source = await self._permission_hold_session_async(job.id)
+ logger.info(
+ "[Cron] _on_wake skipped: permission card pending job=%s run_id=%s "
+ "manual=%s held_session=%s source=%s",
+ job.id,
+ run_id,
+ bool(state.manual_trigger),
+ held_sid,
+ hold_source,
+ )
+ return
+
_log_cron_run_phase("wake_start_run_agent", run_id=run_id, job_id=job.id)
async def _run_agent() -> None:
state.status = "running"
state.started_at = self._now_fn()
ok = False
+ awaiting_permission = False
mode = CRON_JOB_DEFAULT_MODE
channel_id = ""
exec_session_id = ""
@@ -1695,7 +2115,7 @@ class CronSchedulerService:
timeout_seconds=timeout_seconds,
)
else:
- envelope.is_stream = False
+ envelope.is_stream = True
timeout_seconds = resolve_cron_job_timeout_seconds(job)
_log_cron_run_phase(
"run_agent_before_chat_send",
@@ -1704,10 +2124,11 @@ class CronSchedulerService:
exec_session_id=exec_session_id,
timeout_seconds=timeout_seconds,
)
- text, ok = await self._run_unary_cron_job(
+ text, ok, awaiting_permission = await self._run_agent_stream_job(
envelope=envelope,
- timeout_seconds=timeout_seconds,
+ job=job,
state=state,
+ timeout_seconds=timeout_seconds,
)
_log_cron_run_phase(
"run_agent_after_chat_send",
@@ -1718,13 +2139,23 @@ class CronSchedulerService:
result_text_len=len(text or ""),
)
await self._mark_last_session_ready(job, exec_session_id)
- logger.info(
- "[Cron] run finished: job_id=%s exec_session_id=%s "
- "mode=%s ok=%s result_text_len=%d",
- job.id, exec_session_id, mode, ok, len(text or ""),
- )
- state.result_text = text
- state.status = "succeeded" if ok else "failed"
+ if awaiting_permission:
+ state.result_text = None
+ state.error = None
+ state.status = "awaiting_approval"
+ self._hold_job_for_permission(job, exec_session_id)
+ logger.info(
+ "[Cron] run paused for permission: job_id=%s exec_session_id=%s",
+ job.id, exec_session_id,
+ )
+ else:
+ logger.info(
+ "[Cron] run finished: job_id=%s exec_session_id=%s "
+ "mode=%s ok=%s result_text_len=%d",
+ job.id, exec_session_id, mode, ok, len(text or ""),
+ )
+ state.result_text = text
+ state.status = "succeeded" if ok else "failed"
except asyncio.CancelledError:
state.status = "failed"
state.error = "cancelled"
@@ -1772,7 +2203,13 @@ class CronSchedulerService:
# Ensure failed runs also produce result_text so push logic can deliver it.
# But for cancelled ghost tasks, skip — no result should be pushed for
# a job the user has removed.
- if not state.result_text and state.error and not is_cancelled_ghost:
+ missing_result_text = not state.result_text
+ should_fill_error_result = (
+ not awaiting_permission
+ and missing_result_text
+ and bool(state.error)
+ )
+ if should_fill_error_result and not is_cancelled_ghost:
state.result_text = f"[cron] 任务执行失败: {state.error}"
if not is_cancelled_ghost:
await _persist_remote_cron_history(job, state)
@@ -1903,6 +2340,235 @@ class CronSchedulerService:
exc,
)
+ async def _run_agent_stream_job(
+ self,
+ *,
+ envelope: Any,
+ job: CronJob,
+ state: CronRunState,
+ timeout_seconds: float,
+ ) -> tuple[str, bool, bool]:
+ """Agent 模式自己消费流:思考、正文和审批卡转到正在看的 ``cron_*``。
+
+ 返回 ``(text, ok, awaiting_approval)``。暂停时断开的是调度器这条读取,
+ 不取消 Agent 上已经暂停的那一轮。``chat.final`` 在 live 上先于
+ ``processing=false`` 发出,便于前端覆盖 delta 拼接;跑完后的 ``_on_push``
+ 仍会再推终稿。
+ """
+ rid = str(getattr(envelope, "request_id", "") or "")
+ sid = str(getattr(envelope, "session_id", "") or "")
+ _log_cron_run_phase(
+ "chat_send_stream_begin",
+ run_id=state.run_id,
+ job_id=state.job_id,
+ exec_session_id=sid,
+ request_id=rid,
+ timeout_seconds=timeout_seconds,
+ )
+ stream_gen = self._agent_client.send_request_stream(envelope)
+ final_text = ""
+ deltas: list[str] = []
+ saw_final = False
+ forwarded_final = False
+ saw_ask = False
+ awaiting = False
+ ok = True
+
+ live_seq = 0
+
+ async def _forward_live(payload: dict[str, Any], event_name: str) -> None:
+ nonlocal live_seq
+ try:
+ event_type = EventType(event_name)
+ except ValueError:
+ return
+ live_seq += 1
+ # Monotonic seq so the browser can drop stale frames when two /live
+ # SSE readers briefly overlap (otherwise CJK deltas can swap, e.g. 令命).
+ enriched = dict(payload)
+ enriched["live_seq"] = live_seq
+ message_id = f"cron-live-{state.run_id}-{live_seq}"
+ if event_name == "chat.ask_user_question":
+ ask_request_id = str(payload.get("request_id") or rid or "ask")
+ message_id = f"cron-ask-{state.run_id}-{ask_request_id}"
+ try:
+ await self._push_to_targets(
+ job,
+ state,
+ text="",
+ is_placeholder=False,
+ event_type=event_type,
+ payload=enriched,
+ message_id=message_id,
+ )
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[Cron] live frame forward failed job=%s run_id=%s event=%s",
+ job.id,
+ state.run_id,
+ event_name,
+ exc_info=True,
+ )
+
+ async def _consume() -> None:
+ nonlocal final_text, saw_final, forwarded_final, saw_ask, awaiting, ok
+ # 首帧标 processing,打开窗口时立刻是「进行中」,而不是空时间线「已完成」。
+ await _forward_live(
+ {
+ "event_type": "chat.processing_status",
+ "is_processing": True,
+ "current_task": "thinking",
+ "session_id": sid,
+ "request_id": rid,
+ },
+ "chat.processing_status",
+ )
+ try:
+ async for chunk in stream_gen:
+ payload = chunk.payload if isinstance(chunk.payload, dict) else None
+ event_type = str((payload or {}).get("event_type") or "").strip()
+ if event_type in _CRON_LIVE_FORWARD_EVENTS and isinstance(payload, dict):
+ if event_type == "chat.ask_user_question":
+ saw_ask = True
+ # 等审批时不要转发 is_processing=false,否则前端会先显示「已完成」。
+ if (
+ event_type == "chat.processing_status"
+ and payload.get("is_processing") is False
+ ):
+ continue
+ await _forward_live(payload, event_type)
+ if event_type == "chat.delta":
+ piece = _extract_text_from_agent_payload(payload)
+ if piece:
+ deltas.append(piece)
+ elif event_type == "chat.invocation_paused" or (
+ isinstance(payload, dict) and payload.get("awaiting_user_input")
+ ):
+ awaiting = True
+ # 停读即可。关掉客户端连接不能取消 Agent 上这次暂停。
+ break
+ elif event_type == "chat.error":
+ ok = False
+ error_text = _extract_text_from_agent_payload(payload)
+ if error_text and not saw_final:
+ final_text = error_text
+ saw_final = True
+ elif event_type == "chat.final":
+ text = _extract_text_from_agent_payload(payload)
+ if text:
+ final_text = text
+ saw_final = True
+ # HITL 暂停前也可能有铺垫 final;照常进 live,前端有权限卡时不拆线。
+ if isinstance(payload, dict) and text:
+ await _forward_live(payload, event_type)
+ forwarded_final = True
+ # 真暂停靠 awaiting;saw_ask alone 不能挡 is_complete,
+ # 否则非 HITL 的 ask 帧会把流拖死,最后还被误判成 awaiting_approval。
+ if bool(getattr(chunk, "is_complete", False)) and not awaiting:
+ break
+ finally:
+ try:
+ await stream_gen.aclose()
+ except Exception:
+ pass
+
+ try:
+ await asyncio.wait_for(_consume(), timeout=timeout_seconds)
+ except asyncio.TimeoutError:
+ timeout_min = max(1, int(timeout_seconds // 60))
+ logger.warning(
+ "[Cron] agent stream timed out after %ss request_id=%s",
+ timeout_seconds,
+ rid,
+ )
+ try:
+ await stream_gen.aclose()
+ except Exception:
+ pass
+ await self._cancel_agent_session(state, reason="timeout")
+ try:
+ await _forward_live(
+ {
+ "event_type": "chat.processing_status",
+ "is_processing": False,
+ "session_id": sid,
+ "request_id": rid,
+ },
+ "chat.processing_status",
+ )
+ except Exception:
+ pass
+ return f"[cron] 任务执行超时(>{timeout_min}min)", False, False
+ except Exception:
+ logger.warning(
+ "[Cron] agent stream failed request_id=%s",
+ rid,
+ exc_info=True,
+ )
+ try:
+ await stream_gen.aclose()
+ except Exception:
+ pass
+ await self._cancel_agent_session(state, reason="error")
+ try:
+ await _forward_live(
+ {
+ "event_type": "chat.processing_status",
+ "is_processing": False,
+ "session_id": sid,
+ "request_id": rid,
+ },
+ "chat.processing_status",
+ )
+ except Exception:
+ pass
+ raise
+
+ # 只有真正收到 invocation_paused / awaiting_user_input 才算等审批。
+ # saw_ask alone(流已跑完、或非暂停类 ask)必须补 false,否则前端一直转圈。
+ if awaiting:
+ _log_cron_run_phase(
+ "chat_send_stream_paused",
+ run_id=state.run_id,
+ job_id=state.job_id,
+ exec_session_id=sid,
+ request_id=rid,
+ saw_ask=saw_ask,
+ )
+ # 等审批:保持 processing=true,不要补 false / 不要补收口 final。
+ return "", True, True
+
+ text = final_text if saw_final else "".join(deltas)
+ # 正常跑完:先推权威 final,再补 processing=false,避免前端拆 live 后错拼钉死。
+ if text and not forwarded_final:
+ await _forward_live(
+ {
+ "event_type": "chat.final",
+ "content": text,
+ "session_id": sid,
+ "request_id": rid,
+ },
+ "chat.final",
+ )
+ # 流里的 is_processing=false 被上面吞掉了(避免审批前误收口)。
+ await _forward_live(
+ {
+ "event_type": "chat.processing_status",
+ "is_processing": False,
+ "session_id": sid,
+ "request_id": rid,
+ },
+ "chat.processing_status",
+ )
+
+ if ok and not text:
+ logger.warning(
+ "[Cron] agent stream succeeded but result_text empty request_id=%s",
+ rid,
+ )
+ return "[cron] 任务执行完成但未返回结果内容", False, False
+ return text, ok, False
+
async def _run_unary_cron_job(
self,
*,
@@ -2122,6 +2788,12 @@ class CronSchedulerService:
if state.pushed_final:
return
+ if state.status in ("awaiting_approval", "skipped"):
+ logger.info(
+ "[Cron] _on_push skipped: %s job=%s run_id=%s",
+ state.status, job.id, run_id,
+ )
+ return
if state.result_text:
await self._push_to_targets(job, state, text=state.result_text, is_placeholder=False)
@@ -2162,35 +2834,55 @@ class CronSchedulerService:
state.pushed_final = True
logger.info("[Cron] push_update done job=%s run_id=%s", job.id, run_id)
- async def _push_to_targets(self, job: CronJob, state: CronRunState, *, text: str, is_placeholder: bool) -> None:
- logger.info(
- "[Cron] push_to_targets job=%s run_id=%s channel=%s is_placeholder=%s text_len=%d status=%s",
+ async def _push_to_targets(
+ self,
+ job: CronJob,
+ state: CronRunState,
+ *,
+ text: str,
+ is_placeholder: bool,
+ event_type: EventType = EventType.CHAT_FINAL,
+ payload: dict | None = None,
+ message_id: str | None = None,
+ ) -> None:
+ _log = logger.debug if event_type in _CRON_QUIET_PUSH_EVENTS else logger.info
+ _log(
+ "[Cron] push_to_targets job=%s run_id=%s channel=%s is_placeholder=%s text_len=%d status=%s event=%s",
job.id,
state.run_id,
(job.targets or "").strip(),
bool(is_placeholder),
len(text or ""),
state.status,
+ getattr(event_type, "value", event_type),
)
broadcast_text = _format_cron_broadcast_text(
job_name=job.name,
text=text,
is_placeholder=is_placeholder,
)
- payload_extra = {
- "content": broadcast_text,
- "cron": {
- "job_id": job.id,
- "job_name": job.name,
- "run_id": state.run_id,
- "push_at": state.push_at_iso,
- "wake_at": state.wake_at_iso,
- "exec_channel_id": state.exec_channel_id,
- "exec_session_id": state.exec_session_id,
- "is_placeholder": bool(is_placeholder),
- "status": state.status,
- },
+ cron_meta = {
+ "job_id": job.id,
+ "job_name": job.name,
+ "run_id": state.run_id,
+ "push_at": state.push_at_iso,
+ "wake_at": state.wake_at_iso,
+ "exec_channel_id": state.exec_channel_id,
+ "exec_session_id": state.exec_session_id,
+ "is_placeholder": bool(is_placeholder),
+ "status": state.status,
}
+ if payload is None:
+ payload_extra = {
+ "content": broadcast_text,
+ "cron": cron_meta,
+ }
+ else:
+ payload_extra = dict(payload)
+ payload_extra["cron"] = cron_meta
+ if state.exec_session_id:
+ payload_extra["session_id"] = state.exec_session_id
+ payload_extra["exec_session_id"] = state.exec_session_id
channel_id = (job.targets or "").strip()
if not channel_id:
# targets 为空:占位/真实结果/push_update 补发均会在此静默丢失。
@@ -2424,7 +3116,7 @@ class CronSchedulerService:
_msg_app_id = str(getattr(job, "app_id", None) or "").strip() or None
msg = Message(
- id=f"cron-push-{state.run_id}-{channel_id}",
+ id=message_id or f"cron-push-{state.run_id}-{channel_id}",
type="event",
channel_id=channel_id,
session_id=msg_session_id,
@@ -2432,9 +3124,42 @@ class CronSchedulerService:
timestamp=self._now_fn(),
ok=True,
payload=payload_extra,
- event_type=EventType.CHAT_FINAL,
+ event_type=event_type,
metadata=metadata,
group_digital_avatar=_group_digital_avatar,
app_id=_msg_app_id,
)
+ # live 扇出与 WebChannel 投递解耦:企业版 HTTP 无 WS,不能因 channel 发送失败丢思考/审批帧。
+ self._mirror_cron_execution_live(state, event_type, payload_extra)
await self._message_handler.publish_robot_messages(msg)
+
+ @staticmethod
+ def _mirror_cron_execution_live(
+ state: CronRunState,
+ event_type: EventType,
+ payload: dict | None,
+ ) -> None:
+ """Copy a cron frame onto the live bus for the open ``cron_*`` window."""
+ sid = str(getattr(state, "exec_session_id", "") or "").strip()
+ if not sid or not isinstance(payload, dict):
+ return
+ name = event_type.value if isinstance(event_type, EventType) else str(event_type)
+ if name not in _CRON_LIVE_MIRROR_EVENTS:
+ return
+ cron_meta = payload.get("cron")
+ if isinstance(cron_meta, dict) and cron_meta.get("is_placeholder"):
+ return
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus
+
+ cron_live_bus.publish(sid, {
+ "type": "event",
+ "event": name,
+ "payload": payload,
+ })
+ # Finished runs must not leave deltas/finals in the replay buffer: a later
+ # page refresh would replay them over history and replace the newest
+ # follow-up answer with the first cron-run answer.
+ if name == "chat.processing_status" and payload.get("is_processing") is False:
+ cron_live_bus.clear_session(sid)
+ elif name == "chat.final":
+ cron_live_bus.clear_session(sid)
diff --git a/jiuwenswarm/gateway/cron/tenant_registry.py b/jiuwenswarm/gateway/cron/tenant_registry.py
index 6c16669b32..a5df53172e 100644
--- a/jiuwenswarm/gateway/cron/tenant_registry.py
+++ b/jiuwenswarm/gateway/cron/tenant_registry.py
@@ -332,6 +332,21 @@ class CronTenantRegistry:
)
return data
+ def release_cron_permission_hold(self, session_id: str) -> None:
+ """审批续跑成功后放开调度(见 ``mark_permission_resume_succeeded``)。"""
+ sid = str(session_id or "").strip()
+ if not sid.startswith("cron_"):
+ return
+ for controller in list(self._controllers.values()):
+ scheduler = getattr(controller, "_scheduler", None)
+ mark = getattr(scheduler, "mark_permission_resume_succeeded", None)
+ if callable(mark):
+ mark(sid)
+ continue
+ release = getattr(scheduler, "release_permission_hold_for_session", None)
+ if callable(release):
+ release(sid)
+
async def stop_all(self) -> None:
for controller in list(self._controllers.values()):
try:
diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.py
index 90271510b9..c4627de5b3 100644
--- a/jiuwenswarm/gateway/message_handler/message_handler.py
+++ b/jiuwenswarm/gateway/message_handler/message_handler.py
@@ -3387,6 +3387,134 @@ class MessageHandler(FileTransferMixin, ABC):
def set_cron_registry(self, registry: Any) -> None:
self._cron_registry = registry
+ def _release_cron_permission_hold(self, session_id: str) -> None:
+ registry = self._cron_registry or self._cron_controller
+ if registry is None:
+ return
+ release = getattr(registry, "release_cron_permission_hold", None)
+ if callable(release):
+ release(session_id)
+ return
+ scheduler = getattr(registry, "_scheduler", None)
+ direct = getattr(scheduler, "release_permission_hold_for_session", None)
+ if callable(direct):
+ direct(session_id)
+
+ @classmethod
+ def _is_cron_interrupt_resume_env(
+ cls,
+ env: Any,
+ session_id: str | None,
+ ) -> bool:
+ """Whether this stream is a cron_* interrupt-resume ``chat.send``."""
+ sid = str(session_id or "").strip()
+ if not sid.startswith("cron_"):
+ return False
+ params = getattr(env, "params", None)
+ if not isinstance(params, dict):
+ return False
+ source = str(params.get("source") or "").strip()
+ if source not in _INTERRUPT_RESUME_SOURCES:
+ return False
+ answers = params.get("answers")
+ request_id = str(params.get("request_id") or "").strip()
+ return bool(request_id) and isinstance(answers, list)
+
+ @staticmethod
+ def _is_outer_hitl_ask_user_payload(payload: dict[str, Any]) -> bool:
+ """Outer-round HITL ask (excludes subagent-forwarded cards that do not pause)."""
+ if payload.get("event_type") != "chat.ask_user_question":
+ return False
+ source = str(payload.get("source") or "").strip()
+ # Align with AgentServer ``_is_ask_user_payload``: these sources do not
+ # end the outer round with invocation_paused.
+ return source not in {"subagent_skill_load", "subagent_tool_permission"}
+
+ def _settle_cron_permission_hold_after_interrupt_stream(
+ self,
+ *,
+ env: Any,
+ session_id: str | None,
+ still_awaiting_hitl: bool,
+ cancelled: bool,
+ request_error: BaseException | None,
+ ) -> None:
+ """Release cron hold only when a permission-resume turn fully settled.
+
+ Keep hold when this resume stream saw another outer HITL ask / pause
+ (multi-tool approval), was cancelled, or errored (interrupt may still
+ be live). Do not release at ``chat.send`` entry. Do not treat
+ intermediate ``chat.final`` as success (see mirror).
+ """
+ if still_awaiting_hitl or cancelled or request_error is not None:
+ return
+ if not self._is_cron_interrupt_resume_env(env, session_id):
+ return
+ sid = str(session_id or "").strip()
+ try:
+ self._release_cron_permission_hold(sid)
+ logger.info(
+ "[MessageHandler] released cron permission hold after interrupt "
+ "resume settled session_id=%s",
+ sid,
+ )
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "[MessageHandler] release cron permission hold after resume "
+ "failed session_id=%s",
+ sid,
+ exc_info=True,
+ )
+
+ def _mirror_cron_live_stream_chunk(
+ self,
+ session_id: str | None,
+ message: Any,
+ ) -> None:
+ """Mirror cron resume ``chat.final`` onto the session live bus.
+
+ After tool permission the scheduler stops reading the agent stream.
+ Resume frames go to the browser ``chat.send`` SSE; also publish the
+ final here so the open ``cron_*`` live watch can show the reply if
+ the SSE path drops it. Deltas are not mirrored (would double-append).
+ Frontend dedupes identical finals.
+
+ Hold release and live ``clear_session`` happen only when the interrupt
+ resume stream settles without another HITL ask/pause — not on each
+ contentful final (multi-tool rounds may emit finals between asks).
+ """
+ sid = str(session_id or "").strip()
+ if not sid.startswith("cron_"):
+ return
+ payload = getattr(message, "payload", None)
+ if not isinstance(payload, dict):
+ return
+ event_name = str(
+ getattr(getattr(message, "event_type", None), "value", None)
+ or payload.get("event_type")
+ or ""
+ ).strip()
+ if event_name != "chat.final":
+ return
+ content = payload.get("content")
+ if not (isinstance(content, str) and content.strip()):
+ return
+ live_bus = None
+ try:
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus as live_bus
+ except ImportError:
+ live_bus = None
+ if live_bus is None:
+ return
+ body = dict(payload)
+ body.setdefault("session_id", sid)
+ body.setdefault("exec_session_id", sid)
+ live_bus.publish(sid, {
+ "type": "event",
+ "event": event_name,
+ "payload": body,
+ })
+
async def _handle_long_horizon_schedule_intent(
self,
*,
@@ -3748,6 +3876,9 @@ class MessageHandler(FileTransferMixin, ABC):
app_id=self._stream_app_ids.get(chunk.request_id, ""),
)
await self.publish_robot_messages(out)
+ # 企业版 cron_* 窗口靠 live SSE;审批续跑走 chat.send,调度器已停读。
+ # 把终态正文再镜像到 live bus,避免只有思考/工具、刷新后才见回复。
+ self._mirror_cron_live_stream_chunk(session_id, out)
return True
async def _publish_stream_cancelled_final(
@@ -4769,6 +4900,11 @@ class MessageHandler(FileTransferMixin, ABC):
continue
+ # 定时任务审批 hold 在 interrupt 续跑流 settle 后释放,见
+ # _settle_cron_permission_hold_after_interrupt_stream。
+ # 入口过早 release 会在 resume 失败时被下一轮调度切入;
+ # 中间 chat.final 也不再单独释放(多工具二次审批会误清)。
+
# ---- Inbound Pipeline(数字分身入站过滤)----
if self._inbound_pipeline is not None and msg.req_method == ReqMethod.CHAT_SEND:
try:
@@ -5089,6 +5225,12 @@ class MessageHandler(FileTransferMixin, ABC):
)
cancelled = False
has_processing_status_false = False
+ # Agent HITL 以 invocation_paused 收尾,故意不发 processing=false。
+ # 若此处仍补发 false,cron 审批续跑的第二次权限卡会被前端当「已完成」清掉。
+ # 另计 saw_outer_hitl_ask:pause 帧丢失时仍凭权限 ask 判定「仍在等用户」。
+ awaiting_user_input_pause = False
+ saw_outer_hitl_ask = False
+ track_cron_interrupt_resume = self._is_cron_interrupt_resume_env(env, session_id)
_proc_count = 0
logger.info(
"[MessageHandler] process_stream started: request_id=%s channel=%s session=%s",
@@ -5129,6 +5271,12 @@ class MessageHandler(FileTransferMixin, ABC):
# ends, and is NOT forwarded to the frontend.
has_processing_status_false = True
continue
+ elif event_type == "chat.invocation_paused" or payload.get(
+ "awaiting_user_input"
+ ):
+ awaiting_user_input_pause = True
+ elif self._is_outer_hitl_ask_user_payload(payload):
+ saw_outer_hitl_ask = True
_has_fanout = bool((getattr(chunk, "metadata", None) or {}).get("fan_out_targets"))
logger.debug(
@@ -5217,16 +5365,26 @@ class MessageHandler(FileTransferMixin, ABC):
session_blocks_processing_false = (
self._session_has_streams_blocking_processing_false(session_id)
)
+ # HITL 暂停:流读完了但轮次仍在等用户;cancelled 仍要补 false 停转圈。
+ # 外层权限 ask(含 pause 帧丢失)同样视为仍在等用户,避免二次审批假完成。
+ still_awaiting_hitl = bool(
+ awaiting_user_input_pause or saw_outer_hitl_ask
+ )
+ skip_processing_false_for_hitl = (
+ still_awaiting_hitl and not cancelled
+ )
_will_broadcast = (
emit_processing_status
and not has_processing_status_false
and not session_blocks_processing_false
+ and not skip_processing_false_for_hitl
)
logger.info(
"[task.global_running] stream 退出: rid=%s cancelled=%s emit=%s "
- "has_status_false=%s remaining_stream=%d remaining_chat=%d "
- "will_broadcast_processing_status=%s",
+ "has_status_false=%s hitl_pause=%s hitl_ask=%s remaining_stream=%d "
+ "remaining_chat=%d will_broadcast_processing_status=%s",
rid, cancelled, emit_processing_status, has_processing_status_false,
+ awaiting_user_input_pause, saw_outer_hitl_ask,
len(self._stream_modes), len(self._active_chat_tasks),
_will_broadcast,
)
@@ -5242,8 +5400,19 @@ class MessageHandler(FileTransferMixin, ABC):
# 让 TUI 立刻停转圈,不等 AgentServer 回 interrupt_result。
# 守卫:同 session 还有 chat.send 或 command.goal 时不误发 false
# (避免权限同意短流在 Goal 仍跑时清前端;history.get 不挡)。
+ # 守卫:invocation_paused / awaiting_user_input / 外层权限 ask 收尾时不补发。
if emit_processing_status and not has_processing_status_false:
- if not session_blocks_processing_false:
+ if skip_processing_false_for_hitl:
+ logger.info(
+ "[MessageHandler] stream paused for user input, "
+ "skip is_processing=false: session_id=%s request_id=%s "
+ "pause=%s ask=%s",
+ session_id,
+ rid,
+ awaiting_user_input_pause,
+ saw_outer_hitl_ask,
+ )
+ elif not session_blocks_processing_false:
await self._send_processing_status(
rid, session_id, channel_id,
is_processing=False, app_id=stream_app_id,
@@ -5254,6 +5423,16 @@ class MessageHandler(FileTransferMixin, ABC):
cancelled,
session_id,
)
+ # cron 审批续跑:仅在本流未再出现外层 HITL ask/pause、且未取消时释放 hold。
+ # clear_session 随 mark/release 一并发生;中间 contentful final 不再清 hold。
+ if track_cron_interrupt_resume:
+ self._settle_cron_permission_hold_after_interrupt_stream(
+ env=env,
+ session_id=session_id,
+ still_awaiting_hitl=still_awaiting_hitl,
+ cancelled=cancelled,
+ request_error=request_error,
+ )
async def _send_stream_cancelled_notification(
self, request_id: str | None, channel_id: str, session_id: str | None
diff --git a/jiuwenswarm/server/handlers/_default.py b/jiuwenswarm/server/handlers/_default.py
index 1ec2ec7288..19499f036b 100644
--- a/jiuwenswarm/server/handlers/_default.py
+++ b/jiuwenswarm/server/handlers/_default.py
@@ -614,12 +614,35 @@ async def _prepare_code_mode_chat_turn(
request.metadata["project_dir"] = project_dir
manager = agent_manager or ctx.services.agent_manager
await manager.wait_for_session_prewarm(request.session_id)
- agent = await manager.get_agent(
- channel_id=channel_id,
- mode=agent_mode,
- project_dir=project_dir,
- sub_mode=sub_mode,
- )
+ # Scheme A: 普通续聊走请求 channel(web);审批/HITL 续跑回到挂着 interrupt 的实例。
+ session_id = str(request.session_id or "").strip()
+ if is_interrupt_continuation:
+ owned = None
+ find_paused = getattr(manager, "find_agent_for_interrupt_resume_nowait", None)
+ if callable(find_paused):
+ owned = find_paused(session_id)
+ if owned is not None:
+ logger.info(
+ "[_prepare_code_mode_chat_turn] interrupt resume reuse session owner: "
+ "session_id=%s source=%s",
+ session_id,
+ source or "-",
+ )
+ return mode, sub_mode, owned
+ resume_channel = "__cron__" if session_id.startswith("cron_") else channel_id
+ agent = await manager.get_agent(
+ channel_id=resume_channel,
+ mode=agent_mode,
+ project_dir=project_dir,
+ sub_mode=sub_mode,
+ )
+ else:
+ agent = await manager.get_agent(
+ channel_id=channel_id,
+ mode=agent_mode,
+ project_dir=project_dir,
+ sub_mode=sub_mode,
+ )
if agent is None:
raise ValueError("Failed to get agent")
return mode, sub_mode, agent
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index e56f501489..8377e95a25 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -1249,7 +1249,13 @@ class JiuWenSwarm:
request: AgentRequest,
session_id: str,
) -> None:
- """Record HITL resume so refresh does not revive an already-answered card."""
+ """Record HITL resume so refresh does not revive an already-answered card.
+
+ Persist the **card** ``request_id`` as the client sent it (including
+ ``{call_id}#{n}``). Harness routing still strips the suffix elsewhere;
+ history restore matches on the card id, and stripping here made refresh
+ resurrect permission cards after a successful approve.
+ """
params = request.params if isinstance(request.params, dict) else {}
answers = params.get("answers")
status = params.get("status")
@@ -1257,10 +1263,14 @@ class JiuWenSwarm:
has_status = isinstance(status, str) and bool(status.strip())
if not has_answers and not has_status:
return
- rid = _ask_user_answer_request_id(params, request.request_id)
+ raw_rid = str(params.get("request_id") or "").strip()
+ rid = raw_rid or _ask_user_answer_request_id(params, request.request_id)
if not rid:
return
extra: dict[str, Any] = {"request_id": rid}
+ base_rid = strip_hitl_seq_suffix(rid)
+ if base_rid and base_rid != rid:
+ extra["base_request_id"] = base_rid
source = str(params.get("source") or "").strip()
if source:
extra["source"] = source
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 0d02d54636..c66df2ebe8 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -2715,6 +2715,9 @@ class JiuWenSwarmDeepAdapter:
self._audio_tools: list[Any] = []
self._instance_overrides: dict[str, Any] = {}
self._is_session_scoped_adapter: bool = False
+ self._session_parent_adapter: "JiuWenSwarmDeepAdapter | None" = None
+ # Parent-only: cron/tool pause pins so eviction and session lookup keep the owner.
+ self._sessions_awaiting_tool_permission: set[str] = set()
self._steering_control: SteeringSession | None = None
self._parent_session_id: str | None = None
# 业务对话 ID(thread_id):由 mark_as_session_scoped 从 bootstrap request 透传。
@@ -3016,6 +3019,7 @@ class JiuWenSwarmDeepAdapter:
if value is not None:
setattr(adapter, attribute, value)
adapter.mark_as_session_scoped(session_id, thread_id=thread_id)
+ adapter.bind_session_parent_adapter(self)
# Session adapters must inherit the parent's tenant env namespace. A fresh
# adapter defaults to default/default and would read placeholder .env
# model credentials instead of the synced per-agent tip bag.
@@ -3037,6 +3041,18 @@ class JiuWenSwarmDeepAdapter:
self._parent_session_id = session_id
self._parent_thread_id = thread_id
+ def bind_session_parent_adapter(self, parent: "JiuWenSwarmDeepAdapter") -> None:
+ """Wire this session-scoped adapter back to its channel parent."""
+ self._session_parent_adapter = parent
+
+ def ensure_sessions_awaiting_tool_permission(self) -> set[str]:
+ """Return the shared awaiting-permission set, creating it if needed."""
+ awaiting = getattr(self, "_sessions_awaiting_tool_permission", None)
+ if not isinstance(awaiting, set):
+ self._sessions_awaiting_tool_permission = set()
+ awaiting = self._sessions_awaiting_tool_permission
+ return awaiting
+
def _get_cached_session_adapter(self, session_id: str | None) -> "JiuWenSwarmDeepAdapter | None":
sid = self._session_adapter_key(session_id)
return self._session_adapters.get(sid)
@@ -3160,6 +3176,8 @@ class JiuWenSwarmDeepAdapter:
checkpoint_uncertain = bool(
getattr(adapter, "_deepresearch_rewrite_tx_uncertain", False)
)
+ if sid in self._sessions_awaiting_tool_permission:
+ continue
last_used = self._session_adapter_last_used.get(sid, 0.0)
if (
not checkpoint_uncertain
@@ -3235,6 +3253,7 @@ class JiuWenSwarmDeepAdapter:
exc,
)
return False
+ self.clear_session_awaiting_tool_permission(sid)
self._drop_session_adapter_cache_entry(sid, remove_lock=False)
remove_lock_after_release = True
cleaned = True
@@ -3675,12 +3694,49 @@ class JiuWenSwarmDeepAdapter:
return ReloadResult(deferred=True)
return None
+ def mark_session_awaiting_tool_permission(self, session_id: str) -> None:
+ """Pin a paused tool-approval session on the channel parent adapter."""
+ sid = self._session_adapter_key(session_id)
+ if not sid or sid == "default":
+ return
+ parent = self
+ if self._is_session_scoped_adapter:
+ parent = self._session_parent_adapter or self
+ awaiting = parent.ensure_sessions_awaiting_tool_permission()
+ awaiting.add(sid)
+ touch = getattr(parent, "_touch_session_adapter", None)
+ if callable(touch):
+ touch(sid)
+
+ def clear_session_awaiting_tool_permission(self, session_id: str) -> None:
+ sid = self._session_adapter_key(session_id)
+ parent = self._session_parent_adapter if self._is_session_scoped_adapter else self
+ if parent is None:
+ parent = self
+ awaiting = getattr(parent, "_sessions_awaiting_tool_permission", None)
+ if isinstance(awaiting, set):
+ awaiting.discard(sid)
+
+ def _clear_cron_awaiting_if_interrupt_gone(self, session_id: str) -> None:
+ """审批续跑收尾:interrupt 已消费则解除 pin,允许空闲驱逐。
+
+ 仍持有 live interrupt(含多工具连续审批中)时不清理。
+ """
+ sid = str(session_id or "").strip()
+ if not sid.startswith("cron_"):
+ return
+ if self._read_session_interrupt_state() is not None:
+ return
+ self.clear_session_awaiting_tool_permission(sid)
+
def has_session_runtime(self, session_id: str | None = None) -> bool:
"""Return whether this adapter still owns session runtime."""
if session_id is not None:
sid = self._session_adapter_key(session_id)
if self._is_session_scoped_adapter:
return self._session_adapter_key(self._parent_session_id) == sid
+ if sid in self._sessions_awaiting_tool_permission:
+ return True
return bool(
sid in self._session_adapters
or sid in self._session_adapter_locks
@@ -13328,6 +13384,227 @@ class JiuWenSwarmDeepAdapter:
pass
return False
+ @staticmethod
+ def _cron_execution_checkpointer(inner_session: Any) -> Any:
+ """cron 落盘用的是 session 自己的 checkpointer,恢复必须读同一份。"""
+ getter = getattr(inner_session, "checkpointer", None)
+ if callable(getter):
+ checkpointer = getter()
+ if checkpointer is not None:
+ return checkpointer
+ return CheckpointerFactory.get_checkpointer()
+
+ def _read_session_interrupt_state(self) -> Any:
+ """当前交互会话里的工具暂停。没有则返回 None。"""
+ instance = getattr(self, "_instance", None)
+ if instance is None:
+ return None
+ sessions = (
+ getattr(instance, "_interaction_session", None),
+ getattr(instance, "_loop_session", None),
+ )
+ seen: list[Any] = []
+ for session in sessions:
+ if session is None or any(session is item for item in seen):
+ continue
+ seen.append(session)
+ targets = (session, getattr(session, "_inner", None))
+ for target in targets:
+ if target is None:
+ continue
+ getter = getattr(target, "get_state", None)
+ if not callable(getter):
+ continue
+ try:
+ state = getter(INTERRUPTION_KEY)
+ except Exception: # noqa: BLE001
+ continue
+ if state is not None:
+ return state
+ return None
+
+ async def _reload_cron_interrupt(self, cron_inner: Any, session_id: str, request_id: str) -> None:
+ """审批续跑时,从执行落盘的 checkpointer 把暂停中的工具调用读回来。"""
+ if self._read_session_interrupt_state() is not None:
+ return
+ candidates: list[Any] = []
+ primary = self._cron_execution_checkpointer(cron_inner)
+ adapter_cp = self._get_adapter_checkpointer()
+ factory_cp = CheckpointerFactory.get_checkpointer()
+ for candidate in (primary, adapter_cp, factory_cp):
+ if candidate is None or any(candidate is item for item in candidates):
+ continue
+ candidates.append(candidate)
+ for checkpointer in candidates:
+ try:
+ await checkpointer.pre_agent_execute(cron_inner, None)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[CRON-CTX] cron interrupt reload failed: session_id=%s "
+ "error=%s request_id=%s",
+ session_id, exc, request_id,
+ )
+ continue
+ if self._read_session_interrupt_state() is not None:
+ logger.info(
+ "[CRON-CTX] cron interrupt reloaded: session_id=%s request_id=%s",
+ session_id, request_id,
+ )
+ return
+
+ async def _recover_cron_session_context(
+ self,
+ session_id: str,
+ request_id: str,
+ *,
+ reload_interrupt: bool = False,
+ ) -> None:
+ """cron_* 续聊 / 审批续跑:从执行时写入的 checkpointer 恢复,空上下文再回灌一次历史。"""
+ if not str(session_id).startswith("cron_") or self._instance is None:
+ return
+ cron_session = getattr(self._instance, "_interaction_session", None)
+ cron_inner = getattr(cron_session, "_inner", None) if cron_session is not None else None
+ if cron_inner is None:
+ return
+ if not self._cron_session_has_context(cron_inner):
+ try:
+ await self._cron_execution_checkpointer(cron_inner).pre_agent_execute(
+ cron_inner, None
+ )
+ logger.info(
+ "[CRON-CTX] cron session re-recover: session_id=%s request_id=%s",
+ session_id, request_id,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[CRON-CTX] cron session re-recover failed: session_id=%s "
+ "error=%s request_id=%s",
+ session_id, exc, request_id,
+ )
+ if reload_interrupt:
+ await self._reload_cron_interrupt(cron_inner, session_id, request_id)
+ if self._cron_session_has_context(cron_inner):
+ return
+ await self._rehydrate_empty_cron_context(session_id, request_id)
+
+ _STALE_CRON_PERMISSION_TEXT = (
+ "这次审批没有对上暂停中的命令,已停止,避免重新生成另一条命令。"
+ "请重新执行该定时任务。"
+ )
+
+ async def _block_stale_cron_permission_resume(self, request: Any) -> bool:
+ """cron_* 审批续跑:恢复后仍无 paused tool 则硬拦,避免误开新一轮工具。
+
+ 返回 True 表示调用方应拒绝本次 resume,并向用户展示
+ ``_STALE_CRON_PERMISSION_TEXT``。
+ """
+ session_id = str(getattr(request, "session_id", "") or "")
+ params = request.params if isinstance(getattr(request, "params", None), dict) else {}
+ reload_interrupt = (
+ session_id.startswith("cron_")
+ and str(params.get("source") or "") == "permission_interrupt"
+ )
+ if not reload_interrupt:
+ return False
+ await self._recover_cron_session_context(
+ session_id,
+ str(getattr(request, "request_id", "") or ""),
+ reload_interrupt=True,
+ )
+ if self._read_session_interrupt_state() is not None:
+ return False
+ logger.warning(
+ "[CRON-CTX] blocking stale cron permission resume (no paused tool): "
+ "session_id=%s bound_session_id=%s request_id=%s",
+ session_id,
+ self._bound_interaction_session_id(),
+ getattr(request, "request_id", ""),
+ )
+ return True
+
+ def _bound_interaction_session_id(self) -> str:
+ session = getattr(getattr(self, "_instance", None), "_interaction_session", None)
+ if session is None:
+ return ""
+ for target in (session, getattr(session, "_inner", None)):
+ if target is None:
+ continue
+ sid_attr = getattr(target, "session_id", None)
+ if callable(sid_attr):
+ try:
+ sid = str(sid_attr() or "").strip()
+ except Exception: # noqa: BLE001
+ continue
+ if sid:
+ return sid
+ elif isinstance(sid_attr, str) and sid_attr.strip():
+ return sid_attr.strip()
+ return ""
+
+ async def _commit_cron_hitl_pause(self, session_id: str, request_id: str) -> None:
+ """审批卡发出前先把暂停状态落盘,调度器断开读取后仍能续跑同一条命令。"""
+ if not str(session_id or "").startswith("cron_") or self._instance is None:
+ return
+ session = getattr(self._instance, "_interaction_session", None)
+ if session is None:
+ return
+ react_agent = getattr(self._instance, "react_agent", None)
+ context_engine = getattr(react_agent, "context_engine", None) if react_agent is not None else None
+ if context_engine is not None:
+ try:
+ await context_engine.save_contexts(session)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[CRON-CTX] save contexts before permission card failed: "
+ "session_id=%s request_id=%s error=%s",
+ session_id, request_id, exc,
+ )
+ try:
+ await session.commit()
+ self.mark_session_awaiting_tool_permission(session_id)
+ logger.info(
+ "[CRON-CTX] cron interrupt committed before permission card: "
+ "session_id=%s request_id=%s",
+ session_id, request_id,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[CRON-CTX] cron interrupt commit before permission card failed: "
+ "session_id=%s request_id=%s error=%s",
+ session_id, request_id, exc,
+ )
+
+ async def _rehydrate_empty_cron_context(self, session_id: str, request_id: str) -> None:
+ """仅 cron_*:checkpoint 仍空、内存 context 也没有消息时,用历史回灌一次。"""
+ react_agent = getattr(self._instance, "react_agent", None)
+ context_engine = getattr(react_agent, "context_engine", None) if react_agent is not None else None
+ if context_engine is None:
+ return
+ ctx = context_engine.get_context(session_id=session_id)
+ if ctx is not None:
+ try:
+ if list(ctx.get_messages() or []):
+ return
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ await context_engine.clear_context(session_id=session_id)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[CRON-CTX] clear empty cron context failed: session_id=%s error=%s",
+ session_id, exc,
+ )
+ return
+ from jiuwenswarm.agents.harness.common.session_ops_service import (
+ warmup_session_context,
+ )
+
+ await warmup_session_context(
+ deep_agent=self._instance,
+ session_id=session_id,
+ history_before_request_id=request_id,
+ )
+
async def _persist_cron_checkpoint(self, session_id: str, request_id: str) -> None:
"""非流式 cron 执行收尾补 commit:把 context_engine 内存 context 落盘到 checkpointer。
@@ -13335,7 +13612,8 @@ class JiuWenSwarmDeepAdapter:
``start_interaction`` 已提前绑定 session,``invoke`` 收到现成 session 致 ``need_cleanup=False``,
commit 被跳过,导致 ``cron_*`` 在 checkpointer 恒为空、web 恢复读不到历史。此处对齐流式路径
(``_inner_stream`` 的 ``is_agent_session`` 分支会自动 commit),显式补一次落盘。
- 姿势参照 ``session_ops_service.rewind_session_context`` 的 save_contexts + post_run。
+ 姿势参照流式收尾:save_contexts 之后走 ``commit()``。
+ ``post_run()`` 在 ``_post_run_done`` 后直接返回,cron 非流式收尾会把落盘跳掉。
"""
try:
if self._instance is None:
@@ -13356,7 +13634,7 @@ class JiuWenSwarmDeepAdapter:
return
# 用运行中的 _interaction_session(而非新建 session):
# save_contexts 内部 _save_state_to_session 会把 context messages 存回该 session 的
- # global_state['context'],post_run 再落盘 checkpointer。跨 channel 的 web adapter
+ # global_state['context'],commit 再落盘 checkpointer。跨 channel 的 web adapter
# 复用本会话时会通过上方的 re-recover 从 checkpoint 读回这些 messages。
session = getattr(self._instance, "_interaction_session", None)
if session is None:
@@ -13367,7 +13645,8 @@ class JiuWenSwarmDeepAdapter:
)
return
await context_engine.save_contexts(session)
- await session.post_run() # → post_agent_execute → _agent_storage.save 落盘
+ # post_run 在 _post_run_done 后会直接返回,cron 非流式收尾必须走 commit。
+ await session.commit()
logger.info(
"[CRON-CTX] cron checkpoint committed: session_id=%s request_id=%s "
"msg_count=%s",
@@ -15484,13 +15763,19 @@ class JiuWenSwarmDeepAdapter:
*,
segment_streamed_text: str,
chunk_payload: Any,
+ preserve_final_content: bool = False,
) -> list[dict[str, Any]]:
"""Move non-empty ``chat.final`` body onto ``chat.delta`` when needed.
- Always clears ``parsed["content"]`` once the body is known to be (or about
- to be) on the delta path. Leaving content on ``chat.final`` makes
+ By default clears ``parsed["content"]`` once the body is known to be (or
+ about to be) on the delta path. Leaving content on ``chat.final`` makes
RelayClaw ``computeFinalTextDelta`` append another copy — especially after
the post-tool ``\\n\\n`` round-break prefix — triplicating the bubble.
+
+ ``preserve_final_content`` (cron_* web follow-up): still emit rescue
+ deltas, but keep final body so Gateway history / live-bus mirror can
+ fall back when delta frames are dropped. Web UI treats identical final
+ as overwrite, not append.
"""
if parsed.get("event_type") != "chat.final":
return []
@@ -15500,20 +15785,24 @@ class JiuWenSwarmDeepAdapter:
return []
streamed = str(segment_streamed_text or "")
if stripped in streamed or streamed.rstrip().endswith(stripped):
- parsed["content"] = ""
+ if not preserve_final_content:
+ parsed["content"] = ""
return []
streamed_visible = streamed.strip()
# llm_output already delivered a substantial body this segment; keeping
# final content would re-route a duplicate chat.delta.
if streamed_visible and len(streamed_visible) >= max(8, len(stripped) // 4):
- parsed["content"] = ""
+ if not preserve_final_content:
+ parsed["content"] = ""
return []
deltas = JiuWenSwarmDeepAdapter._iter_delta_for_unstreamed_final(
content=content,
chunk_payload=chunk_payload,
)
- # Body rides on delta; final is trailer-only for non-team hosts.
- parsed["content"] = ""
+ # Body rides on delta; final is trailer-only for non-team hosts —
+ # unless cron_* needs final as history/live fallback.
+ if not preserve_final_content:
+ parsed["content"] = ""
return deltas
@staticmethod
@@ -19152,26 +19441,24 @@ class JiuWenSwarmDeepAdapter:
query = request.params.get("query", "")
mode = request.params.get("mode", "agent")
- # [CRON-CTX] 非流式入口:与流式对称,跨 channel 时强制 recover cron 历史。
- if str(session_id).startswith("cron_") and self._instance is not None:
- _cron_sess = getattr(self._instance, "_interaction_session", None)
- _cron_inner = getattr(_cron_sess, "_inner", None) if _cron_sess is not None else None
- if _cron_inner is not None and not self._cron_session_has_context(_cron_inner):
- try:
- await self._get_adapter_checkpointer().pre_agent_execute(
- _cron_inner, None
- )
- logger.info(
- "[CRON-CTX] cron session re-recover(non-stream): session_id=%s "
- "request_id=%s",
- session_id, request.request_id,
- )
- except Exception as _e: # noqa: BLE001
- logger.warning(
- "[CRON-CTX] cron session re-recover(non-stream) failed: "
- "session_id=%s error=%s request_id=%s",
- session_id, _e, request.request_id,
- )
+ # [CRON-CTX] 非流式入口:与流式对称,只恢复 cron_*。
+ # 对不上暂停工具的审批点击在这里停下,不再当成新的用户消息。
+ if await self._block_stale_cron_permission_resume(request):
+ return AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={
+ "event_type": "chat.error",
+ "error": self._STALE_CRON_PERMISSION_TEXT,
+ },
+ metadata=request.metadata,
+ )
+ elif str(session_id).startswith("cron_"):
+ # 普通续聊:与审批续跑共享空上下文恢复(docstring 已声明覆盖续聊)。
+ await self._recover_cron_session_context(
+ session_id, str(request.request_id or ""),
+ )
token_trace_sid = _LLM_TRACE_SESSION_ID.set(session_id)
token_log_sid = set_log_session_id(request.session_id)
@@ -19693,6 +19980,16 @@ class JiuWenSwarmDeepAdapter:
"step=cron_checkpoint error_type=%s",
type(exc).__name__,
)
+ try:
+ self._clear_cron_awaiting_if_interrupt_gone(session_id)
+ except BaseException as exc:
+ if cleanup_error is None:
+ cleanup_error = exc
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] cleanup failed: "
+ "step=cron_awaiting_clear error_type=%s",
+ type(exc).__name__,
+ )
if active_error is None and cleanup_error is not None:
raise cleanup_error
@@ -19952,33 +20249,24 @@ class JiuWenSwarmDeepAdapter:
query = request.params.get("query", "")
mode = request.params.get("mode", "agent")
- # [CRON-CTX] 跨 channel(cron 写 / web 读)恢复:cron 与 web 是不同 channel_key,
- # 各自持有独立 JiuWenSwarm → 独立 adapter → 独立 _session_adapters 缓存。web adapter
- # 的 session 在 cron 执行前 pre_run 过、读的是旧 checkpoint;cron 落盘新 context 后
- # web adapter HIT cache 复用、不重跑 pre_run,session.global_state 无 context。
- # 此处检测到无 context 时强制重新 recover 一次,把 checkpoint 里 cron 的历史灌进
- # 当前 session。姿势同 Session.pre_run 内部:直接调
- # checkpointer.pre_agent_execute(_inner, None),绕过 _pre_run_done 守卫。
- # recover→_restore_state→set_state 会覆盖整个 global_state(本场景即所求:从 checkpoint
- # 还原)。仅 cron_* session 触发,避免影响普通 web 会话。
- if str(session_id).startswith("cron_") and self._instance is not None:
- _cron_sess = getattr(self._instance, "_interaction_session", None)
- _cron_inner = getattr(_cron_sess, "_inner", None) if _cron_sess is not None else None
- if _cron_inner is not None and not self._cron_session_has_context(_cron_inner):
- try:
- await self._get_adapter_checkpointer().pre_agent_execute(
- _cron_inner, None
- )
- logger.info(
- "[CRON-CTX] cron session re-recover: session_id=%s request_id=%s",
- session_id, request.request_id,
- )
- except Exception as _e: # noqa: BLE001
- logger.warning(
- "[CRON-CTX] cron session re-recover failed: session_id=%s "
- "error=%s request_id=%s",
- session_id, _e, request.request_id,
- )
+ # [CRON-CTX] 跨 channel 续聊:读执行 checkpointer,空上下文再回灌历史。仅 cron_*。
+ # 对不上暂停工具的审批点击在这里停下,不再开一轮新的模型调用。
+ if await self._block_stale_cron_permission_resume(request):
+ yield AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload={
+ "event_type": "chat.error",
+ "error": self._STALE_CRON_PERMISSION_TEXT,
+ },
+ is_complete=True,
+ )
+ return
+ elif str(session_id).startswith("cron_"):
+ # 普通续聊:与审批续跑共享空上下文恢复(docstring 已声明覆盖续聊)。
+ await self._recover_cron_session_context(
+ session_id, str(rid or ""),
+ )
token_trace_sid = _LLM_TRACE_SESSION_ID.set(session_id)
token_log_sid = set_log_session_id(request.session_id)
@@ -20309,6 +20597,8 @@ class JiuWenSwarmDeepAdapter:
accumulated_reasoning = ""
had_assistant_output = False
emitted_terminal_chat_final = False
+ # cron_* 续聊/审批:delta 若丢帧,仍靠 chat.final 落 PG / live mirror。
+ preserve_cron_final = str(session_id or "").startswith("cron_")
usage_accumulator = {
"input_tokens": 0,
"output_tokens": 0,
@@ -21022,6 +21312,7 @@ class JiuWenSwarmDeepAdapter:
continue
if self._is_ask_user_payload(parsed):
hitl_pending_stream = True
+ await self._commit_cron_hitl_pause(session_id, rid)
if accumulated_text:
yield AgentResponseChunk(
request_id=rid,
@@ -21193,6 +21484,7 @@ class JiuWenSwarmDeepAdapter:
parsed,
segment_streamed_text=segment_streamed_text,
chunk_payload=chunk.payload,
+ preserve_final_content=preserve_cron_final,
):
yield AgentResponseChunk(
request_id=rid,
@@ -21204,6 +21496,7 @@ class JiuWenSwarmDeepAdapter:
continue
if self._is_ask_user_payload(parsed):
hitl_pending_stream = True
+ await self._commit_cron_hitl_pause(session_id, rid)
if parsed.get("event_type") == "chat.final":
self._stream_content_run_kind = None
if parsed.get("event_type") == "chat.error":
@@ -21233,6 +21526,7 @@ class JiuWenSwarmDeepAdapter:
parsed,
segment_streamed_text=segment_streamed_text,
chunk_payload=chunk.payload,
+ preserve_final_content=preserve_cron_final,
):
yield AgentResponseChunk(
request_id=rid,
@@ -21244,6 +21538,7 @@ class JiuWenSwarmDeepAdapter:
continue
if self._is_ask_user_payload(parsed):
hitl_pending_stream = True
+ await self._commit_cron_hitl_pause(session_id, rid)
if parsed.get("event_type") == "chat.final":
self._stream_content_run_kind = None
if parsed.get("event_type") == "chat.error":
@@ -21305,6 +21600,7 @@ class JiuWenSwarmDeepAdapter:
parsed,
segment_streamed_text=segment_streamed_text,
chunk_payload=getattr(chunk, "payload", None),
+ preserve_final_content=preserve_cron_final,
):
yield AgentResponseChunk(
request_id=rid,
@@ -21316,6 +21612,7 @@ class JiuWenSwarmDeepAdapter:
continue
if self._is_ask_user_payload(parsed):
hitl_pending_stream = True
+ await self._commit_cron_hitl_pause(session_id, rid)
if parsed.get("event_type") == "chat.final":
self._stream_content_run_kind = None
if parsed.get("event_type") == "chat.error":
@@ -21416,8 +21713,10 @@ class JiuWenSwarmDeepAdapter:
is_complete=False,
)
# Body already on delta; keep final empty to avoid RelayClaw
- # computeFinalTextDelta appending a duplicate copy.
- fallback_content = ""
+ # computeFinalTextDelta appending a duplicate copy — except
+ # cron_* which needs final as history/live fallback.
+ if not preserve_cron_final:
+ fallback_content = ""
yield AgentResponseChunk(
request_id=rid,
channel_id=cid,
@@ -21451,25 +21750,39 @@ class JiuWenSwarmDeepAdapter:
_debug_logger.end_run(status="ok")
interaction_stream_abort = False
except asyncio.CancelledError:
- perf_summary_status = "cancelled"
- stream_consumer_cancelled = initialization_complete
- logger.info(
- "[JiuWenSwarmDeepAdapter] 流式任务被取消: request_id=%s session_id=%s",
- rid,
- session_id,
- )
- # InteractionOutputStream.close() in ``finally`` owns the targeted
- # round abort. Do not issue a second adapter-level abort here:
- # it can race with a newly attached output consumer.
- # Do not yield chat.final here: CancelledError often means the
- # consumer is already tearing down, so the frame may never reach
- # the frontend; user Stop already closes UI via interrupt_result.
- if _debug_logger is not None:
- _debug_logger.end_run(status="cancelled")
- self._revoke_main_skill_authorization(
- session_id,
- reason="task_cancelled",
- )
+ if hitl_pending_stream:
+ # 调度器读到审批卡后会断开自己的流。这不是用户取消:
+ # 暂停中的工具调用留在原会话,等 cron_* 上的审批回复续跑同一条命令。
+ interaction_stream_abort = False
+ stream_consumer_cancelled = False
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] 流式消费者在工具审批暂停后断开,保留中断: "
+ "request_id=%s session_id=%s",
+ rid,
+ session_id,
+ )
+ if _debug_logger is not None:
+ _debug_logger.end_run(status="ok")
+ else:
+ perf_summary_status = "cancelled"
+ stream_consumer_cancelled = initialization_complete
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] 流式任务被取消: request_id=%s session_id=%s",
+ rid,
+ session_id,
+ )
+ # InteractionOutputStream.close() in ``finally`` owns the targeted
+ # round abort. Do not issue a second adapter-level abort here:
+ # it can race with a newly attached output consumer.
+ # Do not yield chat.final here: CancelledError often means the
+ # consumer is already tearing down, so the frame may never reach
+ # the frontend; user Stop already closes UI via interrupt_result.
+ if _debug_logger is not None:
+ _debug_logger.end_run(status="cancelled")
+ self._revoke_main_skill_authorization(
+ session_id,
+ reason="task_cancelled",
+ )
raise
except Exception as exc:
perf_summary_status = "error"
@@ -21497,8 +21810,21 @@ class JiuWenSwarmDeepAdapter:
perf_usage_fallback = snapshot_perf_summary_usage(request.request_id)
if interaction_stream is not None:
try:
+ # 审批卡已发出后,调度器 aclose 会以 GeneratorExit 收流,
+ # 不一定进 CancelledError 分支。这里必须保留暂停,否则
+ # abort 清掉中断,后面的 checkpoint 还会把落盘盖成“无暂停”。
+ abort_active_round = bool(interaction_stream_abort) and not bool(
+ hitl_pending_stream
+ )
+ if hitl_pending_stream and interaction_stream_abort:
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] keep tool interrupt on stream close: "
+ "request_id=%s session_id=%s",
+ rid,
+ session_id,
+ )
await interaction_stream.close(
- abort_active_round=interaction_stream_abort,
+ abort_active_round=abort_active_round,
)
except BaseException as exc:
cleanup_error = exc
@@ -21654,6 +21980,16 @@ class JiuWenSwarmDeepAdapter:
"step=session_checkpoint error_type=%s",
type(exc).__name__,
)
+ try:
+ self._clear_cron_awaiting_if_interrupt_gone(session_id)
+ except BaseException as exc:
+ if cleanup_error is None:
+ cleanup_error = exc
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] cleanup failed: "
+ "step=cron_awaiting_clear error_type=%s",
+ type(exc).__name__,
+ )
if active_error is None and cleanup_error is not None:
raise cleanup_error
diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.py
index 583321d573..37ec7f7df1 100644
--- a/jiuwenswarm/server/runtime/agent_manager.py
+++ b/jiuwenswarm/server/runtime/agent_manager.py
@@ -152,6 +152,55 @@ def _build_acp_agent_config(extra_config: dict[str, Any] | None = None) -> dict[
return config
+_INTERRUPT_RESUME_SOURCES = frozenset(
+ {"permission_interrupt", "confirm_interrupt", "ask_user_interrupt"}
+)
+
+
+def _is_cron_session_request(request: Any) -> bool:
+ """Whether this request targets a cron_* execution session."""
+ return str(getattr(request, "session_id", "") or "").strip().startswith("cron_")
+
+
+def _is_interrupt_resume_request(request: Any) -> bool:
+ """HITL / permission resume (any channel), not a plain follow-up chat.send."""
+ params = getattr(request, "params", None)
+ if not isinstance(params, dict):
+ return False
+ source = str(params.get("source") or "").strip()
+ if source not in _INTERRUPT_RESUME_SOURCES:
+ return False
+ # Align with ``_prepare_code_mode_chat_turn`` interrupt continuation.
+ if not isinstance(params.get("answers"), list):
+ return False
+ return bool(str(params.get("request_id") or "").strip())
+
+
+def _is_cron_permission_resume(request: Any) -> bool:
+ """cron_* + permission_interrupt (legacy helper; prefer interrupt-resume)."""
+ params = getattr(request, "params", None)
+ return (
+ _is_cron_session_request(request)
+ and isinstance(params, dict)
+ and str(params.get("source") or "") == "permission_interrupt"
+ )
+
+
+def _cron_permission_resume_channel(request: Any) -> str:
+ """Fallback lookup channel when interrupt resume has no live session owner.
+
+ cron_* job pauses live on ``__cron__``; plain web follow-up stays on
+ ``request.channel_id``. Outbound replies always use ``request.channel_id``.
+ """
+ if _is_cron_session_request(request) and _is_interrupt_resume_request(request):
+ return "__cron__"
+ return str(getattr(request, "channel_id", "") or "")
+
+
+# 旧名:曾把所有 cron_* 续聊都绑到 __cron__;现仅审批 fallback 用。
+_cron_agent_channel_for_request = _cron_permission_resume_channel
+
+
class AgentManager:
"""管理多个 Agent 实例.
@@ -1028,11 +1077,8 @@ class AgentManager:
return None
for cache_key, agent in channel_agents.items():
- has_runtime = getattr(agent, "has_session_runtime", None)
- if not callable(has_runtime):
- continue
try:
- if has_runtime(sid):
+ if self._agent_owns_session(agent, sid):
return self._borrow_agent(agent)
except Exception:
logger.exception(
@@ -1044,6 +1090,236 @@ class AgentManager:
)
return None
+ @staticmethod
+ def _agent_owns_session(agent: Any, session_id: str) -> bool:
+ """Whether this swarm still holds the session adapter / pause for ``session_id``."""
+ sid = str(session_id or "").strip()
+ if not sid or agent is None:
+ return False
+ has_runtime = getattr(agent, "has_session_runtime", None)
+ if callable(has_runtime):
+ try:
+ if has_runtime(sid):
+ return True
+ except Exception:
+ logger.debug(
+ "[AgentManager] has_session_runtime failed session_id=%s",
+ sid,
+ exc_info=True,
+ )
+ adapter = getattr(agent, "_adapter", None)
+ if adapter is None:
+ adapter = agent
+ awaiting = getattr(adapter, "_sessions_awaiting_tool_permission", None)
+ if isinstance(awaiting, set) and sid in awaiting:
+ return True
+ session_adapters = getattr(adapter, "_session_adapters", None)
+ if isinstance(session_adapters, dict) and sid in session_adapters:
+ return True
+ for candidate in (
+ adapter,
+ *(session_adapters.values() if isinstance(session_adapters, dict) else ()),
+ ):
+ if candidate is None:
+ continue
+ for session_attr in ("_interaction_session", "_loop_session"):
+ session = getattr(getattr(candidate, "_instance", None), session_attr, None)
+ if session is None:
+ continue
+ sid_attr = getattr(session, "session_id", None)
+ try:
+ bound = str(sid_attr() if callable(sid_attr) else (sid_attr or "")).strip()
+ except Exception:
+ bound = ""
+ if bound == sid:
+ return True
+ return False
+
+ @staticmethod
+ def _adapter_interaction_session_id(adapter: Any) -> str:
+ instance = getattr(adapter, "_instance", None)
+ if instance is None:
+ return ""
+ for session_attr in ("_interaction_session", "_loop_session"):
+ session = getattr(instance, session_attr, None)
+ if session is None:
+ continue
+ sid_attr = getattr(session, "session_id", None)
+ try:
+ bound = str(sid_attr() if callable(sid_attr) else (sid_attr or "")).strip()
+ except Exception:
+ bound = ""
+ if bound:
+ return bound
+ return ""
+
+ @classmethod
+ def _agent_interrupt_resume_rank(
+ cls,
+ agent: Any,
+ session_id: str,
+ ) -> tuple[int, float] | None:
+ """Rank an agent for HITL resume. None means it is not holding this pause.
+
+ ``(2, last_used)`` = in-memory paused tool for this session.
+ ``(1, last_used)`` = awaiting-permission flag only (interrupt may be on disk).
+ A prior cron owner that merely still has session runtime is not a candidate:
+ follow-up approvals must return to the agent that just raised the card.
+ """
+ sid = str(session_id or "").strip()
+ if not sid or agent is None:
+ return None
+ live = False
+ awaiting = False
+ last_used = 0.0
+ root = getattr(agent, "_adapter", None) or agent
+ adapters: list[Any] = [root]
+ children = getattr(root, "_session_adapters", None)
+ if isinstance(children, dict):
+ adapters.extend(child for child in children.values() if child is not None)
+ for adapter in adapters:
+ parent = adapter
+ if getattr(adapter, "_is_session_scoped_adapter", False):
+ parent = getattr(adapter, "_session_parent_adapter", None) or adapter
+ awaiting_set = getattr(parent, "_sessions_awaiting_tool_permission", None)
+ if isinstance(awaiting_set, set) and sid in awaiting_set:
+ awaiting = True
+ used_map = getattr(parent, "_session_adapter_last_used", None)
+ if isinstance(used_map, dict):
+ try:
+ last_used = max(last_used, float(used_map.get(sid, 0.0) or 0.0))
+ except (TypeError, ValueError):
+ pass
+ if cls._adapter_interaction_session_id(adapter) != sid:
+ continue
+ read_state = getattr(adapter, "_read_session_interrupt_state", None)
+ if not callable(read_state):
+ continue
+ try:
+ if read_state() is not None:
+ live = True
+ except Exception:
+ logger.debug(
+ "[AgentManager] interrupt state read failed session_id=%s",
+ sid,
+ exc_info=True,
+ )
+ if live:
+ return (2, last_used)
+ if awaiting:
+ return (1, last_used)
+ return None
+
+ def iter_interrupt_resume_candidates_nowait(
+ self,
+ session_id: str,
+ ) -> list[tuple[tuple[int, float], Any]]:
+ """Agents that currently hold this session's pause, best rank last-compared by caller."""
+ sid = str(session_id or "").strip()
+ if not sid:
+ return []
+ found: list[tuple[tuple[int, float], Any]] = []
+ for _channel_key, channel_agents in list(self.agents.items()):
+ if not isinstance(channel_agents, dict):
+ continue
+ for _cache_key, agent in channel_agents.items():
+ try:
+ rank = self._agent_interrupt_resume_rank(agent, sid)
+ except Exception:
+ logger.exception(
+ "[AgentManager] interrupt resume rank failed session_id=%s",
+ sid,
+ )
+ continue
+ if rank is None:
+ continue
+ found.append((rank, self._borrow_agent(agent)))
+ return found
+
+ def find_agent_for_interrupt_resume_nowait(self, session_id: str) -> "JiuWenSwarm | None":
+ """Prefer a live paused tool over a stale session owner."""
+ best_rank: tuple[int, float] | None = None
+ best: Any = None
+ for rank, agent in self.iter_interrupt_resume_candidates_nowait(session_id):
+ if best_rank is None or rank > best_rank:
+ best_rank = rank
+ best = agent
+ return best
+
+ def find_agent_for_session_nowait(self, session_id: str) -> "JiuWenSwarm | None":
+ """Find any cached agent that already owns ``session_id`` (any channel/key)."""
+ sid = str(session_id or "").strip()
+ if not sid:
+ return None
+ for channel_key, channel_agents in list(self.agents.items()):
+ if not isinstance(channel_agents, dict):
+ continue
+ for cache_key, agent in channel_agents.items():
+ try:
+ if self._agent_owns_session(agent, sid):
+ return self._borrow_agent(agent)
+ except Exception:
+ logger.exception(
+ "[AgentManager] session runtime scan failed: "
+ "channel_id=%s session_id=%s cache_key=%s",
+ channel_key,
+ sid,
+ cache_key,
+ )
+ return None
+
+ async def _get_agent_for_request(self, request: Any) -> "JiuWenSwarm | None":
+ """Pick the Agent that should handle this request.
+
+ Scheme A:
+ - Plain follow-up (incl. cron_*): ``request.channel_id`` (usually web).
+ - Interrupt resume: reuse whoever still owns the pause (web or ``__cron__``);
+ cron_* with no live owner falls back to ``get_agent(__cron__)``.
+ """
+ mode, sub_mode, project_dir = self._agent_lookup_from_request(request)
+ session_id = str(getattr(request, "session_id", "") or "").strip()
+ if _is_interrupt_resume_request(request):
+ # 只回到「还挂着这次 pause」的实例。旧 __cron__ 若只是仍占着
+ # session runtime、但没有这条暂停命令,不能拿来续跑。
+ owned = self.find_agent_for_interrupt_resume_nowait(session_id)
+ if owned is not None:
+ logger.info(
+ "[AgentManager] interrupt resume reuse session owner: "
+ "session_id=%s channel_id=%s source=%s",
+ session_id,
+ getattr(owned, "_jiuwenswarm_agent_channel_id", None)
+ or getattr(owned, "channel_id", None)
+ or "-",
+ (getattr(request, "params", None) or {}).get("source")
+ if isinstance(getattr(request, "params", None), dict)
+ else None,
+ )
+ return owned
+ channel_id = _cron_permission_resume_channel(request)
+ if _is_cron_session_request(request):
+ logger.warning(
+ "[AgentManager] interrupt resume has no live session owner; "
+ "fallback get_agent(%s) session_id=%s project_dir=%s",
+ channel_id,
+ session_id,
+ project_dir,
+ )
+ return await self.get_agent(
+ channel_id=channel_id,
+ mode=mode,
+ project_dir=project_dir,
+ sub_mode=sub_mode,
+ request=request if is_enterprise() else None,
+ )
+ channel_id = str(getattr(request, "channel_id", "") or "")
+ return await self.get_agent(
+ channel_id=channel_id,
+ mode=mode,
+ project_dir=project_dir,
+ sub_mode=sub_mode,
+ request=request if is_enterprise() else None,
+ )
+
def get_agent_nowait(
self,
channel_id: str = "",
@@ -1779,16 +2055,9 @@ class AgentManager:
if isinstance(req_method_value, str) and req_method_value in _DISK_ONLY_EVOLUTION_METHODS:
return await self._process_disk_only_evolution(request)
- channel_id = getattr(request, "channel_id", "")
- mode, sub_mode, project_dir = self._agent_lookup_from_request(request)
-
- agent = await self.get_agent(
- channel_id=channel_id,
- mode=mode,
- project_dir=project_dir,
- sub_mode=sub_mode,
- )
+ agent = await self._get_agent_for_request(request)
if agent is None:
+ channel_id = _cron_agent_channel_for_request(request)
raise RuntimeError(f"[AgentManager] No agent available for channel {channel_id}")
return await agent.process_message(request)
@@ -1807,16 +2076,9 @@ class AgentManager:
"""
try:
await self.wait_for_session_prewarm(getattr(request, "session_id", None))
- channel_id = getattr(request, "channel_id", "")
- mode, sub_mode, project_dir = self._agent_lookup_from_request(request)
-
- agent = await self.get_agent(
- channel_id=channel_id,
- mode=mode,
- project_dir=project_dir,
- sub_mode=sub_mode,
- )
+ agent = await self._get_agent_for_request(request)
if agent is None:
+ channel_id = _cron_agent_channel_for_request(request)
raise RuntimeError(f"[AgentManager] No agent available for channel {channel_id}")
# 流式处理
diff --git a/jiuwenswarm/server/runtime/tenant_agent_pool.py b/jiuwenswarm/server/runtime/tenant_agent_pool.py
index 7e8dcbf386..6b0fb617d9 100644
--- a/jiuwenswarm/server/runtime/tenant_agent_pool.py
+++ b/jiuwenswarm/server/runtime/tenant_agent_pool.py
@@ -1031,11 +1031,163 @@ class TenantAgentPool:
cache_key,
)
+ def find_agent_for_session_nowait(self, session_id: str) -> Any | None:
+ """Scan every cached tenant manager for the agent that owns ``session_id``."""
+ sid = str(session_id or "").strip()
+ if not sid:
+ return None
+ for manager in self.iter_agent_managers_nowait():
+ find = getattr(manager, "find_agent_for_session_nowait", None)
+ if not callable(find):
+ continue
+ try:
+ agent = find(sid)
+ except Exception:
+ logger.exception(
+ "[TenantAgentPool] session owner scan failed session_id=%s",
+ sid,
+ )
+ continue
+ if agent is not None:
+ return agent
+ return None
+
+ def find_agent_for_interrupt_resume_nowait(self, session_id: str) -> Any | None:
+ """Cross-tenant: the agent that still holds this pause, not any old owner."""
+ sid = str(session_id or "").strip()
+ if not sid:
+ return None
+ best: Any = None
+ best_rank: tuple[int, float] | None = None
+ for manager in self.iter_agent_managers_nowait():
+ scan = getattr(manager, "iter_interrupt_resume_candidates_nowait", None)
+ if not callable(scan):
+ continue
+ try:
+ candidates = scan(sid)
+ except Exception:
+ logger.exception(
+ "[TenantAgentPool] interrupt resume scan failed session_id=%s",
+ sid,
+ )
+ continue
+ for rank, agent in candidates:
+ if best_rank is None or rank > best_rank:
+ best_rank = rank
+ best = agent
+ return best
+
+ @staticmethod
+ def _is_cron_session_request(request: AgentRequest) -> bool:
+ """Whether this request targets a cron_* execution session."""
+ return str(getattr(request, "session_id", "") or "").strip().startswith("cron_")
+
+ _INTERRUPT_RESUME_SOURCES = frozenset(
+ {"permission_interrupt", "confirm_interrupt", "ask_user_interrupt"}
+ )
+
+ @staticmethod
+ def _is_interrupt_resume_request(request: AgentRequest) -> bool:
+ """HITL / permission resume — not a plain follow-up chat.send."""
+ params = request.params if isinstance(getattr(request, "params", None), dict) else {}
+ source = str(params.get("source") or "").strip()
+ if source not in TenantAgentPool._INTERRUPT_RESUME_SOURCES:
+ return False
+ if not isinstance(params.get("answers"), list):
+ return False
+ return bool(str(params.get("request_id") or "").strip())
+
+ @staticmethod
+ def _is_cron_permission_resume(request: AgentRequest) -> bool:
+ """Legacy helper: cron_* + permission_interrupt (prefer interrupt-resume)."""
+ params = request.params if isinstance(getattr(request, "params", None), dict) else {}
+ return (
+ TenantAgentPool._is_cron_session_request(request)
+ and str(params.get("source") or "") == "permission_interrupt"
+ )
+
+ @staticmethod
+ async def _cron_resume_session_allowed(request: AgentRequest, session_id: str) -> bool:
+ """Cross-tenant cron_* reuse must still pass session ownership (fail-closed)."""
+ try:
+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage
+ except Exception: # noqa: BLE001
+ return False
+ if not is_remote_storage():
+ return True
+ sid = str(session_id or "").strip()
+ if not sid:
+ return False
+ uid = str(getattr(request, "user_id", None) or "").strip() or "guest"
+ params = request.params if isinstance(getattr(request, "params", None), dict) else {}
+ meta = getattr(request, "metadata", None)
+ meta_dict = meta if isinstance(meta, dict) else {}
+ group_id = (
+ str(meta_dict.get("group_id") or params.get("group_id") or "").strip() or None
+ )
+ bot_id = str(meta_dict.get("bot_id") or params.get("bot_id") or "").strip() or None
+ try:
+ from jiuwenswarm.channels.web.history_store.api import get_session_detail_sync
+
+ detail = await asyncio.to_thread(
+ get_session_detail_sync,
+ sid,
+ user=uid,
+ group_id=group_id,
+ bot_id=bot_id,
+ )
+ except Exception: # noqa: BLE001
+ logger.exception(
+ "[TenantAgentPool] cron session ownership check failed session_id=%s",
+ sid,
+ )
+ return False
+ return detail is not None
+
+ _CRON_RESUME_FORBIDDEN_TEXT = (
+ "无权操作该定时任务会话,或会话不属于当前用户。"
+ )
+
async def process_message(self, request: AgentRequest) -> AgentResponse:
"""处理非流式请求."""
guard = self.require_officeclaw_agent(request)
if guard is not None:
return guard
+ # Scheme A: 仅审批/HITL 续跑跨租户找回挂着 interrupt 的 Agent;
+ # 普通 cron_* 续聊走本租户 web channel,不强制绑回 __cron__。
+ if self._is_interrupt_resume_request(request):
+ sid = str(request.session_id or "")
+ owned = self.find_agent_for_interrupt_resume_nowait(sid)
+ if owned is not None:
+ if self._is_cron_session_request(request) and (
+ not await self._cron_resume_session_allowed(request, sid)
+ ):
+ logger.warning(
+ "[TenantAgentPool] interrupt resume denied by ownership: "
+ "session_id=%s user_id=%s",
+ sid,
+ getattr(request, "user_id", None),
+ )
+ return AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={
+ "event_type": "chat.error",
+ "error": self._CRON_RESUME_FORBIDDEN_TEXT,
+ "code": "FORBIDDEN",
+ },
+ metadata=getattr(request, "metadata", None),
+ )
+ logger.info(
+ "[TenantAgentPool] interrupt resume reuse cross-tenant owner: "
+ "session_id=%s source=%s",
+ request.session_id,
+ (request.params or {}).get("source")
+ if isinstance(request.params, dict)
+ else None,
+ )
+ return await owned.process_message(request)
agent_id, service_id, workspace_key = self.extract_ids(request)
agent_id, service_id = self.resolve_control_rpc_tenant(request, agent_id, service_id)
cache_key = self._build_cache_key(agent_id, service_id, workspace_key)
@@ -1138,6 +1290,49 @@ class TenantAgentPool:
is_complete=True,
)
return
+ # Scheme A: 审批/HITL 才跨租户找回挂 pause 的实例;普通续聊走本租户。
+ # 找回后仍须校验会话归属,防止仅凭 session_id 操作他人任务。
+ if self._is_interrupt_resume_request(request):
+ sid = str(request.session_id or "")
+ owned = self.find_agent_for_interrupt_resume_nowait(sid)
+ if owned is not None:
+ if self._is_cron_session_request(request) and (
+ not await self._cron_resume_session_allowed(request, sid)
+ ):
+ logger.warning(
+ "[TenantAgentPool] interrupt resume denied by ownership: "
+ "session_id=%s user_id=%s",
+ sid,
+ getattr(request, "user_id", None),
+ )
+ yield AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload={
+ "event_type": "chat.error",
+ "error": self._CRON_RESUME_FORBIDDEN_TEXT,
+ "code": "FORBIDDEN",
+ },
+ is_complete=True,
+ )
+ return
+ logger.info(
+ "[TenantAgentPool] interrupt resume reuse cross-tenant owner: "
+ "session_id=%s source=%s",
+ request.session_id,
+ (request.params or {}).get("source")
+ if isinstance(request.params, dict)
+ else None,
+ )
+ async for chunk in owned.process_message_stream(request):
+ yield chunk
+ return
+ if self._is_cron_session_request(request):
+ logger.warning(
+ "[TenantAgentPool] interrupt resume has no cross-tenant owner: "
+ "session_id=%s",
+ request.session_id,
+ )
agent_id, service_id, workspace_key = self.extract_ids(request)
agent_id, service_id = self.resolve_control_rpc_tenant(request, agent_id, service_id)
cache_key = self._build_cache_key(agent_id, service_id, workspace_key)
diff --git a/tests/conftest.py b/tests/conftest.py
index 5f3dba8f19..2148f13abe 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -8,7 +8,7 @@ import tempfile
import warnings
from importlib import import_module, invalidate_caches
from pathlib import Path
-from types import ModuleType
+from types import ModuleType, SimpleNamespace
from typing import Generator
import pytest
@@ -171,8 +171,32 @@ def _install_missing_extensions_observability_stub() -> None:
return bool(core_obs.is_initialized())
+ def _force_flush_provider(timeout_millis: int = 5000) -> None:
+ return None
+
+ def _get_config():
+ return None
+
+ def _get_observability_runtime():
+ return SimpleNamespace(
+ get_config=lambda: None,
+ is_initialized=lambda: False,
+ get_tracer=lambda name: None,
+ )
+
+ def _init_observability(*args, **kwargs):
+ return None
+
+ def _shutdown_observability(*args, **kwargs):
+ return None
+
setup.get_tracer = _get_tracer
setup.is_initialized = _is_initialized
+ setup.force_flush_provider = _force_flush_provider
+ setup.get_config = _get_config
+ setup.get_observability_runtime = _get_observability_runtime
+ setup.init_observability = _init_observability
+ setup.shutdown_observability = _shutdown_observability
semconv = _ensure_module("openjiuwen.extensions.observability.semconv")
semconv.LANGFUSE_SESSION_ID = "langfuse.session.id"
diff --git a/tests/unit_tests/agentserver/test_cron_ctx_review_fixes.py b/tests/unit_tests/agentserver/test_cron_ctx_review_fixes.py
new file mode 100644
index 0000000000..84b8d20279
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_cron_ctx_review_fixes.py
@@ -0,0 +1,98 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""PR review fixes: cron_* 普通续聊恢复 + 审批 pin 清理。"""
+
+from __future__ import annotations
+
+import sys
+from types import ModuleType, SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+# interface_deep 会拉 image_tools → google.genai;本地/精简环境可能未装,先 stub。
+_genai = ModuleType("google.genai")
+_genai.types = ModuleType("google.genai.types")
+_google = sys.modules.get("google") or ModuleType("google")
+_google.genai = _genai
+sys.modules["google"] = _google
+sys.modules["google.genai"] = _genai
+sys.modules["google.genai.types"] = _genai.types
+
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import ( # noqa: E402
+ JiuWenSwarmDeepAdapter,
+)
+
+
+def _bare_adapter() -> JiuWenSwarmDeepAdapter:
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ adapter._is_session_scoped_adapter = False
+ adapter._session_parent_adapter = None
+ adapter._sessions_awaiting_tool_permission = set()
+ adapter._session_adapter_last_used = {}
+ adapter._instance = None
+ return adapter
+
+
+async def test_block_stale_does_not_skip_plain_cron_recover(monkeypatch):
+ """无 source 的 cron_* 请求也应触发空上下文恢复。"""
+ adapter = _bare_adapter()
+ recovered: list[tuple[str, str]] = []
+
+ async def _fake_block(request):
+ return False
+
+ async def _fake_recover(session_id, request_id, *, reload_interrupt=False):
+ recovered.append((session_id, request_id))
+
+ monkeypatch.setattr(adapter, "_block_stale_cron_permission_resume", _fake_block)
+ monkeypatch.setattr(adapter, "_recover_cron_session_context", _fake_recover)
+
+ request = SimpleNamespace(
+ session_id="cron_job_1",
+ request_id="req-plain",
+ channel_id="web",
+ params={"query": "总结一下"},
+ metadata={},
+ )
+ # 直接复现入口分支:block 未拦时,普通 cron_* 仍 recover。
+ if await adapter._block_stale_cron_permission_resume(request):
+ pytest.fail("plain cron chat must not be blocked")
+ elif str(request.session_id).startswith("cron_"):
+ await adapter._recover_cron_session_context(
+ request.session_id, str(request.request_id or ""),
+ )
+
+ assert recovered == [("cron_job_1", "req-plain")]
+
+
+def test_clear_cron_awaiting_when_interrupt_gone():
+ adapter = _bare_adapter()
+ sid = "cron_done_1"
+ adapter.mark_session_awaiting_tool_permission(sid)
+ assert sid in adapter._sessions_awaiting_tool_permission
+
+ adapter._read_session_interrupt_state = MagicMock(return_value=None)
+ adapter._clear_cron_awaiting_if_interrupt_gone(sid)
+ assert sid not in adapter._sessions_awaiting_tool_permission
+
+
+def test_clear_cron_awaiting_keeps_pin_while_interrupt_live():
+ adapter = _bare_adapter()
+ sid = "cron_live_1"
+ adapter.mark_session_awaiting_tool_permission(sid)
+ adapter._read_session_interrupt_state = MagicMock(return_value={"paused": True})
+
+ adapter._clear_cron_awaiting_if_interrupt_gone(sid)
+ assert sid in adapter._sessions_awaiting_tool_permission
+
+
+def test_clear_cron_awaiting_ignores_non_cron_session():
+ adapter = _bare_adapter()
+ sid = "web_session"
+ adapter._sessions_awaiting_tool_permission.add(sid)
+ adapter._read_session_interrupt_state = MagicMock(return_value=None)
+
+ adapter._clear_cron_awaiting_if_interrupt_gone(sid)
+ assert sid in adapter._sessions_awaiting_tool_permission
diff --git a/tests/unit_tests/agentserver/test_cron_session_routing.py b/tests/unit_tests/agentserver/test_cron_session_routing.py
new file mode 100644
index 0000000000..dc298bfc62
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_cron_session_routing.py
@@ -0,0 +1,414 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Scheme A: plain cron_* follow-up on web; interrupt resume finds session owner."""
+
+# pylint: disable=protected-access
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from jiuwenswarm.common.schema.agent import AgentRequest
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
+from jiuwenswarm.server.context import AgentServerServices, RequestContext
+from jiuwenswarm.server.handlers import _default
+from jiuwenswarm.server.runtime import agent_manager as am
+from jiuwenswarm.server.runtime.agent_manager import AgentManager
+from jiuwenswarm.server.runtime.tenant_agent_pool import TenantAgentPool
+from jiuwenswarm.server.transports.sink import WSSink
+
+
+def _default_ctx(server, request):
+ import asyncio as _asyncio
+
+ class _NullWs:
+ async def send(self, text): # noqa: ANN001
+ return None
+
+ _ws = _NullWs()
+ return RequestContext(
+ request=request,
+ sink=WSSink(_ws, _asyncio.Lock()),
+ connection_id=str(id(_ws)),
+ services=AgentServerServices(server),
+ )
+
+
+def test_cron_agent_channel_helpers_cover_followup_and_resume() -> None:
+ followup = SimpleNamespace(
+ session_id="cron_abc",
+ channel_id="web",
+ params={"query": "1"},
+ )
+ resume = SimpleNamespace(
+ session_id="cron_abc",
+ channel_id="web",
+ params={
+ "source": "permission_interrupt",
+ "answers": [{"option_id": "allow"}],
+ "request_id": "perm-1",
+ },
+ )
+ normal = SimpleNamespace(
+ session_id="sess_web",
+ channel_id="web",
+ params={"query": "hi"},
+ )
+
+ assert am._is_cron_session_request(followup) is True
+ assert am._is_cron_permission_resume(followup) is False
+ assert am._is_interrupt_resume_request(followup) is False
+ # Plain follow-up stays on request channel (web), not forced to __cron__.
+ assert am._cron_agent_channel_for_request(followup) == "web"
+ assert am._cron_permission_resume_channel(followup) == "web"
+
+ assert am._is_interrupt_resume_request(resume) is True
+ assert am._is_cron_permission_resume(resume) is True
+ assert am._cron_agent_channel_for_request(resume) == "__cron__"
+
+ assert am._is_cron_session_request(normal) is False
+ assert am._cron_agent_channel_for_request(normal) == "web"
+
+
+async def test_agent_manager_plain_cron_followup_uses_request_channel() -> None:
+ """Plain cron_* follow-up must get_agent(web), not reuse __cron__ owner."""
+ owned = MagicMock(name="owned_cron")
+ owned._jiuwenswarm_agent_channel_id = "__cron__"
+ web_agent = MagicMock(name="web_agent")
+ manager = AgentManager.__new__(AgentManager)
+ manager.get_agent_for_session_nowait = MagicMock(return_value=owned)
+ manager.find_agent_for_session_nowait = MagicMock(return_value=owned)
+ manager.get_agent = AsyncMock(return_value=web_agent)
+ manager._agent_lookup_from_request = MagicMock(return_value=("agent", None, None))
+
+ request = SimpleNamespace(
+ session_id="cron_job_x",
+ channel_id="web",
+ params={"query": "1"},
+ )
+ selected = await manager._get_agent_for_request(request)
+ assert selected is web_agent
+ manager.find_agent_for_session_nowait.assert_not_called()
+ manager.get_agent.assert_awaited_once_with(
+ channel_id="web",
+ mode="agent",
+ project_dir=None,
+ sub_mode=None,
+ request=None,
+ )
+
+
+async def test_agent_manager_interrupt_resume_reuses_owner() -> None:
+ owned = MagicMock(name="owned_cron")
+ owned._jiuwenswarm_agent_channel_id = "__cron__"
+ manager = AgentManager.__new__(AgentManager)
+ manager.get_agent_for_session_nowait = MagicMock(return_value=None)
+ manager.find_agent_for_session_nowait = MagicMock(return_value=None)
+ manager.find_agent_for_interrupt_resume_nowait = MagicMock(return_value=owned)
+ manager.get_agent = AsyncMock(return_value=MagicMock())
+ manager._agent_lookup_from_request = MagicMock(return_value=("agent", None, None))
+
+ request = SimpleNamespace(
+ session_id="cron_job_x",
+ channel_id="web",
+ params={
+ "source": "permission_interrupt",
+ "answers": [{"option_id": "allow"}],
+ "request_id": "perm-1",
+ },
+ )
+ selected = await manager._get_agent_for_request(request)
+ assert selected is owned
+ manager.get_agent.assert_not_awaited()
+
+
+async def test_cron_followup_routes_to_web_channel_agent() -> None:
+ """Plain cron_* follow-up uses request channel (web), not __cron__."""
+ web_agent = MagicMock(name="web_agent")
+ manager = MagicMock()
+ manager.get_agent = AsyncMock(return_value=web_agent)
+ manager.wait_for_session_prewarm = AsyncMock()
+ manager.get_agent_for_session_nowait = MagicMock(return_value=MagicMock())
+ manager.find_agent_for_session_nowait = MagicMock(return_value=MagicMock())
+ manager.find_agent_for_interrupt_resume_nowait = MagicMock(return_value=None)
+
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ server._agent_manager = manager
+ request = AgentRequest(
+ request_id="cron-followup",
+ channel_id="web",
+ session_id="cron_job1_run2",
+ req_method=ReqMethod.CHAT_SEND,
+ params={"query": "1"},
+ )
+
+ with patch(
+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",
+ return_value={"mode": "agent", "work_mode": "work"},
+ ), patch.object(
+ _default,
+ "_sync_chat_request_metadata",
+ return_value=None,
+ ):
+ mode, _sub_mode, selected = await _default._prepare_code_mode_chat_turn(
+ _default_ctx(server, request),
+ request,
+ "web",
+ agent_manager=manager,
+ )
+
+ assert selected is web_agent
+ assert mode == "agent"
+ manager.find_agent_for_session_nowait.assert_not_called()
+ manager.get_agent.assert_awaited_once_with(
+ channel_id="web",
+ mode="agent",
+ project_dir=None,
+ sub_mode=None,
+ )
+
+
+async def test_cron_interrupt_resume_reuses_session_owner() -> None:
+ owned = MagicMock(name="cron_owner")
+ manager = MagicMock()
+ manager.get_agent = AsyncMock(return_value=MagicMock())
+ manager.wait_for_session_prewarm = AsyncMock()
+ manager.get_agent_for_session_nowait = MagicMock(return_value=None)
+ manager.find_agent_for_session_nowait = MagicMock(return_value=None)
+ manager.find_agent_for_interrupt_resume_nowait = MagicMock(return_value=owned)
+
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ server._agent_manager = manager
+ request = AgentRequest(
+ request_id="cron-resume",
+ channel_id="web",
+ session_id="cron_job1_run2",
+ req_method=ReqMethod.CHAT_SEND,
+ params={
+ "source": "permission_interrupt",
+ "answers": [{"option_id": "allow"}],
+ "request_id": "perm-1",
+ },
+ )
+
+ with patch(
+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",
+ return_value={"mode": "agent", "work_mode": "work"},
+ ), patch.object(
+ _default,
+ "_sync_chat_request_metadata",
+ return_value=None,
+ ):
+ _mode, _sub, selected = await _default._prepare_code_mode_chat_turn(
+ _default_ctx(server, request),
+ request,
+ "web",
+ agent_manager=manager,
+ )
+
+ assert selected is owned
+ manager.find_agent_for_interrupt_resume_nowait.assert_called_once_with("cron_job1_run2")
+ manager.find_agent_for_session_nowait.assert_not_called()
+ manager.get_agent.assert_not_awaited()
+
+
+async def test_cron_interrupt_resume_falls_back_to_get_agent_cron_channel() -> None:
+ """When no live owner, cron_* interrupt resume falls back to get_agent(__cron__)."""
+ agent = MagicMock(name="cron_agent")
+ manager = MagicMock()
+ manager.get_agent = AsyncMock(return_value=agent)
+ manager.wait_for_session_prewarm = AsyncMock()
+ manager.get_agent_for_session_nowait = MagicMock(return_value=None)
+ manager.find_agent_for_session_nowait = MagicMock(return_value=None)
+ manager.find_agent_for_interrupt_resume_nowait = MagicMock(return_value=None)
+
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ server._agent_manager = manager
+ request = AgentRequest(
+ request_id="cron-resume-fallback",
+ channel_id="web",
+ session_id="cron_job1_run3",
+ req_method=ReqMethod.CHAT_SEND,
+ params={
+ "source": "permission_interrupt",
+ "answers": [{"option_id": "allow"}],
+ "request_id": "perm-2",
+ },
+ )
+
+ with patch(
+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",
+ return_value={"mode": "agent", "work_mode": "work"},
+ ), patch.object(
+ _default,
+ "_sync_chat_request_metadata",
+ return_value=None,
+ ):
+ _mode, _sub, selected = await _default._prepare_code_mode_chat_turn(
+ _default_ctx(server, request),
+ request,
+ "web",
+ agent_manager=manager,
+ )
+
+ assert selected is agent
+ manager.get_agent.assert_awaited_once_with(
+ channel_id="__cron__",
+ mode="agent",
+ project_dir=None,
+ sub_mode=None,
+ )
+
+
+async def test_tenant_pool_plain_cron_followup_does_not_cross_tenant_reuse() -> None:
+ owned = MagicMock()
+ owned.process_message_stream = MagicMock(
+ return_value=_async_chunks(
+ [
+ SimpleNamespace(
+ request_id="r1",
+ channel_id="web",
+ payload={"event_type": "chat.delta", "content": "ok"},
+ is_complete=True,
+ )
+ ]
+ )
+ )
+ pool = TenantAgentPool.__new__(TenantAgentPool)
+ pool.require_officeclaw_agent = MagicMock(return_value=None)
+ pool.find_agent_for_session_nowait = MagicMock(return_value=owned)
+ pool._cron_resume_session_allowed = AsyncMock(return_value=True)
+ manager = MagicMock()
+ manager.process_message_stream = MagicMock(
+ return_value=_async_chunks(
+ [
+ SimpleNamespace(
+ request_id="r1",
+ channel_id="web",
+ payload={"event_type": "chat.delta", "content": "web-ok"},
+ is_complete=True,
+ )
+ ]
+ )
+ )
+ pool._ensure_agent_manager = AsyncMock(return_value=manager)
+ pool._refresh_agent_manager_cache = AsyncMock()
+ pool.extract_ids = MagicMock(return_value=("a", "s", "w"))
+ pool.resolve_control_rpc_tenant = MagicMock(return_value=("a", "s"))
+ pool._build_cache_key = MagicMock(return_value="cache")
+
+ request = AgentRequest(
+ request_id="r1",
+ channel_id="web",
+ session_id="cron_tenant_1",
+ req_method=ReqMethod.CHAT_SEND,
+ params={"query": "1"},
+ )
+ chunks = [
+ chunk async for chunk in TenantAgentPool.process_message_stream(pool, request)
+ ]
+ assert len(chunks) == 1
+ assert chunks[0].payload["content"] == "web-ok"
+ pool.find_agent_for_session_nowait.assert_not_called()
+ owned.process_message_stream.assert_not_called()
+ pool._ensure_agent_manager.assert_awaited()
+
+
+async def test_tenant_pool_reuses_owner_for_interrupt_resume_stream() -> None:
+ owned = MagicMock()
+ owned.process_message_stream = MagicMock(
+ return_value=_async_chunks(
+ [
+ SimpleNamespace(
+ request_id="r1",
+ channel_id="web",
+ payload={"event_type": "chat.delta", "content": "ok"},
+ is_complete=True,
+ )
+ ]
+ )
+ )
+ pool = TenantAgentPool.__new__(TenantAgentPool)
+ pool.require_officeclaw_agent = MagicMock(return_value=None)
+ pool.find_agent_for_session_nowait = MagicMock(return_value=owned)
+ pool.find_agent_for_interrupt_resume_nowait = MagicMock(return_value=owned)
+ pool._cron_resume_session_allowed = AsyncMock(return_value=True)
+ pool._ensure_agent_manager = AsyncMock()
+
+ request = AgentRequest(
+ request_id="r1",
+ channel_id="web",
+ session_id="cron_tenant_1",
+ req_method=ReqMethod.CHAT_SEND,
+ params={
+ "source": "permission_interrupt",
+ "answers": [{"option_id": "allow"}],
+ "request_id": "perm-1",
+ },
+ )
+ chunks = [
+ chunk async for chunk in TenantAgentPool.process_message_stream(pool, request)
+ ]
+ assert len(chunks) == 1
+ pool._ensure_agent_manager.assert_not_awaited()
+ owned.process_message_stream.assert_called_once_with(request)
+
+
+def _agent_holding(session_id: str, *, live: bool, awaiting: bool, last_used: float):
+ adapter = MagicMock()
+ adapter._is_session_scoped_adapter = False
+ adapter._sessions_awaiting_tool_permission = {session_id} if awaiting or live else set()
+ adapter._session_adapter_last_used = {session_id: last_used}
+ adapter._session_adapters = {}
+ adapter._instance = SimpleNamespace(
+ _interaction_session=SimpleNamespace(session_id=session_id),
+ _loop_session=None,
+ )
+ adapter._read_session_interrupt_state = MagicMock(
+ return_value={"paused": True} if live else None
+ )
+ agent = MagicMock()
+ agent._adapter = adapter
+ return agent
+
+
+def test_interrupt_resume_prefers_live_web_pause_over_stale_cron_owner() -> None:
+ """Follow-up approval must hit the agent that still has the paused tool."""
+ cron_agent = _agent_holding("cron_job", live=False, awaiting=True, last_used=1.0)
+ web_agent = _agent_holding("cron_job", live=True, awaiting=True, last_used=10.0)
+ manager = AgentManager.__new__(AgentManager)
+ manager.agents = {
+ "__cron__": {"cron": cron_agent},
+ "web": {"web": web_agent},
+ }
+ selected = manager.find_agent_for_interrupt_resume_nowait("cron_job")
+ assert selected is web_agent
+
+
+def test_interrupt_resume_keeps_live_cron_pause() -> None:
+ """First-run cron approval still returns to __cron__ when that pause is live."""
+ cron_agent = _agent_holding("cron_job", live=True, awaiting=True, last_used=1.0)
+ web_agent = _agent_holding("cron_job", live=False, awaiting=False, last_used=9.0)
+ manager = AgentManager.__new__(AgentManager)
+ manager.agents = {
+ "__cron__": {"cron": cron_agent},
+ "web": {"web": web_agent},
+ }
+ selected = manager.find_agent_for_interrupt_resume_nowait("cron_job")
+ assert selected is cron_agent
+
+
+async def _async_chunks(items):
+ for item in items:
+ yield item
diff --git a/tests/unit_tests/agentserver/test_deep_adapter_session_teardown.py b/tests/unit_tests/agentserver/test_deep_adapter_session_teardown.py
index 28a8916a66..e7c9f0cdaf 100644
--- a/tests/unit_tests/agentserver/test_deep_adapter_session_teardown.py
+++ b/tests/unit_tests/agentserver/test_deep_adapter_session_teardown.py
@@ -15,6 +15,7 @@ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
def _make_adapter(**state: object) -> JiuWenSwarmDeepAdapter:
"""Create a bare adapter with internal state set via setattr."""
adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ state.setdefault("_sessions_awaiting_tool_permission", set())
for name, value in state.items():
setattr(adapter, name, value)
return adapter
diff --git a/tests/unit_tests/agentserver/test_deepresearch_rewrite_fast_path_adapter.py b/tests/unit_tests/agentserver/test_deepresearch_rewrite_fast_path_adapter.py
index 32988f906c..7c2bcce720 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_rewrite_fast_path_adapter.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_rewrite_fast_path_adapter.py
@@ -1455,6 +1455,7 @@ async def test_parent_evicts_uncertain_child_without_waiting_for_idle_ttl():
parent._session_adapter_last_used = {"session-1": interface_module.time.time()}
parent._session_adapter_versions = {"session-1": 0}
parent._session_adapter_reload_failures = {}
+ parent._sessions_awaiting_tool_permission = set()
await parent._evict_idle_session_adapters()
diff --git a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py
index 315d1d26c3..61665a48b6 100644
--- a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py
+++ b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py
@@ -587,6 +587,7 @@ async def test_tenant_interrupt_continuation_restores_code_route_before_defaults
manager = MagicMock()
manager.get_agent = AsyncMock(return_value=agent)
manager.wait_for_session_prewarm = AsyncMock()
+ manager.find_agent_for_interrupt_resume_nowait = MagicMock(return_value=None)
server = AgentWebSocketServer.__new__(AgentWebSocketServer)
server._agent_manager = manager
request = AgentRequest(
diff --git a/tests/unit_tests/agentserver/test_subagent_runtime_acceptance.py b/tests/unit_tests/agentserver/test_subagent_runtime_acceptance.py
index 50278e3bc5..2abb524409 100644
--- a/tests/unit_tests/agentserver/test_subagent_runtime_acceptance.py
+++ b/tests/unit_tests/agentserver/test_subagent_runtime_acceptance.py
@@ -35,6 +35,7 @@ from jiuwenswarm.server.runtime.session import session_history
def _make_adapter(**state: object) -> JiuWenSwarmDeepAdapter:
adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ state.setdefault("_sessions_awaiting_tool_permission", set())
for name, value in state.items():
setattr(adapter, name, value)
return adapter
diff --git a/tests/unit_tests/gateway/test_cron_live_bus.py b/tests/unit_tests/gateway/test_cron_live_bus.py
new file mode 100644
index 0000000000..f82f35e631
--- /dev/null
+++ b/tests/unit_tests/gateway/test_cron_live_bus.py
@@ -0,0 +1,322 @@
+"""Cron live bus: local replay + Redis cross-pod fanout."""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from typing import Any
+
+import pytest
+
+from jiuwenswarm.gateway.cron import live_bus as live_bus_module
+from jiuwenswarm.gateway.cron.live_bus import CronLiveBus
+
+
+def test_late_subscribe_replays_buffered_frames():
+ bus = CronLiveBus(replay_size=8, replay_ttl_seconds=60.0)
+ sid = "cron_late_join_1"
+
+ bus.publish(sid, {"event": "chat.reasoning", "payload": {"content": "先想一下"}})
+ bus.publish(sid, {"event": "chat.ask_user_question", "payload": {"request_id": "ask-1"}})
+
+ queue = bus.subscribe(sid)
+ events = []
+ while not queue.empty():
+ events.append(queue.get_nowait()["event"])
+
+ assert events == ["chat.reasoning", "chat.ask_user_question"]
+
+ bus.publish(sid, {"event": "chat.delta", "payload": {"content": "继续"}})
+ assert queue.get_nowait()["event"] == "chat.delta"
+ bus.unsubscribe(sid, queue)
+
+
+def test_replay_buffer_caps_size():
+ bus = CronLiveBus(replay_size=3, replay_ttl_seconds=60.0)
+ sid = "cron_cap_1"
+ for i in range(5):
+ bus.publish(sid, {"event": "chat.delta", "payload": {"content": str(i)}})
+
+ queue = bus.subscribe(sid)
+ contents = []
+ while not queue.empty():
+ contents.append(queue.get_nowait()["payload"]["content"])
+ assert contents == ["2", "3", "4"]
+ bus.unsubscribe(sid, queue)
+
+
+def test_replay_expires_after_ttl_without_subscribers():
+ bus = CronLiveBus(replay_size=8, replay_ttl_seconds=0.05)
+ sid = "cron_ttl_1"
+ bus.publish(sid, {"event": "chat.reasoning", "payload": {"content": "x"}})
+ queue = bus.subscribe(sid)
+ bus.unsubscribe(sid, queue)
+ time.sleep(0.2)
+ late = bus.subscribe(sid)
+ assert late.empty()
+ bus.unsubscribe(sid, late)
+
+
+def test_origin_unique_even_when_gateway_instance_id_shared(monkeypatch):
+ """Deploy sets the same GATEWAY_INSTANCE_ID on every replica; origins must still differ."""
+ monkeypatch.setenv("POD_IP", "10.0.0.1")
+ monkeypatch.setattr(
+ "jiuwenswarm.extensions.redis.redis_runtime.get_gateway_instance_id",
+ lambda: "jiuwenclaw-gateway-hjh",
+ raising=False,
+ )
+ a = live_bus_module._gateway_origin_id()
+ monkeypatch.setenv("POD_IP", "10.0.0.2")
+ b = live_bus_module._gateway_origin_id()
+ assert a != b
+ assert a.startswith("jiuwenclaw-gateway-hjh:")
+ assert b.startswith("jiuwenclaw-gateway-hjh:")
+
+
+def test_processing_status_true_false_fingerprints_differ_with_large_cron_meta():
+ """Large cron blobs must not make true/false processing_status collide after truncate."""
+ cron_meta = {
+ "job_id": "j" * 80,
+ "job_name": "n" * 80,
+ "run_id": "r" * 80,
+ "push_at": "2026-01-01T00:00:00+00:00",
+ "wake_at": "2026-01-01T00:00:00+00:00",
+ "exec_channel_id": "__cron__",
+ "exec_session_id": "cron_abc",
+ "is_placeholder": False,
+ "status": "running",
+ }
+ true_frame = {
+ "event": "chat.processing_status",
+ "payload": {
+ "event_type": "chat.processing_status",
+ "is_processing": True,
+ "request_id": "cron-1",
+ "cron": cron_meta,
+ },
+ }
+ false_frame = {
+ "event": "chat.processing_status",
+ "payload": {
+ "event_type": "chat.processing_status",
+ "is_processing": False,
+ "request_id": "cron-1",
+ "cron": cron_meta,
+ },
+ }
+ assert live_bus_module._frame_fingerprint(true_frame) != live_bus_module._frame_fingerprint(
+ false_frame
+ )
+
+
+def test_identical_delta_content_different_live_seq_fingerprints_differ():
+ """Repeated LLM tokens (「的」「,」) must not collide after content-only fingerprinting."""
+ first = {
+ "event": "chat.delta",
+ "payload": {"content": "的", "live_seq": 10, "request_id": "r1"},
+ }
+ second = {
+ "event": "chat.delta",
+ "payload": {"content": "的", "live_seq": 11, "request_id": "r1"},
+ }
+ assert live_bus_module._frame_fingerprint(first) != live_bus_module._frame_fingerprint(second)
+
+
+def test_repeated_identical_deltas_both_reach_subscriber():
+ bus = CronLiveBus(replay_size=8, replay_ttl_seconds=60.0, queue_size=8)
+ sid = "cron_repeat_delta"
+ queue = bus.subscribe(sid)
+ bus.publish(
+ sid,
+ {"event": "chat.delta", "payload": {"content": "的", "live_seq": 1}},
+ )
+ bus.publish(
+ sid,
+ {"event": "chat.delta", "payload": {"content": "的", "live_seq": 2}},
+ )
+ assert queue.qsize() == 2
+ assert queue.get_nowait()["payload"]["live_seq"] == 1
+ assert queue.get_nowait()["payload"]["live_seq"] == 2
+ bus.unsubscribe(sid, queue)
+
+
+def test_queue_full_drops_oldest_keeps_newest():
+ bus = CronLiveBus(replay_size=4, replay_ttl_seconds=60.0, queue_size=2)
+ sid = "cron_queue_full"
+ queue = bus.subscribe(sid)
+ # Drain subscribe-time empty replay.
+ while not queue.empty():
+ queue.get_nowait()
+ for i in range(4):
+ bus.publish(
+ sid,
+ {"event": "chat.delta", "payload": {"content": str(i), "live_seq": i + 1}},
+ )
+ # queue_size=2 with drop-oldest → newest two frames remain.
+ assert queue.qsize() == 2
+ assert queue.get_nowait()["payload"]["live_seq"] == 3
+ assert queue.get_nowait()["payload"]["live_seq"] == 4
+ bus.unsubscribe(sid, queue)
+
+
+def test_subscribe_skip_replay_does_not_drain_buffer():
+ bus = CronLiveBus(replay_size=8, replay_ttl_seconds=60.0)
+ sid = "cron_skip_replay_1"
+ bus.publish(
+ sid,
+ {"event": "chat.ask_user_question", "payload": {"request_id": "ask-1", "live_seq": 1}},
+ )
+ bus.publish(
+ sid,
+ {"event": "chat.reasoning", "payload": {"content": "上一轮思考", "live_seq": 2}},
+ )
+ queue = bus.subscribe(sid, replay=False)
+ assert queue.empty()
+ # Buffer itself must remain for a later catch-up subscribe.
+ late = bus.subscribe(sid, replay=True)
+ assert late.qsize() == 2
+ bus.unsubscribe(sid, queue)
+ bus.unsubscribe(sid, late)
+
+
+class _FakeRedis:
+ def __init__(self) -> None:
+ self.lists: dict[str, list[str]] = {}
+ self.channels: dict[str, list[asyncio.Queue[str]]] = {}
+ self.ttls: dict[str, int] = {}
+
+ async def rpush(self, key: str, *values: Any) -> int:
+ bucket = self.lists.setdefault(key, [])
+ bucket.extend(str(v) for v in values)
+ return len(bucket)
+
+ async def ltrim(self, key: str, start: int, stop: int) -> bool:
+ items = self.lists.get(key) or []
+ # Redis LTRIM semantics with negative indexes.
+ n = len(items)
+ if n == 0:
+ return True
+ s = start if start >= 0 else n + start
+ e = stop if stop >= 0 else n + stop
+ s = max(0, s)
+ e = min(n - 1, e)
+ self.lists[key] = items[s : e + 1] if s <= e else []
+ return True
+
+ async def expire(self, key: str, ttl_seconds: int) -> bool:
+ self.ttls[key] = int(ttl_seconds)
+ return True
+
+ async def delete(self, *keys: str) -> int:
+ removed = 0
+ for key in keys:
+ if key in self.lists:
+ del self.lists[key]
+ removed += 1
+ self.ttls.pop(key, None)
+ return removed
+
+ async def lrange(self, key: str, start: int, stop: int) -> list[str]:
+ items = self.lists.get(key) or []
+ n = len(items)
+ if n == 0:
+ return []
+ s = start if start >= 0 else n + start
+ e = stop if stop >= 0 else n + stop
+ if stop == -1:
+ e = n - 1
+ s = max(0, s)
+ e = min(n - 1, e)
+ return items[s : e + 1] if s <= e else []
+
+ async def publish(self, channel: str, message: str) -> int:
+ waiters = list(self.channels.get(channel, ()))
+ for q in waiters:
+ await q.put(message)
+ return len(waiters)
+
+ async def subscribe(self, channel: str):
+ q: asyncio.Queue[str] = asyncio.Queue()
+ self.channels.setdefault(channel, []).append(q)
+ try:
+ while True:
+ yield await q.get()
+ finally:
+ bucket = self.channels.get(channel) or []
+ if q in bucket:
+ bucket.remove(q)
+
+
+async def test_redis_fanout_delivers_to_other_origin(monkeypatch):
+ redis = _FakeRedis()
+ monkeypatch.setattr(live_bus_module, "_redis_client", lambda: redis)
+
+ publisher = CronLiveBus(replay_size=8, replay_ttl_seconds=60.0)
+ publisher._origin = "gw-publisher"
+ subscriber = CronLiveBus(replay_size=8, replay_ttl_seconds=60.0)
+ subscriber._origin = "gw-subscriber"
+
+ sid = "cron_cross_pod_1"
+ queue = subscriber.subscribe(sid)
+ # Let bridge task subscribe to fake redis.
+ await asyncio.sleep(0.05)
+
+ publisher.publish(
+ sid,
+ {"event": "chat.reasoning", "payload": {"content": "跨副本思考"}},
+ )
+ # Redis publish is scheduled as a task.
+ await asyncio.sleep(0.05)
+
+ frame = await asyncio.wait_for(queue.get(), timeout=1.0)
+ assert frame["event"] == "chat.reasoning"
+ assert frame["payload"]["content"] == "跨副本思考"
+ subscriber.unsubscribe(sid, queue)
+
+
+async def test_redis_replay_fills_late_subscriber_on_other_pod(monkeypatch):
+ redis = _FakeRedis()
+ monkeypatch.setattr(live_bus_module, "_redis_client", lambda: redis)
+
+ publisher = CronLiveBus(replay_size=8, replay_ttl_seconds=60.0)
+ publisher._origin = "gw-publisher"
+ publisher.publish(
+ "cron_cross_pod_2",
+ {"event": "chat.ask_user_question", "payload": {"request_id": "ask-9"}},
+ )
+ await asyncio.sleep(0.05)
+ assert any(redis.lists.values())
+
+ late = CronLiveBus(replay_size=8, replay_ttl_seconds=60.0)
+ late._origin = "gw-late"
+ queue = late.subscribe("cron_cross_pod_2")
+ await asyncio.sleep(0.05)
+
+ assert not queue.empty()
+ frame = queue.get_nowait()
+ assert frame["event"] == "chat.ask_user_question"
+ assert frame["payload"]["request_id"] == "ask-9"
+ late.unsubscribe("cron_cross_pod_2", queue)
+
+
+async def test_publisher_skips_redis_echo_to_local_subscribers(monkeypatch):
+ redis = _FakeRedis()
+ monkeypatch.setattr(live_bus_module, "_redis_client", lambda: redis)
+
+ bus = CronLiveBus(replay_size=8, replay_ttl_seconds=60.0)
+ bus._origin = "gw-same"
+ sid = "cron_echo_1"
+ queue = bus.subscribe(sid)
+ await asyncio.sleep(0.05)
+
+ bus.publish(sid, {"event": "chat.delta", "payload": {"content": "once"}})
+ await asyncio.sleep(0.05)
+
+ # Local deliver once; redis echo must not duplicate.
+ assert queue.qsize() == 1
+ assert queue.get_nowait()["payload"]["content"] == "once"
+ assert queue.empty()
+ bus.unsubscribe(sid, queue)
diff --git a/tests/unit_tests/gateway/test_cron_live_mirror_clear.py b/tests/unit_tests/gateway/test_cron_live_mirror_clear.py
new file mode 100644
index 0000000000..2573307bc1
--- /dev/null
+++ b/tests/unit_tests/gateway/test_cron_live_mirror_clear.py
@@ -0,0 +1,54 @@
+"""Resume chat.final mirror publishes to live; hold settle is separate."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+from jiuwenswarm.gateway.cron.live_bus import CronLiveBus
+from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler
+
+
+def test_mirror_cron_final_publishes_without_releasing_hold(monkeypatch):
+ """Contentful final must not release hold / clear replay by itself.
+
+ Multi-tool rounds may emit finals between asks; clearing here would drop
+ the next permission card and free run_now too early.
+ """
+ bus = CronLiveBus(replay_size=8, replay_ttl_seconds=60.0)
+ sid = "cron_mirror_clear_1"
+ bus.publish(
+ sid,
+ {
+ "event": "chat.ask_user_question",
+ "payload": {"request_id": "ask-1", "session_id": sid},
+ },
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.cron.live_bus.cron_live_bus",
+ bus,
+ )
+
+ msg = SimpleNamespace(
+ payload={
+ "event_type": "chat.final",
+ "content": "验证完成",
+ "session_id": sid,
+ },
+ event_type=SimpleNamespace(value="chat.final"),
+ )
+ handler = MagicMock(spec=MessageHandler)
+ handler._cron_registry = None
+ handler._cron_controller = None
+ MessageHandler._mirror_cron_live_stream_chunk(handler, sid, msg)
+
+ handler._release_cron_permission_hold.assert_not_called()
+ queue = bus.subscribe(sid)
+ # Prior ask remains in replay; settle path clears when hold is released.
+ assert not queue.empty()
+ frame = queue.get_nowait()
+ assert frame.get("event") == "chat.ask_user_question"
+ # Mirrored final is also in the buffer after the ask.
+ frame2 = queue.get_nowait()
+ assert frame2.get("event") == "chat.final"
+ bus.unsubscribe(sid, queue)
diff --git a/tests/unit_tests/gateway/test_cron_remote_history.py b/tests/unit_tests/gateway/test_cron_remote_history.py
index d899d915c3..5ba573a8d0 100644
--- a/tests/unit_tests/gateway/test_cron_remote_history.py
+++ b/tests/unit_tests/gateway/test_cron_remote_history.py
@@ -10,10 +10,13 @@ import pytest
from jiuwenswarm.channels.web.history_store import api as history_api
from jiuwenswarm.channels.web.history_store.store import ChatHistoryStore
-from jiuwenswarm.common.schema.agent import AgentResponse
+from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk
from jiuwenswarm.gateway.cron import scheduler as scheduler_module
-from jiuwenswarm.gateway.cron.models import CronJob
-from jiuwenswarm.gateway.cron.scheduler import CronSchedulerService
+from jiuwenswarm.gateway.cron.models import CronJob, CronRunState
+from jiuwenswarm.gateway.cron.scheduler import (
+ CronSchedulerService,
+ _persist_remote_cron_history,
+)
from jiuwenswarm.gateway.cron.store import CronJobStore
@@ -42,6 +45,26 @@ class AgentClient:
payload = {"content": "晴,25℃"} if ok else {"error": "weather request failed"}
return AgentResponse(envelope.request_id, envelope.channel, ok, payload)
+ async def send_request_stream(self, envelope):
+ """Agent 模式 chat.send 已改走流式;结果语义与上面的 unary 桩一致。"""
+ self.requests.append(envelope)
+ if self.outcome == "exception":
+ raise RuntimeError("Agent connection closed")
+ if self.outcome == "cancelled":
+ raise asyncio.CancelledError
+ ok = self.outcome == "success"
+ payload = (
+ {"event_type": "chat.final", "content": "晴,25℃"}
+ if ok
+ else {"event_type": "chat.error", "error": "weather request failed"}
+ )
+ yield AgentResponseChunk(
+ request_id=envelope.request_id or "",
+ channel_id=envelope.channel or "",
+ payload=payload,
+ is_complete=True,
+ )
+
@pytest.fixture
def history_store(monkeypatch):
@@ -114,3 +137,129 @@ async def test_local_mode_does_not_write_remote_history(tmp_path, history_store,
scheduler, job = make_scheduler(tmp_path)
await scheduler.execute(job, f"weather:{int(time.time())}")
assert history_store.list_sessions_blocking(user="owner", limit=20, offset=0) == []
+
+
+async def test_awaiting_approval_persists_user_prompt_without_assistant(
+ tmp_path, history_store,
+):
+ """审批暂停时 result_text 为空,仍须落 user 任务内容,刷新后窗口不空白。"""
+ job = CronJob(
+ id="bash-ask",
+ name="试 bash",
+ description="尝试调用一下bash工具",
+ enabled=True,
+ cron_expr="* * * * *",
+ timezone="Asia/Shanghai",
+ targets="web",
+ user_id="owner",
+ group_id="group",
+ bot_id="bot",
+ project_id="project",
+ work_mode="work",
+ )
+ run_id = f"bash-ask:{int(time.time())}"
+ state = CronRunState(
+ run_id=run_id,
+ job_id=job.id,
+ wake_at_iso="2026-10-13T15:01:00+08:00",
+ push_at_iso="2026-10-13T15:01:00+08:00",
+ job_name=job.name,
+ targets=job.targets,
+ session_id="",
+ chat_type="",
+ timezone=job.timezone,
+ exec_session_id="cron_awaiting_hist_1",
+ status="awaiting_approval",
+ started_at=time.time(),
+ finished_at=time.time(),
+ result_text=None,
+ )
+ await _persist_remote_cron_history(job, state)
+ detail = history_store.get_session_detail_blocking(
+ state.exec_session_id, user="owner", group_id="group", bot_id="bot",
+ )
+ assert detail is not None
+ assert detail["message_count"] == 1
+ assert detail["messages"][0]["role"] == "user"
+ assert detail["messages"][0]["content"] == "尝试调用一下bash工具"
+ assert detail["messages"][0]["request_id"] == f"cron-{run_id}"
+
+
+async def test_permission_pause_stream_persists_user_and_run_now_reuses_session(
+ tmp_path, history_store,
+):
+ """端到端:流式审批暂停落 user;再次 run_now 复用同一 cron_*。"""
+
+ class AskStreamClient(AgentClient):
+ def __init__(self):
+ super().__init__("success")
+
+ async def send_request_stream(self, envelope):
+ self.requests.append(envelope)
+ payloads = [
+ {"event_type": "chat.ask_user_question", "request_id": "perm-1"},
+ {"event_type": "chat.invocation_paused", "awaiting_user_input": True},
+ ]
+ for payload in payloads:
+ yield AgentResponseChunk(
+ request_id=envelope.request_id or "",
+ channel_id=envelope.channel or "",
+ payload=payload,
+ is_complete=payload.get("event_type") == "chat.invocation_paused",
+ )
+
+ class FakeHandler:
+ def __init__(self):
+ self.published = []
+
+ async def publish_robot_messages(self, msg):
+ self.published.append(msg)
+
+ job = CronJob(
+ id="bash-reuse",
+ name="试 bash",
+ description="尝试调用一下bash工具",
+ enabled=True,
+ cron_expr="* * * * *",
+ timezone="Asia/Shanghai",
+ targets="web",
+ user_id="owner",
+ group_id="group",
+ bot_id="bot",
+ project_id="project",
+ work_mode="work",
+ mode="agent",
+ )
+ store = CronJobStore(path=tmp_path / "jobs.json")
+ agent = AskStreamClient()
+ scheduler = CronSchedulerService(
+ store=store, agent_client=agent, message_handler=FakeHandler(),
+ )
+ scheduler._jobs[job.id] = job
+
+ run_id = f"{job.id}:1001"
+ await scheduler._on_wake(job, run_id)
+ task = scheduler._run_tasks.get(run_id)
+ assert task is not None
+ await task
+
+ state = scheduler._runs[run_id]
+ assert state.status == "awaiting_approval"
+ assert scheduler._permission_hold_active(job.id)
+
+ detail = history_store.get_session_detail_blocking(
+ state.exec_session_id, user="owner", group_id="group", bot_id="bot",
+ )
+ assert detail is not None
+ assert detail["message_count"] == 1
+ assert detail["messages"][0]["content"] == "尝试调用一下bash工具"
+
+ reused = await scheduler.trigger_run_now_info(job.id, preallocate=True)
+ assert reused["session_id"] == state.exec_session_id
+ assert reused.get("reused_pending_session") is True
+ assert reused.get("awaiting_approval") is True
+ assert reused["run_id"] == run_id
+ # 复用路径不再 schedule 新 wake / 新 session.create
+ assert len([r for r in agent.requests if getattr(r, "method", None) == "session.create"]) == 1
diff --git a/tests/unit_tests/gateway/test_cron_scheduler.py b/tests/unit_tests/gateway/test_cron_scheduler.py
index bdd39c7567..c6fd9ff1e9 100644
--- a/tests/unit_tests/gateway/test_cron_scheduler.py
+++ b/tests/unit_tests/gateway/test_cron_scheduler.py
@@ -132,6 +132,12 @@ class _TestableScheduler(CronSchedulerService):
async def on_wake(self, job, run_id):
return await self._on_wake(job, run_id)
+ async def on_push(self, job, run_id):
+ return await self._on_push(job, run_id)
+
+ async def permission_hold_blocks_new_run(self, job_id: str) -> bool:
+ return await self._permission_hold_blocks_new_run(job_id)
+
@property
def events(self):
"""Expose _events for test assertions (G.CLS.11: access via subclass property)."""
@@ -192,18 +198,25 @@ class FakeAgentClient:
async def send_request_stream(self, envelope):
self.stream_requests.append(envelope)
- payloads = [
- {
- "event_type": "workflow.updated",
- "workflow": {
- "id": "wf-1",
- "status": "completed",
- "summary": "team workflow done",
+ mode = str((getattr(envelope, "params", None) or {}).get("mode") or "")
+ if mode == "team" or mode.startswith("team"):
+ payloads = [
+ {
+ "event_type": "workflow.updated",
+ "workflow": {
+ "id": "wf-1",
+ "status": "completed",
+ "summary": "team workflow done",
+ },
},
- },
- {"event_type": "chat.final", "content": "team result"},
- {"is_complete": True},
- ]
+ {"event_type": "chat.final", "content": "team result"},
+ {"is_complete": True},
+ ]
+ else:
+ payloads = [
+ {"event_type": "chat.final", "content": "done"},
+ {"is_complete": True},
+ ]
for payload in payloads:
yield AgentResponseChunk(
request_id=envelope.request_id or "",
@@ -220,6 +233,11 @@ class FailingAgentClient(FakeAgentClient):
self.unary_requests.append(envelope)
raise RuntimeError("agent unavailable")
+ async def send_request_stream(self, envelope):
+ self.stream_requests.append(envelope)
+ raise RuntimeError("agent unavailable")
+ yield # pragma: no cover - keep this an async generator
+
class FakeMessageHandler:
"""Stub MessageHandler that records published messages."""
@@ -333,6 +351,168 @@ class TestCronLastSessionId:
assert state.exec_session_id == info["session_id"]
assert state.session_preallocated is True
+ @pytest.mark.asyncio
+ async def test_run_now_clears_orphan_hold_and_starts_new_session(self, tmp_path):
+ """Hold 残留但无 awaiting_approval run 时,run_now 不得卡在复用旧会话。"""
+ store = CronJobStore(path=tmp_path / "cron_jobs.json")
+ job = await _create_one_job(store)
+ svc = _make_scheduler(store)
+ stuck_sid = f"cron_orphan_{job.id}"
+ svc._permission_hold[job.id] = (time.time() + 600, stuck_sid)
+
+ info = await svc.trigger_run_now_info(job.id, preallocate=True)
+
+ assert info.get("reused_pending_session") is not True
+ assert info["session_id"] != stuck_sid
+ assert info["session_id"] == "cron_agentserver_allocated"
+ assert job.id not in svc._permission_hold
+
+ @pytest.mark.asyncio
+ async def test_run_now_keeps_real_awaiting_approval_hold(self, tmp_path):
+ """真有 awaiting_approval run 时仍复用,不误清 hold。"""
+ store = CronJobStore(path=tmp_path / "cron_jobs.json")
+ job = await _create_one_job(store)
+ svc = _make_scheduler(store)
+ held_sid = f"cron_pending_{job.id}"
+ run_id = f"{job.id}:pending"
+ svc._permission_hold[job.id] = (time.time() + 600, held_sid)
+ svc._runs[run_id] = CronRunState(
+ run_id=run_id,
+ job_id=job.id,
+ wake_at_iso="2026-01-01T00:00:00+08:00",
+ push_at_iso="2026-01-01T00:00:00+08:00",
+ job_name=job.name,
+ targets=job.targets,
+ session_id=job.session_id,
+ chat_type=job.chat_type,
+ timezone=job.timezone,
+ exec_session_id=held_sid,
+ status="awaiting_approval",
+ )
+
+ info = await svc.trigger_run_now_info(job.id, preallocate=True)
+
+ assert info.get("reused_pending_session") is True
+ assert info["session_id"] == held_sid
+ assert info["awaiting_approval"] is True
+ assert job.id in svc._permission_hold
+
+ @pytest.mark.asyncio
+ async def test_peer_replica_does_not_clear_redis_permission_hold(
+ self, tmp_path, monkeypatch,
+ ):
+ """双实例共享 FakeRedis:A 待审批时 B 不得清 Redis hold / 不得新开跑。"""
+ from jiuwenswarm.extensions.redis.redis_keys import cron_permission_hold_rel
+
+ class _HoldFakeRedis:
+ def __init__(self) -> None:
+ self.kv: dict[str, str] = {}
+
+ async def get(self, key: str):
+ return self.kv.get(key)
+
+ async def set(self, key: str, value, ttl_seconds: int | None = None) -> bool:
+ self.kv[key] = str(value)
+ return True
+
+ async def delete(self, *keys: str) -> int:
+ removed = 0
+ for key in keys:
+ if key in self.kv:
+ del self.kv[key]
+ removed += 1
+ return removed
+
+ redis = _HoldFakeRedis()
+ monkeypatch.setattr(
+ CronSchedulerService,
+ "_redis_hold_required",
+ staticmethod(lambda: True),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.extensions.redis.redis_runtime.get_gateway_redis_client_if_open",
+ lambda: redis,
+ )
+
+ store = CronJobStore(path=tmp_path / "cron_jobs.json")
+ job = await _create_one_job(store)
+ held_sid = f"cron_pending_{job.id}"
+ hold_key = cron_permission_hold_rel(job.id)
+
+ svc_a = _make_scheduler(store)
+ svc_b = _make_scheduler(store)
+ run_id = f"{job.id}:pending"
+ svc_a._permission_hold[job.id] = (time.time() + 600, held_sid)
+ svc_a._runs[run_id] = CronRunState(
+ run_id=run_id,
+ job_id=job.id,
+ wake_at_iso="2026-01-01T00:00:00+08:00",
+ push_at_iso="2026-01-01T00:00:00+08:00",
+ job_name=job.name,
+ targets=job.targets,
+ session_id=job.session_id,
+ chat_type=job.chat_type,
+ timezone=job.timezone,
+ exec_session_id=held_sid,
+ status="awaiting_approval",
+ )
+ await svc_a._redis_write_permission_hold(job.id, held_sid, 600)
+ assert redis.kv.get(hold_key) == held_sid
+
+ # B 本机无 awaiting run,但 Redis hold 仍在 → 不得当孤儿清掉。
+ assert await svc_b.permission_hold_blocks_new_run(job.id) is True
+ assert redis.kv.get(hold_key) == held_sid
+
+ reused = await svc_b.trigger_run_now_info(job.id, preallocate=True)
+ assert reused.get("reused_pending_session") is True
+ assert reused["session_id"] == held_sid
+ assert redis.kv.get(hold_key) == held_sid
+
+ # B 上的 wake 应标 skipped,且仍不删 Redis hold。
+ next_run_id = f"{job.id}:wake-b"
+ svc_b._runs[next_run_id] = CronRunState(
+ run_id=next_run_id,
+ job_id=job.id,
+ wake_at_iso="2026-01-01T01:00:00+08:00",
+ push_at_iso="2026-01-01T01:00:00+08:00",
+ job_name=job.name,
+ targets=job.targets,
+ session_id=job.session_id,
+ chat_type=job.chat_type,
+ timezone=job.timezone,
+ status="pending",
+ )
+ await svc_b.on_wake(job, next_run_id)
+ assert svc_b.runs[next_run_id].status == "skipped"
+ assert redis.kv.get(hold_key) == held_sid
+
+ @pytest.mark.asyncio
+ async def test_on_push_skips_placeholder_for_skipped_status(self, tmp_path):
+ """权限 hold 导致 wake skipped 后,push 不得发「正在执行中」占位。"""
+ store = CronJobStore(path=tmp_path / "cron_jobs.json")
+ job = await _create_one_job(store)
+ handler = FakeMessageHandler()
+ svc = _make_scheduler(store, handler=handler)
+ run_id = f"{job.id}:skipped-push"
+ svc._runs[run_id] = CronRunState(
+ run_id=run_id,
+ job_id=job.id,
+ wake_at_iso="2026-01-01T00:00:00+08:00",
+ push_at_iso="2026-01-01T00:05:00+08:00",
+ job_name=job.name,
+ targets=job.targets,
+ session_id=job.session_id,
+ chat_type=job.chat_type,
+ timezone=job.timezone,
+ status="skipped",
+ )
+
+ await svc.on_push(job, run_id)
+
+ assert handler.published == []
+ assert svc.runs[run_id].placeholder_sent is False
+ assert svc.runs[run_id].pushed_final is False
+
class TestCheckStoreChanged:
"""_check_store_changed detects file deletion, modification, recreation."""
@@ -1024,12 +1204,13 @@ class TestTeamModeWake:
assert task is not None
await task
- assert len(agent.unary_requests) == 2
- assert len(agent.stream_requests) == 0
- create_env, env = agent.unary_requests
+ assert len(agent.unary_requests) == 1
+ assert len(agent.stream_requests) == 1
+ create_env = agent.unary_requests[0]
+ env = agent.stream_requests[0]
assert create_env.method == "session.create"
assert "session_id" not in create_env.params
- assert env.is_stream is False
+ assert env.is_stream is True
assert env.channel == "__cron__"
assert env.session_id == "cron_agentserver_allocated"
@@ -1052,10 +1233,282 @@ class TestTeamModeWake:
assert task is not None
await task
- env = agent.unary_requests[1]
+ env = agent.stream_requests[0]
assert env.params["model_name"] == "fast-model"
assert "model" not in env.params
+ @pytest.mark.asyncio
+ async def test_agent_wake_permission_pause_forwards_card_and_skips_next_fire(self, tmp_path):
+ store = CronJobStore(path=tmp_path / "cron_jobs.json")
+ job = _make_job(description="提醒我吃药", targets="web")
+
+ class AskStreamClient(FakeAgentClient):
+ async def send_request_stream(self, envelope):
+ self.stream_requests.append(envelope)
+ payloads = [
+ {"event_type": "chat.reasoning", "content": "先看一下要执行的命令"},
+ {"event_type": "chat.delta", "content": "准备调用 bash"},
+ {
+ "event_type": "chat.ask_user_question",
+ "request_id": "perm-1",
+ "questions": [
+ {
+ "question": "允许使用 grep?",
+ "options": [{"label": "本次允许"}],
+ }
+ ],
+ },
+ {
+ "event_type": "chat.invocation_paused",
+ "awaiting_user_input": True,
+ },
+ ]
+ for payload in payloads:
+ yield AgentResponseChunk(
+ request_id=envelope.request_id or "",
+ channel_id=envelope.channel or "",
+ payload=payload,
+ is_complete=payload.get("event_type") == "chat.invocation_paused",
+ )
+
+ agent = AskStreamClient()
+ handler = FakeMessageHandler()
+ svc = _make_scheduler(store, handler, agent_client=agent)
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus
+
+ live_queue = cron_live_bus.subscribe("cron_agentserver_allocated")
+
+ run_id = f"{job.id}:1234"
+ await svc.on_wake(job, run_id)
+ task = svc.run_tasks.get(run_id)
+ assert task is not None
+ await task
+
+ state = svc.runs[run_id]
+ assert state.status == "awaiting_approval"
+ assert not state.result_text
+ assert len(agent.stream_requests) == 1
+ ask_msgs = [
+ msg for msg in handler.published
+ if getattr(msg.event_type, "value", msg.event_type) == "chat.ask_user_question"
+ ]
+ assert len(ask_msgs) == 1
+ assert ask_msgs[0].payload["session_id"] == state.exec_session_id
+ assert ask_msgs[0].payload["cron"]["job_id"] == job.id
+ published_events = [
+ getattr(msg.event_type, "value", msg.event_type) for msg in handler.published
+ ]
+ assert "chat.reasoning" in published_events
+ assert "chat.delta" in published_events
+ delta_msgs = [
+ msg for msg in handler.published
+ if getattr(msg.event_type, "value", msg.event_type) == "chat.delta"
+ ]
+ assert delta_msgs and isinstance(delta_msgs[0].payload.get("live_seq"), int)
+ live_events = []
+ live_seqs = []
+ while not live_queue.empty():
+ frame = live_queue.get_nowait()
+ live_events.append(frame["event"])
+ seq = (frame.get("payload") or {}).get("live_seq")
+ if isinstance(seq, int):
+ live_seqs.append(seq)
+ cron_live_bus.unsubscribe("cron_agentserver_allocated", live_queue)
+ assert live_events[:4] == [
+ "chat.processing_status",
+ "chat.reasoning",
+ "chat.delta",
+ "chat.ask_user_question",
+ ]
+ assert live_seqs == sorted(live_seqs) and live_seqs == list(range(1, len(live_seqs) + 1))
+ assert all(
+ "任务执行完成但未返回结果内容" not in str((msg.payload or {}).get("content") or "")
+ for msg in handler.published
+ )
+
+ next_run_id = f"{job.id}:5678"
+ await svc.on_wake(job, next_run_id)
+ assert len(agent.stream_requests) == 1
+ assert svc.runs[next_run_id].status == "skipped"
+ assert svc.runs[next_run_id].pushed_final is False
+
+ # 立即执行应复用待审批会话,不再新建空 cron_* / 不再调度 wake。
+ reused = await svc.trigger_run_now_info(job.id, preallocate=True)
+ assert reused["session_id"] == state.exec_session_id
+ assert reused.get("reused_pending_session") is True
+ assert reused.get("awaiting_approval") is True
+ assert reused["run_id"] == run_id
+ assert len(svc.runs) == 2 # 原 awaiting + skipped,无第三轮
+
+ svc.release_permission_hold_for_session(state.exec_session_id)
+ assert not svc._permission_hold_active(job.id)
+
+ @pytest.mark.asyncio
+ async def test_agent_wake_ask_without_pause_still_emits_processing_false(self, tmp_path):
+ """Non-HITL ask (or ask then in-band continue) must not stick awaiting_approval."""
+ store = CronJobStore(path=tmp_path / "cron_jobs.json")
+ job = _make_job(description="验证 read_file", targets="web")
+
+ class AskThenCompleteClient(FakeAgentClient):
+ async def send_request_stream(self, envelope):
+ self.stream_requests.append(envelope)
+ payloads = [
+ {"event_type": "chat.ask_user_question", "request_id": "ask-auto"},
+ {"event_type": "chat.tool_result", "content": "ok"},
+ {"event_type": "chat.final", "content": "验证通过"},
+ {"event_type": "chat.processing_status", "is_processing": False},
+ {"is_complete": True},
+ ]
+ for payload in payloads:
+ yield AgentResponseChunk(
+ request_id=envelope.request_id or "",
+ channel_id=envelope.channel or "",
+ payload=payload,
+ is_complete=bool(payload.get("is_complete")),
+ )
+
+ agent = AskThenCompleteClient()
+ handler = FakeMessageHandler()
+ svc = _make_scheduler(store, handler, agent_client=agent)
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus
+
+ live_queue = cron_live_bus.subscribe("cron_agentserver_allocated")
+
+ run_id = f"{job.id}:ask-complete"
+ await svc.on_wake(job, run_id)
+ task = svc.run_tasks.get(run_id)
+ assert task is not None
+ await task
+
+ state = svc.runs[run_id]
+ assert state.status == "succeeded"
+ assert state.result_text == "验证通过"
+ live_events = []
+ processing_flags = []
+ while not live_queue.empty():
+ frame = live_queue.get_nowait()
+ live_events.append(frame["event"])
+ if frame["event"] == "chat.processing_status":
+ processing_flags.append(frame["payload"].get("is_processing"))
+ cron_live_bus.unsubscribe("cron_agentserver_allocated", live_queue)
+ assert "chat.ask_user_question" in live_events
+ assert "chat.final" in live_events
+ assert processing_flags[0] is True
+ assert False in processing_flags
+ assert processing_flags[-1] is False
+ # B': final must reach live before the terminal processing=false.
+ final_idx = live_events.index("chat.final")
+ status_i = 0
+ last_false_idx = -1
+ for i, ev in enumerate(live_events):
+ if ev != "chat.processing_status":
+ continue
+ if processing_flags[status_i] is False:
+ last_false_idx = i
+ status_i += 1
+ assert last_false_idx > final_idx
+
+ @pytest.mark.asyncio
+ async def test_agent_wake_forwards_final_before_processing_false(self, tmp_path):
+ """Delta-only streams still get a live chat.final before processing=false."""
+ store = CronJobStore(path=tmp_path / "cron_jobs.json")
+ job = _make_job(description="你好,不要调用任何工具,直接回复", targets="web")
+
+ class DeltaOnlyClient(FakeAgentClient):
+ async def send_request_stream(self, envelope):
+ self.stream_requests.append(envelope)
+ payloads = [
+ {"event_type": "chat.delta", "content": "你好"},
+ {"event_type": "chat.delta", "content": "!我在这儿"},
+ {"event_type": "chat.processing_status", "is_processing": False},
+ {"is_complete": True},
+ ]
+ for payload in payloads:
+ yield AgentResponseChunk(
+ request_id=envelope.request_id or "",
+ channel_id=envelope.channel or "",
+ payload=payload,
+ is_complete=bool(payload.get("is_complete")),
+ )
+
+ agent = DeltaOnlyClient()
+ handler = FakeMessageHandler()
+ svc = _make_scheduler(store, handler, agent_client=agent)
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus
+
+ live_queue = cron_live_bus.subscribe("cron_agentserver_allocated")
+ run_id = f"{job.id}:delta-final"
+ await svc.on_wake(job, run_id)
+ task = svc.run_tasks.get(run_id)
+ assert task is not None
+ await task
+
+ state = svc.runs[run_id]
+ assert state.status == "succeeded"
+ assert state.result_text == "你好!我在这儿"
+ live_events = []
+ while not live_queue.empty():
+ live_events.append(live_queue.get_nowait()["event"])
+ cron_live_bus.unsubscribe("cron_agentserver_allocated", live_queue)
+ assert live_events[0] == "chat.processing_status"
+ assert "chat.delta" in live_events
+ assert "chat.final" in live_events
+ assert live_events.index("chat.final") < len(live_events) - 1
+ assert live_events[-1] == "chat.processing_status"
+
+ @pytest.mark.asyncio
+ async def test_agent_wake_forwards_usage_summary_to_live(self, tmp_path):
+ """Token/cost row needs chat.usage_summary on the cron live bus."""
+ store = CronJobStore(path=tmp_path / "cron_jobs.json")
+ job = _make_job(description="你好,不要调用任何工具,直接回复", targets="web")
+ usage = {
+ "input_tokens": 24664,
+ "output_tokens": 93,
+ "total_tokens": 24757,
+ "total_cost": 0.0483,
+ }
+
+ class UsageClient(FakeAgentClient):
+ async def send_request_stream(self, envelope):
+ self.stream_requests.append(envelope)
+ payloads = [
+ {"event_type": "chat.delta", "content": "你好"},
+ {"event_type": "chat.final", "content": "你好"},
+ {"event_type": "chat.usage_summary", "usage": usage},
+ {"is_complete": True},
+ ]
+ for payload in payloads:
+ yield AgentResponseChunk(
+ request_id=envelope.request_id or "",
+ channel_id=envelope.channel or "",
+ payload=payload,
+ is_complete=bool(payload.get("is_complete")),
+ )
+
+ agent = UsageClient()
+ handler = FakeMessageHandler()
+ svc = _make_scheduler(store, handler, agent_client=agent)
+ from jiuwenswarm.gateway.cron.live_bus import cron_live_bus
+
+ live_queue = cron_live_bus.subscribe("cron_agentserver_allocated")
+ run_id = f"{job.id}:usage-summary"
+ await svc.on_wake(job, run_id)
+ task = svc.run_tasks.get(run_id)
+ assert task is not None
+ await task
+
+ live_frames = []
+ while not live_queue.empty():
+ live_frames.append(live_queue.get_nowait())
+ cron_live_bus.unsubscribe("cron_agentserver_allocated", live_queue)
+ usage_frames = [f for f in live_frames if f.get("event") == "chat.usage_summary"]
+ assert len(usage_frames) == 1
+ assert usage_frames[0]["payload"]["usage"]["total_tokens"] == 24757
+ events = [f["event"] for f in live_frames]
+ # usage 须在收口 processing=false 之前到达,否则前端拆 live 后收不到。
+ assert events.index("chat.usage_summary") < len(events) - 1
+ assert events[-1] == "chat.processing_status"
+
@pytest.mark.asyncio
async def test_team_wake_stream_timeout(self, tmp_path):
store = CronJobStore(path=tmp_path / "cron_jobs.json")
diff --git a/tests/unit_tests/gateway/test_message_handler_evolution.py b/tests/unit_tests/gateway/test_message_handler_evolution.py
index 9c1da527b8..3b64a482be 100644
--- a/tests/unit_tests/gateway/test_message_handler_evolution.py
+++ b/tests/unit_tests/gateway/test_message_handler_evolution.py
@@ -637,6 +637,234 @@ def test_processing_status_is_only_emitted_for_chat_streams() -> None:
+async def test_hitl_pause_skips_processing_false_supplement() -> None:
+ """invocation_paused 收尾时不得补发 processing=false(cron 二次审批续跑)。"""
+ handler = _TestMessageHandler.create()
+ _FakeAgentClient.stream_payloads = [
+ {
+ "event_type": "chat.ask_user_question",
+ "request_id": "perm-read-1",
+ "source": "permission_interrupt",
+ "questions": [{"question": "允许 read_file?", "options": [{"label": "本次允许"}]}],
+ },
+ {
+ "event_type": "chat.invocation_paused",
+ "awaiting_user_input": True,
+ },
+ ]
+ env = SimpleNamespace(
+ request_id="resume-hitl-1",
+ channel="web",
+ method=ReqMethod.CHAT_SEND.value,
+ params={
+ "source": "permission_interrupt",
+ "request_id": "perm-bash-1",
+ "answers": [{"selected_options": ["allow_once"]}],
+ },
+ )
+ # 走 impl,避开本环境 telemetry/observability 导入链。
+ await handler._process_stream_impl(
+ env,
+ "cron_sess_hitl",
+ None,
+ emit_processing_status=True,
+ telemetry_outcome={"error": None, "cancelled": False},
+ )
+
+ payloads = await _drain_robot_payloads_for_permission_resume(handler)
+ assert any(p.get("event_type") == "chat.ask_user_question" for p in payloads)
+ assert any(p.get("event_type") == "chat.invocation_paused" for p in payloads)
+ assert not any(
+ p.get("event_type") == "chat.processing_status"
+ and p.get("is_processing") is False
+ for p in payloads
+ )
+
+
+async def test_cron_permission_resume_empty_final_releases_hold() -> None:
+ """空 final(drain 后)且无新 ask:流结束须释放 hold,便于下次 run-now 新开。"""
+ handler = _TestMessageHandler.create()
+ released: list[str] = []
+ handler._cron_registry = SimpleNamespace(
+ release_cron_permission_hold=lambda sid: released.append(sid),
+ )
+ _FakeAgentClient.stream_payloads = [
+ {"event_type": "chat.delta", "content": "bash 验证完成"},
+ {"event_type": "chat.final", "content": ""},
+ ]
+ env = SimpleNamespace(
+ request_id="resume-empty-final-1",
+ channel="web",
+ method=ReqMethod.CHAT_SEND.value,
+ params={
+ "source": "permission_interrupt",
+ "request_id": "perm-bash-2",
+ "answers": [{"selected_options": ["allow_once"]}],
+ },
+ )
+ await handler._process_stream_impl(
+ env,
+ "cron_1a13859afeb_db60b72257b9",
+ None,
+ emit_processing_status=True,
+ telemetry_outcome={"error": None, "cancelled": False},
+ )
+ assert released == ["cron_1a13859afeb_db60b72257b9"]
+ payloads = await _drain_robot_payloads_for_permission_resume(handler)
+ assert any(
+ p.get("event_type") == "chat.processing_status"
+ and p.get("is_processing") is False
+ for p in payloads
+ )
+
+
+async def test_cron_permission_resume_second_ask_keeps_hold_and_skips_false() -> None:
+ """多工具第二次权限 ask:不释放 hold、不补 processing=false(即使无 pause 帧)。"""
+ handler = _TestMessageHandler.create()
+ released: list[str] = []
+ handler._cron_registry = SimpleNamespace(
+ release_cron_permission_hold=lambda sid: released.append(sid),
+ )
+ _FakeAgentClient.stream_payloads = [
+ {"event_type": "chat.delta", "content": "准备调用 read_file"},
+ {"event_type": "chat.final", "content": "中间收口正文"},
+ {
+ "event_type": "chat.ask_user_question",
+ "request_id": "perm-read-2",
+ "source": "permission_interrupt",
+ },
+ # 故意不发 invocation_paused:覆盖 pause 帧丢失时仍须保卡/保 hold。
+ ]
+ env = SimpleNamespace(
+ request_id="resume-second-ask-1",
+ channel="web",
+ method=ReqMethod.CHAT_SEND.value,
+ params={
+ "source": "permission_interrupt",
+ "request_id": "perm-bash-3",
+ "answers": [{"selected_options": ["allow_once"]}],
+ },
+ )
+ await handler._process_stream_impl(
+ env,
+ "cron_sess_second_ask",
+ None,
+ emit_processing_status=True,
+ telemetry_outcome={"error": None, "cancelled": False},
+ )
+ assert released == []
+ payloads = await _drain_robot_payloads_for_permission_resume(handler)
+ assert any(p.get("event_type") == "chat.ask_user_question" for p in payloads)
+ assert not any(
+ p.get("event_type") == "chat.processing_status"
+ and p.get("is_processing") is False
+ for p in payloads
+ )
+
+
+async def test_cron_permission_resume_contentful_final_alone_does_not_release() -> None:
+ """仅有正文 final、流中又二次 pause:中间 final 不得单独释放 hold。"""
+ handler = _TestMessageHandler.create()
+ released: list[str] = []
+ handler._cron_registry = SimpleNamespace(
+ release_cron_permission_hold=lambda sid: released.append(sid),
+ )
+ _FakeAgentClient.stream_payloads = [
+ {"event_type": "chat.final", "content": "工具1已执行"},
+ {
+ "event_type": "chat.ask_user_question",
+ "request_id": "perm-bash-4",
+ "source": "permission_interrupt",
+ },
+ {
+ "event_type": "chat.invocation_paused",
+ "awaiting_user_input": True,
+ },
+ ]
+ env = SimpleNamespace(
+ request_id="resume-mid-final-1",
+ channel="web",
+ method=ReqMethod.CHAT_SEND.value,
+ params={
+ "source": "permission_interrupt",
+ "request_id": "perm-1",
+ "answers": [{"selected_options": ["allow_once"]}],
+ },
+ )
+ await handler._process_stream_impl(
+ env,
+ "cron_sess_mid_final",
+ None,
+ emit_processing_status=True,
+ telemetry_outcome={"error": None, "cancelled": False},
+ )
+ assert released == []
+
+
+async def test_non_cron_permission_resume_does_not_release_cron_hold() -> None:
+ """普通 sess_* 审批续跑不得走 cron hold 释放。"""
+ handler = _TestMessageHandler.create()
+ released: list[str] = []
+ handler._cron_registry = SimpleNamespace(
+ release_cron_permission_hold=lambda sid: released.append(sid),
+ )
+ _FakeAgentClient.stream_payloads = [
+ {"event_type": "chat.final", "content": ""},
+ ]
+ env = SimpleNamespace(
+ request_id="resume-sess-1",
+ channel="web",
+ method=ReqMethod.CHAT_SEND.value,
+ params={
+ "source": "permission_interrupt",
+ "request_id": "perm-1",
+ "answers": [{"selected_options": ["allow_once"]}],
+ },
+ )
+ await handler._process_stream_impl(
+ env,
+ "sess_normal_1",
+ None,
+ emit_processing_status=True,
+ telemetry_outcome={"error": None, "cancelled": False},
+ )
+ assert released == []
+
+
+async def test_normal_complete_still_supplements_processing_false() -> None:
+ """无 HITL 暂停时,Agent 未发 false 仍由 Gateway 补发。"""
+ handler = _TestMessageHandler.create()
+ _FakeAgentClient.stream_payloads = [
+ {"event_type": "chat.final", "content": "done"},
+ ]
+ env = SimpleNamespace(
+ request_id="chat-complete-1",
+ channel="web",
+ method=ReqMethod.CHAT_SEND.value,
+ params={"query": "hello"},
+ )
+ await handler._process_stream_impl(
+ env,
+ "sess-complete",
+ None,
+ emit_processing_status=True,
+ telemetry_outcome={"error": None, "cancelled": False},
+ )
+
+ payloads = await _drain_robot_payloads_for_permission_resume(handler)
+ assert any(
+ p.get("event_type") == "chat.processing_status"
+ and p.get("is_processing") is False
+ for p in payloads
+ )
+
+
@pytest.mark.asyncio
async def test_permission_resume_stream_keeps_processing_while_goal_stream_active() -> None:
"""command.goal (emit=False) still blocks processing_status=false on permission ack."""