Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(hetero): stop AskUserQuestion cards from freezing after the producer times out (#19804)

Arvin Xu878e802cebfc
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 88f76b80f9b..6268007dd99 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -56,6 +56,7 @@ drive / probe / capture / publish. Skip a row only when its surface AND runtime
| P32 | web, electron | hetero | fixture | Dispatch a temp assistant message and attach an `AgentRuntimeError` guide code |
| P33 | web, electron | any | fixture | Backfill `pluginState` from each tool message's result after Agent Mock playback |
| P34 | web, electron | any | fixture | Dispatch an assistant+tool pair into an empty conversation; truncate args to reach the Streaming render |
+| P87 | web, electron | any | fixture | Render a pending intervention card: explicit dispatch context, `messagesInit`, `intervention` on BOTH projections, a registered operation |
| P35 | web | gateway | probe | Step-boundary `uiMessages` snapshots overwrite the bucket; record `replaceMessages` stacks, A/B with `disableGatewayMode` |
| P36 | web | gateway | env | Run the JWT handshake probe after every gateway restart; `/health` 200 proves nothing |
| P37 | any | gateway | env | QStash / s3rver on fixed ports may belong to a sibling session; read the start log before stopping anything |
@@ -1173,6 +1174,46 @@ code A/B, re-dispatch after each edit rather than expecting react-refresh to kee
the messages — and re-run the identical dispatch + expand + scroll sequence on both
sides so the two frames differ only by the change.
+#### P87 · Rendering a pending intervention card: four gates, not one dispatch
+
+**applies-to:** surface=web, electron · runtime=any · phase=fixture
+
+**Situation:** verifying the AskUserQuestion / approval card (the InterventionBar
+and the global approval island) without driving a real agent run.
+
+**Doesn't work:** the P34 assistant+tool dispatch alone. The pair lands in the
+store and still nothing renders, or it renders but every submit silently
+early-returns, because four separate gates each fail quietly:
+
+1. **`activeAgentId` is empty until the route settles.** `internal_dispatchMessage`
+ with no context reads global state, so the pair lands in `main__new` and no
+ surface ever looks there. Pass an explicit
+ `{ context: { agentId, threadId, topicId } }`.
+2. **`messagesInit === false` keeps the conversation on its welcome state**, so a
+ correctly-bucketed pair renders nothing. Gate the seed on it, not on
+ `networkidle`.
+3. **`getPendingInterventions` reads two projections.** The tool row needs
+ `pluginIntervention.status === 'pending'`, and the parent assistant's
+ `tools[i]` needs its own `intervention: { status: 'pending' }` — the display
+ pipeline folds the tool row into an `assistantGroup`, after which only the
+ `children[].tools` copy is reachable. Stamping one of the two renders nothing.
+4. **A submit needs a registered operation or it never reaches a transport.**
+ With no `messageOperationMap` entry, `submitHeteroIntervention` warns
+ `no operationId` and returns — the card's own spinner still resolves, so it
+ looks like a successful submit while the whole store path was skipped. Register
+ it the way the product does: `startOperation({ context: { messageId: <assistantId> } })`,
+ with `type: 'execServerAgentRuntime'` for the remote/gateway branch (an
+ `execHeterogeneousAgent` op takes the local Electron IPC branch instead).
+
+**Also useful:** switching cards in the tab strip is a genuine remount —
+`InterventionBar` renders `InterventionContent` with `key={toolCallId}` — so two
+seeded cards give you a remount probe without a reload that would drop the
+in-memory fixture. In-SPA navigation away and back does NOT work: it refetches
+messages and wipes the pair. And `setInterventionAnswers` will log
+`persist failed: Plugin not found` for a store-only fixture; that is expected and
+is swallowed by design, not a defect — treat it as confirmation the flow reached
+the real transport.
+
#### P35 · A client bucket that keeps reverting mid-run is the gateway `uiMessages` snapshot, not your write
**applies-to:** surface=web · runtime=gateway · phase=probe
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 5990758a87f..0cf0f4dd7f0 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2055,6 +2055,7 @@
"tool.intervention.optionApproveRemember": "Approve, and don't ask again for similar actions",
"tool.intervention.pending": "Pending",
"tool.intervention.questionSkipped": "You skipped this question",
+ "tool.intervention.questionTimedOut": "This question timed out before it was answered",
"tool.intervention.reject": "Reject",
"tool.intervention.rejectOnly": "Reject",
"tool.intervention.rejectReasonPlaceholder": "Tell the agent what you'd like instead",
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index c4505fae74d..a88c6737553 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -67,6 +67,7 @@
"claudeCode.askUserQuestion.supplement.enter": "Additional notes",
"claudeCode.askUserQuestion.supplement.placeholder": "Add context to your selected answers…",
"claudeCode.askUserQuestion.timeExpired": "Time expired — using option 1 of each question.",
+ "claudeCode.askUserQuestion.timeExpiredNoAnswer": "Time expired — this question can no longer be answered.",
"claudeCode.askUserQuestion.timeRemaining": "Time remaining: {{time}} · unanswered questions default to option 1 on timeout.",
"codeInterpreter-legacy.error": "Execution Error",
"codeInterpreter-legacy.executing": "Executing...",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 83a0b76ebca..16809df651e 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2055,6 +2055,7 @@
"tool.intervention.optionApproveRemember": "批准,且类似操作不再询问",
"tool.intervention.pending": "等待中",
"tool.intervention.questionSkipped": "你已跳过此次提问",
+ "tool.intervention.questionTimedOut": "这个提问在作答前已超时",
"tool.intervention.reject": "拒绝",
"tool.intervention.rejectOnly": "仅拒绝",
"tool.intervention.rejectReasonPlaceholder": "告诉 Agent 你希望它怎么做",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index 473f9048bbc..a848405c02e 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -67,6 +67,7 @@
"claudeCode.askUserQuestion.supplement.enter": "补充说明",
"claudeCode.askUserQuestion.supplement.placeholder": "为已选答案补充更多背景…",
"claudeCode.askUserQuestion.timeExpired": "已超时——将使用每题的选项 1。",
+ "claudeCode.askUserQuestion.timeExpiredNoAnswer": "已超时——这个提问已经无法再作答。",
"claudeCode.askUserQuestion.timeRemaining": "剩余时间:{{time}} · 超时后未作答题目默认选项 1。",
"codeInterpreter-legacy.error": "执行出错",
"codeInterpreter-legacy.executing": "正在执行...",
diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx
index ec633d938b7..f4542804ea3 100644
--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx
@@ -40,6 +40,17 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
const msg = dataSelectors.getDbMessageById(messageId)(s);
return (msg?.pluginState as { [DRAFT_PLUGIN_STATE_KEY]?: unknown })?.[DRAFT_PLUGIN_STATE_KEY];
});
+ // The producer stamps its own ask-user deadline onto the durable tool row.
+ // Hand it to the form so the countdown tracks the clock that actually
+ // decides when the answer stops being deliverable, instead of restarting on
+ // every remount and outliving the blocked producer.
+ const deadlineAt = useConversationStore((s) => {
+ const msg = dataSelectors.getDbMessageById(messageId)(s);
+ const stored = (
+ msg?.pluginState as { heterogeneousIntervention?: { deadline?: unknown } } | undefined
+ )?.heterogeneousIntervention?.deadline;
+ return typeof stored === 'number' ? stored : undefined;
+ });
const setInterventionDraft = useChatStore((s) => s.setInterventionDraft);
const writeDraft = useCallback(
(draft: AskUserDraft) => setInterventionDraft(messageId, draft),
@@ -49,6 +60,7 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
const form = useAskUserForm({
args,
countdownMs: DEFAULT_COUNTDOWN_MS,
+ deadlineAt,
disabled,
onInteractionAction,
persistedDraft,
@@ -67,6 +79,7 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
supplementEnter: t('claudeCode.askUserQuestion.supplement.enter'),
supplementPlaceholder: t('claudeCode.askUserQuestion.supplement.placeholder'),
timeExpired: t('claudeCode.askUserQuestion.timeExpired'),
+ timeExpiredNoAnswer: t('claudeCode.askUserQuestion.timeExpiredNoAnswer'),
timeRemaining: (time: string) => t('claudeCode.askUserQuestion.timeRemaining', { time }),
};
diff --git a/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx b/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx
index 96a37d665f3..a60791bf797 100644
--- a/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx
+++ b/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx
@@ -116,6 +116,7 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio
supplementEnter: t('askUserQuestion.supplement.enter'),
supplementPlaceholder: t('askUserQuestion.supplement.placeholder'),
timeExpired: '',
+ timeExpiredNoAnswer: '',
timeRemaining: () => '',
};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 7fc74c24890..e632015be62 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2386,6 +2386,7 @@ export default {
'tool.intervention.toolAbort': 'You canceled this Skill call',
'tool.intervention.toolRejected': 'This Skill call was rejected',
'tool.intervention.questionSkipped': 'You skipped this question',
+ 'tool.intervention.questionTimedOut': 'This question timed out before it was answered',
'tool.intervention.toolSkipped': 'You skipped this step',
'toolAuth.authorize': 'Authorize',
'toolAuth.authorizing': 'Authorizing...',
diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.ts
index edd9e02d95a..72fd28c37cf 100644
--- a/packages/locales/src/default/tool.ts
+++ b/packages/locales/src/default/tool.ts
@@ -72,6 +72,8 @@ export default {
'claudeCode.askUserQuestion.skip': 'Skip',
'claudeCode.askUserQuestion.submit': 'Submit',
'claudeCode.askUserQuestion.timeExpired': 'Time expired — using option 1 of each question.',
+ 'claudeCode.askUserQuestion.timeExpiredNoAnswer':
+ 'Time expired — this question can no longer be answered.',
'claudeCode.askUserQuestion.timeRemaining':
'Time remaining: {{time}} · unanswered questions default to option 1 on timeout.',
'codeInterpreter-legacy.error': 'Execution Error',
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx
index a66df4506c6..0cff8a2a91b 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx
+++ b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx
@@ -56,7 +56,15 @@ export interface AskUserQuestionLabels {
submit: string;
supplementEnter: string;
supplementPlaceholder: string;
+ /** Shown once the timeout fallback has answered on the user's behalf. */
timeExpired: string;
+ /**
+ * Shown when the clock ran out with no fallback answer — provider-owned
+ * option ids (consent is never inferred) or a card opened after the
+ * producer already stopped waiting. Promising "option 1 will be used" here
+ * would describe a submission that is never going to happen.
+ */
+ timeExpiredNoAnswer: string;
timeRemaining: (time: string) => string;
}
@@ -84,6 +92,7 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {
actionsPortalTarget,
activeQuestion,
activeTab,
+ autoSubmitted,
custom,
escapeActive,
escapeText,
@@ -282,7 +291,11 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {
>
{showCountdown && (
<Text fontSize={12} type="secondary">
- {expired ? labels.timeExpired : labels.timeRemaining(formatRemaining(remainingMs))}
+ {autoSubmitted
+ ? labels.timeExpired
+ : expired
+ ? labels.timeExpiredNoAnswer
+ : labels.timeRemaining(formatRemaining(remainingMs))}
</Text>
)}
<Flexbox horizontal gap={8}>
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/draft.ts b/packages/shared-tool-ui/src/AskUserQuestion/draft.ts
index 0670ae1f34e..43b9f0663e9 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/draft.ts
+++ b/packages/shared-tool-ui/src/AskUserQuestion/draft.ts
@@ -13,12 +13,45 @@ export const FREEFORM_PAYLOAD_KEY = '__freeform__';
export const SUPPLEMENT_PAYLOAD_KEY = '__supplement__';
/**
- * Default on-screen countdown, mirroring the server-side bridge timeout
- * (`DEFAULT_ASK_USER_TIMEOUT_MS`). Hosts that have no bridge timeout (the
+ * Fallback on-screen countdown, mirroring the server-side bridge timeout
+ * (`DEFAULT_ASK_USER_TIMEOUT_MS`). Only used when the producer did not tell us
+ * its own deadline — a mount-relative countdown restarts on every remount, so
+ * `deadlineAt` is always preferred. Hosts that have no bridge timeout (the
* builtin surfaces) pass `undefined` to disable the countdown entirely.
*/
export const DEFAULT_COUNTDOWN_MS = 10 * 60 * 1000;
+/**
+ * How far ahead of the producer's deadline the timeout fallback submits.
+ *
+ * The producer's bridge stops waiting exactly at the deadline and its
+ * long-poll stops listening with it, so an answer published after that point
+ * can never be acknowledged. The lead only has to cover publishing the answer
+ * and the producer picking it off the stream — every millisecond beyond that
+ * is answering time taken from the user, who is still looking at a question
+ * the countdown says they may answer.
+ */
+export const AUTO_SUBMIT_LEAD_MS = 5 * 1000;
+
+/**
+ * How long a card stays in the waiting-for-ACK state before the host settles
+ * it. A remote submit is only transport acceptance; the card stays disabled
+ * until the blocked producer echoes, and when the producer is already gone that
+ * echo never comes. The answer was accepted for delivery either way, so the
+ * card settles as answered and leaves the surface — re-offering a question the
+ * user has already answered only invites a duplicate answer.
+ */
+export const SUBMIT_ACK_TIMEOUT_MS = 30 * 1000;
+
+/**
+ * Last-resort release of the form's own `submitting` latch, for the case where
+ * the host never settled the card at all (a submit that never reached a
+ * transport). Deliberately longer than the host's settle budget so the normal
+ * path is always "the card settles and disappears", never "the buttons come
+ * back on a question that is already answered".
+ */
+export const SUBMIT_SETTLE_FALLBACK_MS = 45 * 1000;
+
/** Key under tool message `pluginState` where the in-progress draft lives. */
export const DRAFT_PLUGIN_STATE_KEY = 'askUserDraft';
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/index.ts b/packages/shared-tool-ui/src/AskUserQuestion/index.ts
index 647464c5813..1b120d77388 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/index.ts
+++ b/packages/shared-tool-ui/src/AskUserQuestion/index.ts
@@ -9,6 +9,7 @@ export {
type AskUserQuestionViewProps,
} from './AskUserQuestionView';
export {
+ AUTO_SUBMIT_LEAD_MS,
buildSubmitPayload,
DEFAULT_COUNTDOWN_MS,
DRAFT_PLUGIN_STATE_KEY,
@@ -16,6 +17,8 @@ export {
FREEFORM_PAYLOAD_KEY,
isQuestionAnswered,
readDraft,
+ SUBMIT_ACK_TIMEOUT_MS,
+ SUBMIT_SETTLE_FALLBACK_MS,
SUPPLEMENT_PAYLOAD_KEY,
} from './draft';
export { normalizeAskUserQuestions } from './normalize';
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts
index f6a32b65422..53e6f58c3a3 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts
+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts
@@ -402,3 +402,136 @@ describe('useAskUserForm additional notes', () => {
vi.useRealTimers();
});
});
+
+describe('useAskUserForm producer deadline', () => {
+ const HOUR = 60 * 60 * 1000;
+ const MINUTE = 60 * 1000;
+
+ const renderWithDeadline = (deadlineAt: number | undefined, onInteractionAction: unknown) =>
+ renderHook(() =>
+ useAskUserForm({
+ args: twoQuestionArgs,
+ countdownMs: 10 * MINUTE,
+ deadlineAt,
+ onInteractionAction: onInteractionAction as never,
+ persistedDraft: undefined,
+ writeDraft: vi.fn(),
+ }),
+ );
+
+ it('tracks the producer deadline instead of restarting the countdown on mount', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-22T00:00:00Z'));
+ // Card mounts 9 minutes into a 10-minute producer window (a refresh, a tab
+ // switch, or simply opening the topic late): only 1 minute is left, not 10.
+ const deadlineAt = Date.now() + MINUTE;
+ const hook = renderWithDeadline(deadlineAt, vi.fn().mockResolvedValue(undefined));
+
+ expect(hook.result.current.remainingMs).toBeLessThanOrEqual(MINUTE);
+ expect(hook.result.current.expired).toBe(false);
+
+ act(() => vi.advanceTimersByTime(MINUTE));
+ expect(hook.result.current.expired).toBe(true);
+
+ hook.unmount();
+ vi.useRealTimers();
+ });
+
+ it('leaves the user their answering time and only auto-answers in the last seconds', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-22T00:00:00Z'));
+ const onInteractionAction = vi.fn().mockResolvedValue(undefined);
+ const deadlineAt = Date.now() + MINUTE;
+ const hook = renderWithDeadline(deadlineAt, onInteractionAction);
+
+ // Ten seconds left is still the user's time to answer — nothing may be
+ // submitted on their behalf yet.
+ act(() => vi.advanceTimersByTime(MINUTE - 10_000));
+ expect(onInteractionAction).not.toHaveBeenCalled();
+ expect(hook.result.current.autoSubmitted).toBe(false);
+
+ // Inside the last few seconds the fallback answers, still early enough that
+ // the producer's bridge is listening.
+ act(() => vi.advanceTimersByTime(6000));
+
+ expect(onInteractionAction).toHaveBeenCalledExactlyOnceWith({
+ payload: { 'How broad?': 'Narrow', 'Which mode?': 'Auto' },
+ type: 'submit',
+ });
+ expect(hook.result.current.autoSubmitted).toBe(true);
+ expect(Date.now()).toBeLessThan(deadlineAt);
+
+ hook.unmount();
+ vi.useRealTimers();
+ });
+
+ it('never auto-submits into a producer that already gave up', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-22T00:00:00Z'));
+ const onInteractionAction = vi.fn().mockResolvedValue(undefined);
+ // The producer's bridge timed out an hour ago; anything published now can
+ // never be acknowledged and would freeze the card on `resolving`.
+ const hook = renderWithDeadline(Date.now() - HOUR, onInteractionAction);
+
+ // Well past the mount-relative countdown the card used to restart from.
+ act(() => vi.advanceTimersByTime(15 * MINUTE));
+
+ expect(onInteractionAction).not.toHaveBeenCalled();
+ expect(hook.result.current.expired).toBe(true);
+ // The footer must not promise an answer that is never going to be sent.
+ expect(hook.result.current.autoSubmitted).toBe(false);
+
+ hook.unmount();
+ vi.useRealTimers();
+ });
+
+ it('does not re-offer an answered question while the host is still settling it', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-22T00:00:00Z'));
+ const onInteractionAction = vi.fn().mockResolvedValue(undefined);
+ const hook = renderWithDeadline(Date.now() + 10 * MINUTE, onInteractionAction);
+
+ act(() => hook.result.current.handleToggle(twoQuestionArgs.questions[0], 'Narrow'));
+ act(() => hook.result.current.handleToggle(twoQuestionArgs.questions[1], 'Auto'));
+ await act(async () => {
+ hook.result.current.handleSubmit();
+ });
+
+ // Publishing is only transport acceptance — the card waits.
+ expect(hook.result.current.submitting).toBe(true);
+
+ // The host settles the card at its own 30s budget and takes it off screen.
+ // The form must NOT hand the buttons back at that moment: the question is
+ // answered, and re-offering it invites a duplicate answer.
+ await act(async () => {
+ vi.advanceTimersByTime(31 * 1000);
+ });
+ expect(hook.result.current.submitting).toBe(true);
+ expect(hook.result.current.isSubmitDisabled).toBe(true);
+
+ hook.unmount();
+ vi.useRealTimers();
+ });
+
+ it('releases the latch only as a floor, when nothing ever settled the card', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-22T00:00:00Z'));
+ const onInteractionAction = vi.fn().mockResolvedValue(undefined);
+ const hook = renderWithDeadline(Date.now() + 10 * MINUTE, onInteractionAction);
+
+ act(() => hook.result.current.handleToggle(twoQuestionArgs.questions[0], 'Narrow'));
+ act(() => hook.result.current.handleToggle(twoQuestionArgs.questions[1], 'Auto'));
+ await act(async () => {
+ hook.result.current.handleSubmit();
+ });
+
+ await act(async () => {
+ vi.advanceTimersByTime(46 * 1000);
+ });
+
+ expect(hook.result.current.submitting).toBe(false);
+
+ hook.unmount();
+ vi.useRealTimers();
+ });
+});
diff --git a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts
index 2f49758ae2b..71774b87483 100644
--- a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts
+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts
@@ -1,11 +1,14 @@
import type { BuiltinInterventionProps } from '@lobechat/types';
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
+ AUTO_SUBMIT_LEAD_MS,
buildSubmitPayload,
+ DEFAULT_COUNTDOWN_MS,
FREEFORM_PAYLOAD_KEY,
isQuestionAnswered,
readDraft,
+ SUBMIT_SETTLE_FALLBACK_MS,
SUPPLEMENT_PAYLOAD_KEY,
} from './draft';
import { normalizeAskUserQuestions } from './normalize';
@@ -20,6 +23,14 @@ export interface UseAskUserFormParams {
* `false`, no timer runs) — used by surfaces with no bridge timeout.
*/
countdownMs?: number;
+ /**
+ * The producer's authoritative wall-clock deadline (unix ms) for this
+ * question. The producer owns the clock — it stops waiting at this instant
+ * no matter when the card mounted — so prefer it over `countdownMs`, which
+ * is mount-relative and therefore restarts a full countdown on every
+ * remount / refresh / tab switch.
+ */
+ deadlineAt?: number;
/** Preserve the form but disable every action while a remote submit awaits producer ACK. */
disabled?: boolean;
onInteractionAction?: BuiltinInterventionProps<AskUserQuestionArgs>['onInteractionAction'];
@@ -32,6 +43,12 @@ export interface UseAskUserFormParams {
export interface AskUserFormApi {
activeQuestion?: AskUserQuestionItem;
activeTab: string;
+ /**
+ * The timeout fallback has fired for this card. Distinguishes "we answered
+ * on your behalf" from "the clock ran out and nothing was sent", which the
+ * footer must not conflate — one is an answer, the other is a dead card.
+ */
+ autoSubmitted: boolean;
custom: Record<string, string>;
escapeActive: boolean;
escapeText: string;
@@ -78,6 +95,7 @@ export interface AskUserFormApi {
export const useAskUserForm = ({
args,
countdownMs,
+ deadlineAt,
disabled = false,
onInteractionAction,
persistedDraft,
@@ -98,18 +116,22 @@ export const useAskUserForm = ({
() => initial.supplementActive && !initial.escapeActive,
);
const [submitting, setSubmitting] = useState(false);
+ const [autoSubmitted, setAutoSubmitted] = useState(false);
const [activeTab, setActiveTab] = useState<string>(() => {
// Resume on the first unanswered question rather than always at Q1.
const idx = questions.findIndex((q) => !isQuestionAnswered(q, initial.picks, initial.custom));
return String(idx >= 0 ? idx : 0);
});
- // Countdown is opt-in: only surfaces with a bridge timeout pass `countdownMs`.
- const countdownEnabled = countdownMs != null;
+ // Countdown is opt-in: only surfaces with a bridge timeout pass a clock.
+ const countdownEnabled = countdownMs != null || deadlineAt != null;
- // Mounted-time deadline; server has its own clock and will return isError if
- // it expires first. Drift of a few seconds is fine.
- const deadline = useMemo(() => Date.now() + (countdownMs ?? 0), [countdownMs]);
+ // The producer's deadline wins whenever it sent one: its bridge gives up at
+ // that wall-clock instant regardless of when this card mounted. Re-deriving
+ // the deadline from mount time would hand a remount / refresh / tab switch a
+ // fresh full countdown long after the producer stopped listening.
+ const [mountedAt] = useState(() => Date.now());
+ const deadline = deadlineAt ?? mountedAt + (countdownMs ?? 0);
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!countdownEnabled) return;
@@ -117,10 +139,36 @@ export const useAskUserForm = ({
return () => clearInterval(id);
}, [countdownEnabled]);
const expired = countdownEnabled ? now >= deadline : false;
+ // Bound the lead by the budget so a short countdown can't be swallowed whole
+ // by it — the fallback must still be a timeout, not an instant answer.
+ const leadMs = Math.min(
+ AUTO_SUBMIT_LEAD_MS,
+ Math.floor((countdownMs ?? DEFAULT_COUNTDOWN_MS) / 2),
+ );
+ // Submitting after the producer's own deadline is worse than not submitting:
+ // it has already settled the call and stopped polling, so no ACK can come
+ // back and the card parks on `resolving` with every button disabled. Fire
+ // inside the lead window instead, while the bridge still listens. Without a
+ // producer deadline the clock is only a mount-relative guess, so there is no
+ // authoritative instant to be late for and expiry still triggers it.
+ const autoSubmitDue =
+ countdownEnabled && now >= deadline - leadMs && !(deadlineAt != null && expired);
const hasProviderOwnedOptionIds = questions.some((question) =>
question.options.some((option) => !!option.id),
);
+ // A resolved `onInteractionAction` means the answer was published, not that
+ // the producer consumed it — the card stays disabled until the host settles
+ // it, which normally happens well before this timer and takes the card off
+ // screen entirely. This is only the floor: a submit that never reached a
+ // transport at all would otherwise leave the form latched forever.
+ const ackTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ useEffect(() => () => clearTimeout(ackTimer.current), []);
+ const awaitProducerAck = useCallback(() => {
+ clearTimeout(ackTimer.current);
+ ackTimer.current = setTimeout(() => setSubmitting(false), SUBMIT_SETTLE_FALLBACK_MS);
+ }, []);
+
/**
* Submit `payload` exactly as given. Used by the Submit button (with the
* user's picks/text), the single-select select-to-submit path, and the
@@ -132,12 +180,13 @@ export const useAskUserForm = ({
setSubmitting(true);
try {
await onInteractionAction({ payload, type: 'submit' });
+ awaitProducerAck();
} catch (err) {
console.error('[AskUserQuestion] submit failed:', err);
setSubmitting(false);
}
},
- [disabled, onInteractionAction, submitting],
+ [awaitProducerAck, disabled, onInteractionAction, submitting],
);
const handleToggle = useCallback(
@@ -368,30 +417,34 @@ export const useAskUserForm = ({
setSubmitting(true);
try {
await onInteractionAction({ type: 'skip' });
+ awaitProducerAck();
} catch (err) {
console.error('[AskUserQuestion] skip failed:', err);
setSubmitting(false);
}
- }, [disabled, onInteractionAction, submitting]);
+ }, [awaitProducerAck, disabled, onInteractionAction, submitting]);
const allAnswered = useMemo(
() => questions.every((q) => isQuestionAnswered(q, picks, custom)),
[picks, custom, questions],
);
- // Timeout fallback for legacy question forms: when the countdown hits zero
- // and the user hasn't submitted, fill option 1 of each unanswered question and submit. Beats
- // letting the bridge time out into a `cancelled` isError — the model gets a
- // structured answer it can act on. Single-shot via the `submitting` guard.
+ // Timeout fallback for legacy question forms: shortly BEFORE the deadline,
+ // if the user hasn't submitted, fill option 1 of each unanswered question and
+ // submit. Beats letting the bridge time out into a `cancelled` isError — the
+ // model gets a structured answer it can act on. Single-shot via
+ // `autoSubmitted`, and never fired once `expired`, because an answer the
+ // producer can no longer receive only strands the card.
//
// Escape-mode special case: if the user is in escape mode with non-empty text
// when the clock hits zero, submit that text as-is rather than discarding it.
useEffect(() => {
- if (!expired || submitting || disabled || questions.length === 0) return;
+ if (!autoSubmitDue || autoSubmitted || submitting || disabled || questions.length === 0) return;
// A stable id means this is a provider-owned choice (permission/plan or a
// newer exact-id question). Never infer consent by selecting option one:
// let the producer timeout/cancel fail closed.
if (hasProviderOwnedOptionIds) return;
+ setAutoSubmitted(true);
if (escapeActive && escapeAvailable && escapeText.trim().length > 0) {
void submitWith({ [FREEFORM_PAYLOAD_KEY]: escapeText.trim() });
return;
@@ -412,7 +465,8 @@ export const useAskUserForm = ({
}
void submitWith(fallback);
}, [
- expired,
+ autoSubmitDue,
+ autoSubmitted,
submitting,
disabled,
questions,
@@ -439,6 +493,7 @@ export const useAskUserForm = ({
return {
activeQuestion,
activeTab,
+ autoSubmitted,
custom,
escapeActive: inEscape,
escapeText,
diff --git a/packages/types/src/agent/heterogeneousIntervention.ts b/packages/types/src/agent/heterogeneousIntervention.ts
index ab5c0549abf..6ab3273b728 100644
--- a/packages/types/src/agent/heterogeneousIntervention.ts
+++ b/packages/types/src/agent/heterogeneousIntervention.ts
@@ -74,3 +74,37 @@ export interface HeterogeneousAgentInterventionResolutionPayload {
/** Question text (or a reserved form key) to freeform text or exact option values. */
result?: HeterogeneousAgentInterventionResult;
}
+
+/**
+ * Producer-stamped wall-clock deadline (unix ms) carried on the tool row's
+ * `pluginState.heterogeneousIntervention`, and mirrored onto the folded tool
+ * entry as `result.state`. Both shapes are read the same way.
+ */
+export const readHeterogeneousInterventionDeadline = (state: unknown): number | undefined => {
+ const deadline = (
+ state as { heterogeneousIntervention?: { deadline?: unknown } } | null | undefined
+ )?.heterogeneousIntervention?.deadline;
+ return typeof deadline === 'number' ? deadline : undefined;
+};
+
+/**
+ * True once the producer has stopped waiting for this answer.
+ *
+ * The deadline is the producer's own: its ask-user bridge deletes the pending
+ * entry at exactly that instant and its long-poll stops listening with it, so
+ * past the deadline "nobody is waiting for this answer" is a fact, not a guess.
+ * A question in that state must never be offered as answerable — submitting
+ * into it cannot be received, and asking the user to act on it is asking for
+ * work that will be thrown away.
+ *
+ * Unknown deadline (local desktop runs, rows written before the producer
+ * stamped one) returns false: without the producer's clock we cannot claim it
+ * gave up.
+ */
+export const isHeterogeneousInterventionExpired = (
+ state: unknown,
+ now: number = Date.now(),
+): boolean => {
+ const deadline = readHeterogeneousInterventionDeadline(state);
+ return deadline !== undefined && now >= deadline;
+};
diff --git a/src/features/Conversation/AssistantTurnSettledWatcher.tsx b/src/features/Conversation/AssistantTurnSettledWatcher.tsx
index 3cd6da15dd9..d292fe07521 100644
--- a/src/features/Conversation/AssistantTurnSettledWatcher.tsx
+++ b/src/features/Conversation/AssistantTurnSettledWatcher.tsx
@@ -7,6 +7,7 @@ import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { type Operation, type OperationType } from '@/store/chat/slices/operation/types';
+import { useUnexpiredInterventions } from './hooks/useDeadlineClock';
import {
contextSelectors,
conversationSelectors,
@@ -14,6 +15,7 @@ import {
messageStateSelectors,
useConversationStore,
} from './store';
+import { isSamePendingInterventionList } from './store/slices/data/pendingInterventions';
const log = debug('lobe-render:features:Conversation');
@@ -67,9 +69,11 @@ const AssistantTurnSettledWatcher = () => {
: false,
);
- const pendingInterventionCount = useConversationStore(
- (s) => dataSelectors.pendingInterventions(s).length,
- );
+ // Same list the InterventionBar shows: an expired card must not keep the turn
+ // counted as waiting on the user just because nothing re-ran the selector.
+ const pendingInterventionCount = useUnexpiredInterventions(
+ useConversationStore(dataSelectors.pendingInterventions, isSamePendingInterventionList),
+ ).length;
const armedSettledMessageIdRef = useRef<string>(undefined);
const firedSettledMessageIdRef = useRef<string>(undefined);
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 874ecffcc37..de7b3ab2552 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -29,6 +29,7 @@ import { fileChatSelectors, useFileStore } from '@/store/file';
import { buildMessageContextSelections } from '../../ChatInput/utils/contextSelections';
import WideScreenContainer from '../../WideScreenContainer';
+import { useUnexpiredInterventions } from '../hooks/useDeadlineClock';
import InterventionBar from '../InterventionBar';
import {
dataSelectors,
@@ -36,6 +37,7 @@ import {
useConversationStore,
useConversationStoreApi,
} from '../store';
+import { isSamePendingInterventionList } from '../store/slices/data/pendingInterventions';
import TodoProgress from '../TodoProgress';
import InputCompletionErrorAlert from './InputCompletionErrorAlert';
import LinkedGoalTray from './LinkedGoalTray';
@@ -262,15 +264,13 @@ const ChatInput = memo<ChatInputProps>(
// Pending interventions — use custom equality to prevent infinite re-render loop.
// The selector creates new array/object refs each call; without equality check,
// any store update → new ref → re-render → Intervention's store writes → loop.
- const pendingInterventions = useConversationStore(
+ const selectedInterventions = useConversationStore(
dataSelectors.pendingInterventions,
- (a, b) => {
- if (a.length !== b.length) return false;
- return a.every(
- (item, i) => item.toolCallId === b[i].toolCallId && item.requestArgs === b[i].requestArgs,
- );
- },
+ isSamePendingInterventionList,
);
+ // The selector only re-runs on store changes; drop a card the moment its
+ // producer stops waiting even when nothing in the store moves.
+ const pendingInterventions = useUnexpiredInterventions(selectedInterventions);
const hasPendingInterventions = pendingInterventions.length > 0;
// Send message error from ConversationStore
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/RejectedResponse.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/RejectedResponse.tsx
index 6394457ea38..4c36ea89aca 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/RejectedResponse.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/RejectedResponse.tsx
@@ -30,17 +30,22 @@ interface RejectedResponseProps {
* rejecting the tool call — render a neutral note, not a warning.
*/
skipped?: boolean;
+ /**
+ * The producer stopped waiting before anyone answered. Neutral like a skip:
+ * nothing went wrong and nobody made a choice.
+ */
+ timedOut?: boolean;
}
-const RejectedResponse = memo<RejectedResponseProps>(({ apiName, reason, skipped }) => {
+const RejectedResponse = memo<RejectedResponseProps>(({ apiName, reason, skipped, timedOut }) => {
const { t } = useTranslation('chat');
- const copyKey = resolveRejectedCopyKey({ apiName, reason, skipped });
+ const copyKey = resolveRejectedCopyKey({ apiName, reason, skipped, timedOut });
return (
<Flexbox className={styles.container} gap={8}>
<Flexbox horizontal align={'center'} gap={8}>
- {skipped ? (
+ {skipped || timedOut ? (
<Icon color={cssVar.colorTextTertiary} icon={CornerUpRight} size={16} />
) : (
<Icon color={cssVar.colorWarning} icon={AlertTriangle} size={16} />
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx
index 1678abf0aa2..82a252e30d9 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx
@@ -4,6 +4,7 @@ import { safeParsePartialJSON } from '@lobechat/utils';
import { Flexbox } from '@lobehub/ui';
import { memo, Suspense } from 'react';
+import { useIsTimedOutUnanswered } from '../../../../hooks/useDeadlineClock';
import AbortResponse from './AbortResponse';
import LoadingPlaceholder from './LoadingPlaceholder';
import RejectedResponse from './RejectedResponse';
@@ -50,11 +51,23 @@ const Render = memo<RenderProps>(
isToolCalling,
showCustomToolRender,
}) => {
+ // A question whose producer stopped waiting is no longer offered as a card
+ // (`getPendingInterventions` drops it), so the inline row is the only place
+ // left to say what happened — returning null here would leave a silent gap
+ // where the tool call was.
+ // Live: flips at the producer's deadline even when nothing else re-renders
+ // this row, so the row speaks up the moment the card leaves the screen.
+ const timedOut = useIsTimedOutUnanswered(intervention, result?.state);
+
// Pending interventions are rendered in the bottom InterventionBar, not inline
- if (toolMessageId && intervention?.status === 'pending' && !disableEditing) {
+ if (!timedOut && toolMessageId && intervention?.status === 'pending' && !disableEditing) {
return null;
}
+ if (timedOut) {
+ return <RejectedResponse timedOut apiName={apiName} />;
+ }
+
if (intervention?.status === 'rejected') {
return (
<RejectedResponse
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/resolveRejectedCopyKey.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/resolveRejectedCopyKey.test.ts
index e6fa6d04aae..be3f4d6ddc3 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/resolveRejectedCopyKey.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/resolveRejectedCopyKey.test.ts
@@ -32,4 +32,18 @@ describe('resolveRejectedCopyKey', () => {
'tool.intervention.rejectedWithReason',
);
});
+
+ it('states a producer timeout as its own outcome, not as a user decision', () => {
+ // A timeout is nobody's choice. Falling through to the skip or rejection
+ // copy would tell the user they declined a question they never saw in time.
+ expect(resolveRejectedCopyKey({ apiName: 'askUserQuestion', timedOut: true })).toBe(
+ 'tool.intervention.questionTimedOut',
+ );
+ expect(
+ resolveRejectedCopyKey({ apiName: 'askUserQuestion', skipped: true, timedOut: true }),
+ ).toBe('tool.intervention.questionTimedOut');
+ expect(resolveRejectedCopyKey({ reason: 'not safe', timedOut: true })).toBe(
+ 'tool.intervention.questionTimedOut',
+ );
+ });
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/resolveRejectedCopyKey.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/resolveRejectedCopyKey.ts
index 750af19b96c..9d1a673f97f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/resolveRejectedCopyKey.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/resolveRejectedCopyKey.ts
@@ -9,10 +9,13 @@ interface ResolveRejectedCopyKeyInput {
apiName?: string;
reason?: string;
skipped?: boolean;
+ /** The producer stopped waiting before anyone answered. */
+ timedOut?: boolean;
}
/**
- * Picks the i18n key for a rejected tool intervention: user skips render as a
+ * Picks the i18n key for a rejected tool intervention: a producer timeout
+ * renders as a neutral note stating nobody answered, user skips render as a
* neutral note (question-specific for ask surfaces), true rejections keep the
* warning copy.
*/
@@ -20,11 +23,17 @@ export const resolveRejectedCopyKey = ({
apiName,
reason,
skipped,
+ timedOut,
}: ResolveRejectedCopyKeyInput):
| 'tool.intervention.questionSkipped'
+ | 'tool.intervention.questionTimedOut'
| 'tool.intervention.rejectedWithReason'
| 'tool.intervention.toolRejected'
| 'tool.intervention.toolSkipped' => {
+ // A timeout is nobody's decision — it outranks the skip/reject copy, which
+ // would otherwise blame the user for a question they were never shown in time.
+ if (timedOut) return 'tool.intervention.questionTimedOut';
+
if (skipped)
return apiName === ASK_USER_QUESTION_API_NAME
? 'tool.intervention.questionSkipped'
diff --git a/src/features/Conversation/hooks/useDeadlineClock.test.ts b/src/features/Conversation/hooks/useDeadlineClock.test.ts
new file mode 100644
index 00000000000..2757c1efda0
--- /dev/null
+++ b/src/features/Conversation/hooks/useDeadlineClock.test.ts
@@ -0,0 +1,119 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type PendingIntervention } from '../store/slices/data/pendingInterventions';
+import { useIsTimedOutUnanswered, useUnexpiredInterventions } from './useDeadlineClock';
+
+const card = (toolCallId: string, deadline?: number): PendingIntervention => ({
+ apiName: 'askUserQuestion',
+ deadline,
+ identifier: 'claude-code',
+ intervention: { status: 'pending' },
+ requestArgs: '{}',
+ toolCallId,
+ toolMessageId: `tool-${toolCallId}`,
+});
+
+describe('useUnexpiredInterventions', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-09-22T00:00:00Z'));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('drops a mounted card the moment its producer deadline passes, with no store change', () => {
+ // Regression: the pending list is recomputed only on store updates. A card
+ // whose form never writes at expiry (provider-owned options skip the
+ // auto-answer) stayed on screen, unanswerable, until some unrelated update.
+ const interventions = [
+ card('expiring', Date.now() + 10_000),
+ card('later', Date.now() + 60_000),
+ ];
+ const hook = renderHook(({ list }) => useUnexpiredInterventions(list), {
+ initialProps: { list: interventions },
+ });
+
+ expect(hook.result.current.map((item) => item.toolCallId)).toEqual(['expiring', 'later']);
+
+ act(() => vi.advanceTimersByTime(9999));
+ expect(hook.result.current.map((item) => item.toolCallId)).toEqual(['expiring', 'later']);
+
+ act(() => vi.advanceTimersByTime(1));
+ expect(hook.result.current.map((item) => item.toolCallId)).toEqual(['later']);
+
+ // Re-arms for the next deadline on its own.
+ act(() => vi.advanceTimersByTime(50_000));
+ expect(hook.result.current).toEqual([]);
+ });
+
+ it('keeps cards whose producer never stamped a deadline', () => {
+ const hook = renderHook(() => useUnexpiredInterventions([card('no-deadline')]));
+
+ act(() => vi.advanceTimersByTime(24 * 60 * 60 * 1000));
+
+ expect(hook.result.current.map((item) => item.toolCallId)).toEqual(['no-deadline']);
+ });
+
+ it('still expires the card when the timer fires a hair before the deadline', () => {
+ const deadline = Date.now() + 5000;
+ const hook = renderHook(() => useUnexpiredInterventions([card('edge', deadline)]));
+
+ // Simulate a timer that runs 1ms early: the wall clock reads deadline - 1
+ // when the callback executes. The card must still leave, or the next
+ // deadline would not change and nothing would re-arm.
+ const early = vi.spyOn(Date, 'now').mockReturnValue(deadline - 1);
+ act(() => vi.advanceTimersToNextTimer());
+ early.mockRestore();
+
+ expect(hook.result.current).toEqual([]);
+ });
+});
+
+describe('useIsTimedOutUnanswered', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-09-22T00:00:00Z'));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ const stateWith = (deadline: number) => ({ heterogeneousIntervention: { deadline } });
+
+ it('flips a mounted row to timed-out at the deadline, with no re-render from outside', () => {
+ // Regression: once the card leaves at the deadline, the inline row is the
+ // only place left to say what happened — and it only re-evaluated when
+ // something else rendered it, so it sat blank.
+ const state = stateWith(Date.now() + 8000);
+ const hook = renderHook(() => useIsTimedOutUnanswered({ status: 'pending' }, state));
+
+ expect(hook.result.current).toBe(false);
+ act(() => vi.advanceTimersByTime(8000));
+ expect(hook.result.current).toBe(true);
+ });
+
+ it('never labels an in-flight answer as timed out', () => {
+ const hook = renderHook(() =>
+ useIsTimedOutUnanswered({ resolving: true, status: 'pending' }, stateWith(Date.now() - 1000)),
+ );
+
+ expect(hook.result.current).toBe(false);
+ });
+
+ it('ignores settled interventions and rows without a producer deadline', () => {
+ const settled = renderHook(() =>
+ useIsTimedOutUnanswered({ status: 'approved' }, stateWith(Date.now() - 1000)),
+ );
+ const noDeadline = renderHook(() => useIsTimedOutUnanswered({ status: 'pending' }, {}));
+
+ expect(settled.result.current).toBe(false);
+ expect(noDeadline.result.current).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/hooks/useDeadlineClock.ts b/src/features/Conversation/hooks/useDeadlineClock.ts
new file mode 100644
index 00000000000..e717ffc3696
--- /dev/null
+++ b/src/features/Conversation/hooks/useDeadlineClock.ts
@@ -0,0 +1,73 @@
+import { readHeterogeneousInterventionDeadline, type ToolIntervention } from '@lobechat/types';
+import { useEffect, useMemo, useState } from 'react';
+
+import { type PendingIntervention } from '../store/slices/data/pendingInterventions';
+
+/**
+ * A clock that ticks exactly when the next of `deadlines` passes, and at no
+ * other time.
+ *
+ * `getPendingInterventions` drops a question whose producer deadline has
+ * passed, but only when something re-runs it — selector results are memoized
+ * on store identity, and nothing in the store changes at the deadline. A card
+ * whose form never writes at expiry (provider-owned options deliberately skip
+ * the auto-answer) would otherwise stay on screen, unanswerable, until some
+ * unrelated update happened to recompute the list.
+ *
+ * The returned `now` only moves forward at a deadline, so it may lag the wall
+ * clock in between; that is safe because anything already past its deadline
+ * when the list was selected was dropped by the selector itself.
+ */
+export const useDeadlineClock = (deadlines: readonly (number | undefined)[]): number => {
+ const [now, setNow] = useState(() => Date.now());
+
+ let next: number | undefined;
+ for (const deadline of deadlines) {
+ if (deadline !== undefined && deadline > now && (next === undefined || deadline < next)) {
+ next = deadline;
+ }
+ }
+
+ useEffect(() => {
+ if (next === undefined) return;
+ // Clamp forward to the deadline itself: a timer that fires a hair early
+ // must still expire the card, or `next` would not change and nothing would
+ // re-arm.
+ const id = setTimeout(() => setNow(Math.max(Date.now(), next)), Math.max(0, next - Date.now()));
+ return () => clearTimeout(id);
+ }, [next]);
+
+ return now;
+};
+
+export const isUnexpiredAt = (now: number) => (item: Pick<PendingIntervention, 'deadline'>) =>
+ item.deadline === undefined || item.deadline > now;
+
+/** The pending list with every card dropped the instant its producer stops waiting. */
+export const useUnexpiredInterventions = (
+ interventions: PendingIntervention[],
+): PendingIntervention[] => {
+ const now = useDeadlineClock(interventions.map((item) => item.deadline));
+ return useMemo(() => interventions.filter(isUnexpiredAt(now)), [interventions, now]);
+};
+
+/**
+ * Whether a tool row should read "timed out before it was answered" — live.
+ *
+ * Once `useUnexpiredInterventions` takes the card off screen at the deadline,
+ * the inline row is the only place left to say what happened, and it has the
+ * same problem the card list had: it only re-evaluates when something renders
+ * it. A card whose answer is already in flight (`resolving`) was answered and
+ * is never labelled as timed out.
+ */
+export const useIsTimedOutUnanswered = (
+ intervention: ToolIntervention | undefined,
+ state: unknown,
+): boolean => {
+ const deadline =
+ intervention?.status === 'pending' && !intervention.resolving
+ ? readHeterogeneousInterventionDeadline(state)
+ : undefined;
+ const now = useDeadlineClock([deadline]);
+ return deadline !== undefined && now >= deadline;
+};
diff --git a/src/features/Conversation/store/slices/data/pendingInterventions.test.ts b/src/features/Conversation/store/slices/data/pendingInterventions.test.ts
index 7918afc1f9b..73cfd03b04a 100644
--- a/src/features/Conversation/store/slices/data/pendingInterventions.test.ts
+++ b/src/features/Conversation/store/slices/data/pendingInterventions.test.ts
@@ -221,4 +221,77 @@ describe('canApproveInterventionBatch', () => {
surface: 'form',
});
});
+
+ describe('a question whose producer stopped waiting', () => {
+ const HOUR = 60 * 60 * 1000;
+
+ const askUserToolRow = (deadline: number): UIChatMessage =>
+ ({
+ id: 'tool-expired',
+ parentId: 'assistant-1',
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ id: 'call-expired',
+ identifier: 'claude-code',
+ type: 'builtin',
+ },
+ pluginIntervention: { status: 'pending' },
+ pluginState: { heterogeneousIntervention: { deadline } },
+ role: 'tool',
+ tool_call_id: 'call-expired',
+ }) as any;
+
+ const askUserGroup = (deadline: number): UIChatMessage =>
+ ({
+ children: [
+ {
+ tools: [
+ {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ id: 'call-expired',
+ identifier: 'claude-code',
+ intervention: { status: 'pending' },
+ result: {
+ content: '',
+ id: 'tool-expired',
+ state: { heterogeneousIntervention: { deadline } },
+ },
+ result_msg_id: 'tool-expired',
+ type: 'builtin',
+ },
+ ],
+ },
+ ],
+ id: 'assistant-1',
+ role: 'assistantGroup',
+ }) as any;
+
+ it('is no longer offered as an answerable card — standalone tool row', () => {
+ // Past the producer's deadline its bridge has deleted the pending entry
+ // and its long-poll has stopped listening. Offering the card would ask the
+ // user to answer into a void.
+ expect(getPendingInterventions([askUserToolRow(Date.now() - HOUR)])).toHaveLength(0);
+ expect(getPendingInterventions([askUserToolRow(Date.now() + HOUR)])).toHaveLength(1);
+ });
+
+ it('is no longer offered as an answerable card — folded tool entry', () => {
+ expect(getPendingInterventions([askUserGroup(Date.now() - HOUR)])).toHaveLength(0);
+ expect(getPendingInterventions([askUserGroup(Date.now() + HOUR)])).toHaveLength(1);
+ });
+
+ it('carries the producer deadline so consumers can expire the card live', () => {
+ const deadline = Date.now() + HOUR;
+ expect(getPendingInterventions([askUserToolRow(deadline)])[0].deadline).toBe(deadline);
+ expect(getPendingInterventions([askUserGroup(deadline)])[0].deadline).toBe(deadline);
+ });
+
+ it('keeps a card whose producer never stamped a deadline', () => {
+ // Without the producer's clock we cannot claim it gave up.
+ const noDeadline = askUserToolRow(0);
+ delete (noDeadline as any).pluginState;
+ expect(getPendingInterventions([noDeadline])).toHaveLength(1);
+ });
+ });
});
diff --git a/src/features/Conversation/store/slices/data/pendingInterventions.ts b/src/features/Conversation/store/slices/data/pendingInterventions.ts
index b84199179b0..b7b7bdde5de 100644
--- a/src/features/Conversation/store/slices/data/pendingInterventions.ts
+++ b/src/features/Conversation/store/slices/data/pendingInterventions.ts
@@ -1,6 +1,8 @@
import {
type ChatToolPayloadWithResult,
classifyToolInterventionPresentation,
+ isHeterogeneousInterventionExpired,
+ readHeterogeneousInterventionDeadline,
type ToolIntervention,
type UIChatMessage,
} from '@lobechat/types';
@@ -19,6 +21,12 @@ export interface PendingIntervention {
*/
assistantGroupId?: string;
batchId?: string;
+ /**
+ * Producer's wall-clock deadline (unix ms) when it stamped one. Carried so
+ * consumers can drop the card the moment it passes — the list itself is only
+ * recomputed when the store changes, and nothing changes at the deadline.
+ */
+ deadline?: number;
identifier: string;
intervention: ToolIntervention & { status: 'pending' };
operationId?: string;
@@ -27,6 +35,23 @@ export interface PendingIntervention {
toolMessageId: string;
}
+/**
+ * Equality for selector results. The selector builds fresh arrays on every
+ * store update; comparing by identity would re-render (and let interventions
+ * write back into the store) in a loop.
+ */
+export const isSamePendingInterventionList = (
+ a: PendingIntervention[],
+ b: PendingIntervention[],
+): boolean =>
+ a.length === b.length &&
+ a.every(
+ (item, i) =>
+ item.toolCallId === b[i].toolCallId &&
+ item.requestArgs === b[i].requestArgs &&
+ item.deadline === b[i].deadline,
+ );
+
export const getPendingInterventions = (
displayMessages: UIChatMessage[],
): PendingIntervention[] => {
@@ -38,13 +63,18 @@ export const getPendingInterventions = (
msg.role === 'tool' &&
msg.pluginIntervention?.status === 'pending' &&
msg.plugin &&
- !msg.id.startsWith('tmp_')
+ !msg.id.startsWith('tmp_') &&
+ // Past the producer's own deadline nobody is waiting for this answer.
+ // Keeping it in the pending list would put an unanswerable card in front
+ // of the user on every surface that reads this list.
+ !isHeterogeneousInterventionExpired(msg.pluginState)
) {
pending.push({
apiName: msg.plugin.apiName,
// A standalone tool row parents directly to its calling assistant.
assistantGroupId: msg.parentId,
batchId: msg.pluginIntervention.batchId,
+ deadline: readHeterogeneousInterventionDeadline(msg.pluginState),
identifier: msg.plugin.identifier,
intervention: msg.pluginIntervention as ToolIntervention & { status: 'pending' },
operationId: msg.pluginIntervention.operationId,
@@ -141,12 +171,16 @@ const collectPendingTools = (
if (
tool.intervention?.status === 'pending' &&
tool.result_msg_id &&
- !tool.result_msg_id.startsWith('tmp_')
+ !tool.result_msg_id.startsWith('tmp_') &&
+ // Same rule as the standalone tool row; the folded entry mirrors the
+ // producer's deadline onto `result.state`.
+ !isHeterogeneousInterventionExpired(tool.result?.state)
) {
pending.push({
apiName: tool.apiName,
assistantGroupId,
batchId: tool.intervention.batchId,
+ deadline: readHeterogeneousInterventionDeadline(tool.result?.state),
identifier: tool.identifier,
intervention: tool.intervention as ToolIntervention & { status: 'pending' },
operationId: tool.intervention.operationId,
diff --git a/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.ts b/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.ts
index 5cb8dfc4662..c3fcbd772f4 100644
--- a/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.ts
+++ b/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.ts
@@ -2,6 +2,7 @@ import { type UIChatMessage } from '@lobechat/types';
import { useMemo } from 'react';
import { useShallow } from 'zustand/react/shallow';
+import { isUnexpiredAt, useDeadlineClock } from '@/features/Conversation/hooks/useDeadlineClock';
import {
getPendingInterventions,
type PendingIntervention,
@@ -122,8 +123,25 @@ export const useGlobalPendingApprovals = (): GlobalApprovalGroup[] => {
[activeAgentId, portalTopicId],
);
- return useMemo(
+ const groups = useMemo(
() => collectGlobalApprovals(dbMessagesMap, operations, activeKey, portalKey),
[dbMessagesMap, operations, activeKey, portalKey],
);
+
+ // The island reads the same pending list, recomputed only on store changes.
+ // Drop each card the moment its producer stops waiting — and a group with it
+ // once nothing answerable is left.
+ const now = useDeadlineClock(
+ groups.flatMap((group) => group.interventions.map((item) => item.deadline)),
+ );
+ return useMemo(
+ () =>
+ groups
+ .map((group) => ({
+ ...group,
+ interventions: group.interventions.filter(isUnexpiredAt(now)),
+ }))
+ .filter((group) => group.interventions.length > 0),
+ [groups, now],
+ );
};
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index 001c3e6221e..f99e8c43a8d 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -11,6 +11,7 @@ import { useUserStore } from '@/store/user';
import { useChatStore } from '../../../../store';
import { messageMapKey } from '../../../../utils/messageMapKey';
+import { dbMessageSelectors } from '../../../message/selectors';
import * as agentDispatcher from '../dispatch/agentDispatcher';
import { createMockMessage, createMockResolvedAgentConfig, TEST_IDS } from './fixtures';
import { resetTestEnvironment } from './helpers';
@@ -3581,6 +3582,7 @@ describe('ConversationControl actions', () => {
.spyOn(result.current, 'optimisticUpdateMessagePlugin')
.mockResolvedValue(undefined);
vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
+ const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');
const updateTopicStatusSpy = vi
.spyOn(result.current, 'updateTopicStatus')
.mockResolvedValue(undefined as any);
@@ -3598,11 +3600,32 @@ describe('ConversationControl actions', () => {
// Remote publish is only transport acceptance: keep the form pending,
// mark it resolving, and use the empty global-state fallback context.
- expect(pluginSpy).toHaveBeenCalledWith(
- 'tool-msg-1',
- { intervention: { resolving: true, status: 'pending' } },
+ // The hint is dispatched locally onto both projections the UI reads and
+ // deliberately never persisted — a refresh must recover an actionable
+ // card rather than a permanently disabled one.
+ const resolvingIntervention = { resolving: true, status: 'pending' };
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ {
+ id: 'tool-msg-1',
+ type: 'updateMessage',
+ value: { pluginIntervention: resolvingIntervention },
+ },
{},
);
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ {
+ id: assistantMessage.id,
+ tool_call_id: 'cc_call_1',
+ type: 'updateMessageTools',
+ value: { intervention: resolvingIntervention },
+ },
+ {},
+ );
+ expect(pluginSpy).not.toHaveBeenCalledWith(
+ 'tool-msg-1',
+ { intervention: expect.objectContaining({ resolving: true }) },
+ expect.anything(),
+ );
expect(updateTopicStatusSpy).not.toHaveBeenCalled();
// Remote tRPC submit fires with the (stale) resolved operationId + cancel;
@@ -3645,11 +3668,255 @@ describe('ConversationControl actions', () => {
});
expect(pluginSpy).toHaveBeenLastCalledWith(
'tool-msg-1',
- { intervention: { status: 'pending' } },
+ // A failed publish rolls back to pending AND drops the in-flight hint,
+ // so the card the user has to retry is actionable again.
+ { intervention: { resolving: false, status: 'pending' } },
{},
);
});
+ it('settles a remote card that the producer never acknowledges', async () => {
+ // Regression: the ask-user bridge stops waiting at its own deadline and
+ // its long-poll stops listening with it, so an answer published after
+ // that point can never be echoed back. The card was left on
+ // `pending + resolving` forever — every button disabled, the submit
+ // button spinning, with no way out but a refresh. The server accepted the
+ // answer, so the card settles as answered and leaves the surface; it is
+ // never re-offered, which would invite a duplicate answer.
+ vi.useFakeTimers();
+ const { result } = renderHook(() => useChatStore());
+
+ const agentId = 'hetero-agent';
+ const topicId = 'hetero-topic';
+ const chatKey = messageMapKey({ agentId, topicId });
+ const assistantMessage = createMockMessage({ id: 'assistant-msg-1', role: 'assistant' });
+ const toolMessage = createMockMessage({
+ id: 'tool-msg-1',
+ parentId: assistantMessage.id,
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ identifier: 'lobe-claude-code',
+ type: 'default',
+ },
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ tool_call_id: 'cc_call_1',
+ } as any);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeThreadId: undefined,
+ activeTopicId: topicId,
+ dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },
+ messagesMap: { [chatKey]: [assistantMessage, toolMessage] },
+ // A GC'd op routes to the remote transport, the path that waits for
+ // a producer ACK.
+ messageOperationMap: { [assistantMessage.id]: 'gc-op-id' },
+ operations: {},
+ });
+ });
+
+ const pluginSpy = vi
+ .spyOn(result.current, 'optimisticUpdateMessagePlugin')
+ .mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'updateTopicStatus').mockResolvedValue(undefined as any);
+ vi.spyOn(messageService, 'updateMessagePluginState').mockResolvedValue({
+ messages: [],
+ success: true,
+ });
+
+ await act(async () => {
+ await result.current.submitHeteroIntervention('tool-msg-1', 'submit', { q: 'a' });
+ });
+
+ const resolvingMessage = dbMessageSelectors.getDbMessageById('tool-msg-1')(
+ useChatStore.getState(),
+ );
+ expect(resolvingMessage?.pluginIntervention?.resolving).toBe(true);
+ pluginSpy.mockClear();
+
+ // No ACK ever arrives.
+ await act(async () => {
+ vi.advanceTimersByTime(30 * 1000);
+ });
+
+ expect(pluginSpy).toHaveBeenCalledWith(
+ 'tool-msg-1',
+ { intervention: { resolving: false, status: 'approved' } },
+ expect.anything(),
+ );
+
+ // The card must leave the surface on the local write alone. The durable
+ // write is best-effort; waiting on its echo is what left the card on
+ // screen in the first place.
+ const settled = dbMessageSelectors.getDbMessageById('tool-msg-1')(useChatStore.getState());
+ expect(settled?.pluginIntervention?.status).toBe('approved');
+ expect(settled?.pluginIntervention?.resolving).toBe(false);
+
+ vi.useRealTimers();
+ });
+
+ it.each([
+ {
+ actionType: 'skip' as const,
+ expected: {
+ rejectedReason: 'User skipped',
+ resolving: false,
+ skipped: true,
+ status: 'rejected',
+ },
+ },
+ {
+ actionType: 'cancel' as const,
+ expected: {
+ rejectedReason: 'User cancelled',
+ resolving: false,
+ skipped: false,
+ status: 'rejected',
+ },
+ },
+ ])(
+ 'settles an unacknowledged $actionType as the decision the user made, not as an answer',
+ async ({ actionType, expected }) => {
+ // Regression: the settle timer runs for every remote action but always
+ // stamped `approved`, so an accepted skip/cancel that never got a
+ // producer ACK was rendered and persisted as an approved answer.
+ vi.useFakeTimers();
+ const { result } = renderHook(() => useChatStore());
+
+ const agentId = 'hetero-agent';
+ const topicId = 'hetero-topic';
+ const chatKey = messageMapKey({ agentId, topicId });
+ const assistantMessage = createMockMessage({
+ id: `assistant-${actionType}`,
+ role: 'assistant',
+ });
+ const toolMessage = createMockMessage({
+ id: `tool-${actionType}`,
+ parentId: assistantMessage.id,
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ identifier: 'lobe-claude-code',
+ type: 'default',
+ },
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ tool_call_id: `call-${actionType}`,
+ } as any);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeThreadId: undefined,
+ activeTopicId: topicId,
+ dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },
+ messagesMap: { [chatKey]: [assistantMessage, toolMessage] },
+ messageOperationMap: { [assistantMessage.id]: `gc-op-${actionType}` },
+ operations: {},
+ });
+ });
+
+ const pluginSpy = vi
+ .spyOn(result.current, 'optimisticUpdateMessagePlugin')
+ .mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'updateTopicStatus').mockResolvedValue(undefined as any);
+
+ await act(async () => {
+ await result.current.submitHeteroIntervention(toolMessage.id, actionType);
+ });
+ pluginSpy.mockClear();
+
+ await act(async () => {
+ vi.advanceTimersByTime(30 * 1000);
+ });
+
+ expect(pluginSpy).toHaveBeenCalledWith(
+ toolMessage.id,
+ { intervention: expected },
+ expect.anything(),
+ );
+ const settled = dbMessageSelectors.getDbMessageById(toolMessage.id)(
+ useChatStore.getState(),
+ );
+ expect(settled?.pluginIntervention).toMatchObject(expected);
+
+ vi.useRealTimers();
+ },
+ );
+
+ it('leaves an acknowledged card alone when the settle timer fires', async () => {
+ vi.useFakeTimers();
+ const { result } = renderHook(() => useChatStore());
+
+ const agentId = 'hetero-agent';
+ const topicId = 'hetero-topic';
+ const chatKey = messageMapKey({ agentId, topicId });
+ const assistantMessage = createMockMessage({ id: 'assistant-msg-2', role: 'assistant' });
+ const toolMessage = createMockMessage({
+ id: 'tool-msg-2',
+ parentId: assistantMessage.id,
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ identifier: 'lobe-claude-code',
+ type: 'default',
+ },
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ tool_call_id: 'cc_call_2',
+ } as any);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeThreadId: undefined,
+ activeTopicId: topicId,
+ dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },
+ messagesMap: { [chatKey]: [assistantMessage, toolMessage] },
+ messageOperationMap: { [assistantMessage.id]: 'gc-op-id-2' },
+ operations: {},
+ });
+ });
+
+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);
+ vi.spyOn(result.current, 'updateTopicStatus').mockResolvedValue(undefined as any);
+ vi.spyOn(messageService, 'updateMessagePluginState').mockResolvedValue({
+ messages: [],
+ success: true,
+ });
+
+ await act(async () => {
+ await result.current.submitHeteroIntervention('tool-msg-2', 'submit', { q: 'a' });
+ });
+
+ // The producer ACKs and the card goes terminal before the timer fires.
+ act(() => {
+ result.current.internal_dispatchMessage(
+ {
+ id: 'tool-msg-2',
+ type: 'updateMessage',
+ value: { pluginIntervention: { resolving: false, status: 'approved' } },
+ },
+ {},
+ );
+ });
+
+ await act(async () => {
+ vi.advanceTimersByTime(30 * 1000);
+ });
+
+ const settled = dbMessageSelectors.getDbMessageById('tool-msg-2')(useChatStore.getState());
+ expect(settled?.pluginIntervention?.status).toBe('approved');
+
+ vi.useRealTimers();
+ });
+
it('flips topic status on the passed context, NOT the active topic, when submitting from a background conversation', async () => {
// Regression: submitting a hetero intervention from the global approval
// card while the user is viewing a DIFFERENT topic must flip *that card's*
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index 6bdb0e20bb5..4462d3e14be 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -6,6 +6,7 @@ import {
type ConversationContext,
type MessageMetadata,
resolveAgentAgencyConfig,
+ type ToolIntervention,
type UIChatMessage,
} from '@lobechat/types';
import { t } from 'i18next';
@@ -104,6 +105,13 @@ const toHeterogeneousSourceAction = (
}
};
+/**
+ * How long a published-but-unacknowledged hetero intervention stays in the
+ * `resolving` phase before it is settled. Mirrors `SUBMIT_ACK_TIMEOUT_MS` in
+ * `@lobechat/shared-tool-ui/ask-user`.
+ */
+const HETERO_INTERVENTION_ACK_TIMEOUT_MS = 30 * 1000;
+
export const conversationControl = (set: Setter, get: () => ChatStore, _api?: unknown) =>
new ConversationControlActionImpl(set, get, _api);
@@ -417,6 +425,96 @@ export class ConversationControlActionImpl {
return true;
};
+ /**
+ * Write an intervention state onto both projections the UI reads: the tool
+ * row's own `pluginIntervention` (what the pending-card list is built from)
+ * and the parent assistant's tool entry (inline row), so every subscribed
+ * surface agrees immediately.
+ *
+ * Local only. For `resolving` that is the whole point — it describes this
+ * client's in-flight publish, not durable truth, and a slow write could land
+ * after the producer's terminal ACK and resurrect a settled card. For a
+ * terminal settle it is the fast half: the durable write follows separately,
+ * and the card must not wait on it to leave the screen.
+ */
+ #dispatchInterventionState = (
+ toolMessageId: string,
+ patch: Partial<ToolIntervention>,
+ context: OptimisticUpdateContext,
+ ): void => {
+ const message = dbMessageSelectors.getDbMessageById(toolMessageId)(this.#get());
+ if (!message) return;
+
+ const intervention = { ...message.pluginIntervention, ...patch };
+ this.#get().internal_dispatchMessage(
+ { id: toolMessageId, type: 'updateMessage', value: { pluginIntervention: intervention } },
+ context,
+ );
+ if (message.parentId && message.tool_call_id) {
+ this.#get().internal_dispatchMessage(
+ {
+ id: message.parentId,
+ tool_call_id: message.tool_call_id,
+ type: 'updateMessageTools',
+ value: { intervention },
+ },
+ context,
+ );
+ }
+ };
+
+ /**
+ * A remote submit parks the card on `pending + resolving` until the blocked
+ * producer echoes its ACK. That ACK can never arrive when the producer is
+ * already gone — its own ask-user deadline elapsed, its process died, or its
+ * long-poll stopped listening the moment the bridge settled — and nothing
+ * else moves the card off that phase, so every surface reading it stays
+ * permanently non-actionable.
+ *
+ * Settle it after a bounded wait rather than handing the buttons back. The
+ * server accepted the user's decision for delivery, so from their side the
+ * question IS resolved; re-offering it would ask them to decide a second time
+ * and risk a duplicate landing on a producer that already has one. The
+ * terminal state is the one the user chose — an answer settles `approved`, a
+ * skip or cancel settles `rejected` — matching what the local desktop path
+ * stamps immediately. A later real producer result simply overwrites this.
+ */
+ #scheduleHeteroInterventionSettle = (
+ toolMessageId: string,
+ actionType: 'submit' | 'skip' | 'cancel',
+ context: OptimisticUpdateContext,
+ ): void => {
+ const settled: Partial<ToolIntervention> =
+ actionType === 'submit'
+ ? { resolving: false, status: 'approved' }
+ : {
+ rejectedReason: actionType === 'skip' ? 'User skipped' : 'User cancelled',
+ resolving: false,
+ skipped: actionType === 'skip',
+ status: 'rejected',
+ };
+
+ setTimeout(() => {
+ const intervention = dbMessageSelectors.getDbMessageById(toolMessageId)(
+ this.#get(),
+ )?.pluginIntervention;
+ // Anything terminal already won the race — never reopen a settled card.
+ if (intervention?.resolving !== true || intervention.status !== 'pending') return;
+
+ // Write the terminal state onto the projections the surfaces read BEFORE
+ // persisting: `optimisticUpdateMessagePlugin` only reaches the tool row's
+ // top-level `pluginIntervention` (what the card list is built from) once
+ // the server echoes, so a failed or slow write would leave the card on
+ // screen — the exact state this settle exists to end.
+ this.#dispatchInterventionState(toolMessageId, settled, context);
+ void this.#get().optimisticUpdateMessagePlugin(
+ toolMessageId,
+ { intervention: settled },
+ context,
+ );
+ }, HETERO_INTERVENTION_ACK_TIMEOUT_MS);
+ };
+
#writeTopicStatus = (context: ConversationContext, status: ChatTopicStatus): void => {
if (!context.topicId) return;
@@ -1669,33 +1767,15 @@ export class ConversationControlActionImpl {
if (sourceResolution.handled) {
const sourceOptimisticContext: OptimisticUpdateContext = { context: effectiveContext };
- const resolvingIntervention = {
- ...originalIntervention,
- resolving: true,
- status: 'pending' as const,
- };
- this.#get().internal_dispatchMessage(
- {
- id: toolMessageId,
- type: 'updateMessage',
- value: { pluginIntervention: resolvingIntervention },
- },
+ this.#dispatchInterventionState(
+ toolMessageId,
+ { resolving: true, status: 'pending' },
sourceOptimisticContext,
);
- if (toolMessage.parentId) {
- this.#get().internal_dispatchMessage(
- {
- id: toolMessage.parentId,
- tool_call_id: toolCallId,
- type: 'updateMessageTools',
- value: { intervention: resolvingIntervention },
- },
- sourceOptimisticContext,
- );
- }
if (actionType === 'submit') {
await this.setInterventionAnswers(toolMessageId, payload ?? {}, sourceOptimisticContext);
}
+ this.#scheduleHeteroInterventionSettle(toolMessageId, actionType, sourceOptimisticContext);
return;
}
}
@@ -1743,9 +1823,9 @@ export class ConversationControlActionImpl {
// Publishing the user intent is not completion. Keep the interaction
// pending but mark its in-flight phase so a remount/retry cannot present
// an optimistic terminal state before the producer has consumed it.
- await this.#get().optimisticUpdateMessagePlugin(
+ this.#dispatchInterventionState(
toolMessageId,
- { intervention: { resolving: true, status: 'pending' } },
+ { resolving: true, status: 'pending' },
optimisticContext,
);
if (actionType === 'submit') {
@@ -1836,12 +1916,26 @@ export class ConversationControlActionImpl {
toolCallId,
},
);
+ this.#scheduleHeteroInterventionSettle(toolMessageId, actionType, optimisticContext);
}
} catch (err) {
console.error('[submitHeteroIntervention] submitIntervention failed:', err);
+ // Drop the in-flight hint first: the rollback below only reaches
+ // `pluginIntervention` once the server echoes, and a failed publish must
+ // never leave the card disabled waiting on an ACK that was never asked for.
+ if (!isLocalDesktopHetero) {
+ this.#dispatchInterventionState(
+ toolMessageId,
+ { resolving: false, status: 'pending' },
+ optimisticContext,
+ );
+ }
await this.#get().optimisticUpdateMessagePlugin(
toolMessageId,
- { intervention: originalIntervention ?? { status: 'pending' } },
+ // `resolving` is never part of what a rollback restores: it describes
+ // an in-flight publish, and this one just failed. Carrying a hint left
+ // by an earlier attempt would re-disable the card the user must retry.
+ { intervention: { ...(originalIntervention ?? { status: 'pending' }), resolving: false } },
optimisticContext,
);
if (isLocalDesktopHetero) {