diff --git a/README.ja.md b/README.ja.md index af380ca4a..9beebc836 100644 --- a/README.ja.md +++ b/README.ja.md @@ -29,6 +29,8 @@ - [omp](https://github.com/can1357/oh-my-pi) がインストールされ、`PATH` に含まれていること(または `OMP_WEB_OMP_BIN` で指定) - Node.js `>= 22.19.0` +キュー内のフォローアップに対する **Steer** 操作には、`promote_queued_message` RPC コマンドをサポートする omp ランタイムが必要です(omp 18.1.16 では未対応)。古いランタイムではエラーを表示し、メッセージはフォローアップとしてキューに残ります。ompweb が重複したステアリングメッセージを送信することはありません。 + ## クイックスタート **インストールせずに直接実行:** diff --git a/README.md b/README.md index 40720b140..6864c7e1c 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ A clean, modern web UI for the [oh-my-pi (omp)](https://github.com/can1357/oh-my - [omp](https://github.com/can1357/oh-my-pi) installed and available on your `PATH` (or specified via `OMP_WEB_OMP_BIN`) - Node.js `>= 22.19.0` +The **Steer** action on a queued follow-up requires an omp runtime with the `promote_queued_message` RPC command (not available in omp 18.1.16). Older runtimes report an error and leave the message queued as a follow-up; ompweb does not send a duplicate steering message. + ## Quick Start **Run directly without installing:** diff --git a/README.zh-CN.md b/README.zh-CN.md index 70f787eba..beda0aee3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -29,6 +29,8 @@ - 已安装 [omp](https://github.com/can1357/oh-my-pi) 且在 `PATH` 中(或通过 `OMP_WEB_OMP_BIN` 指定路径) - Node.js `>= 22.19.0` +将排队的后续消息转为 **Steer** 需要 omp 运行时支持 `promote_queued_message` RPC 命令(omp 18.1.16 尚不支持)。旧版运行时会返回错误,消息仍作为后续消息排队;ompweb 不会重复发送一条引导消息。 + ## 快速开始 **免安装直接运行:** diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 0cf23a39c..282ec08a7 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -120,9 +120,9 @@ interface Props { modelCapacity?: { contextWindow?: number; maxTokens?: number } | null; /** Generation speed shown in the context ring popover. */ generationSpeed?: GenerationSpeedInfo | null; - /** Remove one queued message from the queue panel (Edit/Delete/Steer). */ + /** Remove one queued message from the queue panel (Edit/Delete). */ onRemoveQueuedMessage?: (text: string) => void; - /** Relabel the first queued follow-up as a steering message. */ + /** Promote the first matching native follow-up into steering. */ onPromoteQueuedToSteer?: (text: string) => void; slashCommands?: SlashCommandInfo[]; slashCommandsLoading?: boolean; diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index a9b403fb5..ca1d78f71 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -129,7 +129,7 @@ function jsonResponse(status, value) { const world = { esInstances: [], calls: [], - holds: [], // { match(method, url), produce: () => Promise<{ status, value }> } + holds: [], // { match(method, url, body), produce: () => Promise<{ status, value }> } sessions: new Map(), // sid -> { leafId, messages, entryIds } agents: new Map(), // sid -> { running, state } subagentSnapshots: new Map(), // sid -> SubagentSnapshotLike[] @@ -138,10 +138,11 @@ const world = { async function fetchStub(url, init = {}) { const method = (init.method ?? "GET").toUpperCase(); const u = String(url); - world.calls.push({ method, url: u, body: typeof init.body === "string" ? safeParse(init.body) : null }); + const body = typeof init.body === "string" ? safeParse(init.body) : null; + world.calls.push({ method, url: u, body }); for (let i = 0; i < world.holds.length; i++) { - if (world.holds[i].match(method, u)) { + if (world.holds[i].match(method, u, body)) { const h = world.holds.splice(i, 1)[0]; const { status = 200, value } = await h.produce(); return jsonResponse(status, value); @@ -174,7 +175,6 @@ async function fetchStub(url, init = {}) { return jsonResponse(200, { running: a.running, state: a.state }); } if (method === "POST") { - const body = typeof init.body === "string" ? safeParse(init.body) : null; if (body?.type === "get_subagents") { return jsonResponse(200, { success: true, data: { subagents: world.subagentSnapshots.get(sid) ?? [] } }); } @@ -221,7 +221,7 @@ function sessionInfo(sid) { }; } -async function mountSession(sid, onAgentEnd) { +async function mountSession(sid, onAgentEnd, strictMode = false) { let latest = null; function Chat({ session }) { latest = useAgentSession({ session, newSessionCwd: null, ...(onAgentEnd ? { onAgentEnd } : {}) }); @@ -229,7 +229,8 @@ async function mountSession(sid, onAgentEnd) { } let renderer; await act(async () => { - renderer = TestRenderer.create(React.createElement(Chat, { session: sessionInfo(sid) })); + const chat = React.createElement(Chat, { session: sessionInfo(sid) }); + renderer = TestRenderer.create(strictMode ? React.createElement(React.StrictMode, null, chat) : chat); }); await settle(); // hydration: loadSession + /state + models + subagents activeRenderers.add(renderer); @@ -290,8 +291,8 @@ const assistantMsg = (id, text) => ({ }); /** Mount + hydrate, then send a prompt and open the stream. Returns the ES. */ -async function startRun(t, sid, message) { - const w = await mountSession(sid); +async function startRun(t, sid, message, strictMode = false) { + const w = await mountSession(sid, undefined, strictMode); if (t) t.after(unmountAll); assert.equal(w.latest.loading, false, "hydration must complete"); assert.equal(w.latest.agentRunning, false); @@ -317,6 +318,202 @@ async function startRun(t, sid, message) { // Tests // --------------------------------------------------------------------------- +test("queued promotion waits for native acknowledgement and moves only the first matching follow-up", async (t) => { + t.after(unmountAll); + resetWorld(); + primeSession("promotion", [userMsg("u0", "q")]); + const w = await mountSession("promotion", undefined, true); + await act(async () => { + await w.latest.handleSteer("existing steer"); + await w.latest.handleFollowUp("other"); + await w.latest.handleFollowUp("target"); + await w.latest.handleFollowUp("target"); + }); + const before = { steering: ["existing steer"], followUp: ["other", "target", "target"] }; + let release; + const acknowledgement = new Promise((resolve) => { release = resolve; }); + world.holds.push({ + match: (method, url, body) => method === "POST" && url === "/api/agent/promotion" && body?.type === "promote_queued_message", + produce: () => acknowledgement, + }); + const callsBefore = world.calls.length; + let promotion; + await act(async () => { promotion = w.latest.promoteQueuedToSteer("target"); }); + assert.deepEqual(w.latest.queuedMessages, before, "pending RPC must not relabel the chip"); + assert.deepEqual(world.calls.slice(callsBefore), [{ + method: "POST", url: "/api/agent/promotion", body: { type: "promote_queued_message", message: "target" }, + }], "promotion must not enqueue a separate steer or follow-up"); + await act(async () => { + release({ value: { success: true, data: { promoted: true } } }); + await promotion; + }); + assert.deepEqual(w.latest.queuedMessages, { + steering: ["existing steer", "target"], followUp: ["other", "target"], + }); + assert.deepEqual(w.latest.notices, []); +}); + +test("queued promotion preserves the follow-up and reports native refusal or rejection", async (t) => { + for (const outcome of [ + { name: "not-found", response: { value: { success: true, data: { promoted: false } } }, noticeType: "warning" }, + { name: "unsupported", response: { status: 400, value: { error: "Unknown RPC command: promote_queued_message" } }, noticeType: "error" }, + ]) { + await t.test(outcome.name, async (t) => { + t.after(unmountAll); + resetWorld(); + primeSession(outcome.name, [userMsg("u0", "q")]); + const w = await mountSession(outcome.name); + await act(async () => { await w.latest.handleFollowUp("target"); }); + let release; + const acknowledgement = new Promise((resolve) => { release = resolve; }); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "promote_queued_message", + produce: () => acknowledgement, + }); + let promotion; + await act(async () => { promotion = w.latest.promoteQueuedToSteer("target"); }); + assert.deepEqual(w.latest.queuedMessages, { steering: [], followUp: ["target"] }); + await act(async () => { + release(outcome.response); + await promotion; + }); + assert.deepEqual(w.latest.queuedMessages, { steering: [], followUp: ["target"] }); + assert.equal(w.latest.notices.length, 1); + assert.equal(w.latest.notices[0].type, outcome.noticeType); + if (outcome.response.value.error) { + assert.equal(w.latest.notices[0].message, outcome.response.value.error); + } + + // A settled failure releases the overlap guard so a deliberate retry works. + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "promote_queued_message", + produce: async () => ({ value: { success: true, data: { promoted: true } } }), + }); + await act(async () => { await w.latest.promoteQueuedToSteer("target"); }); + assert.deepEqual(w.latest.queuedMessages, { steering: ["target"], followUp: [] }); + }); + } +}); + +test("overlapping same-text promotion clicks send one command and promote one occurrence", async (t) => { + t.after(unmountAll); + resetWorld(); + primeSession("double-promotion", [userMsg("u0", "q")]); + const w = await mountSession("double-promotion"); + await act(async () => { + await w.latest.handleFollowUp("target"); + await w.latest.handleFollowUp("target"); + }); + let release; + const acknowledgement = new Promise((resolve) => { release = resolve; }); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "promote_queued_message", + produce: () => acknowledgement, + }); + let first; + let second; + await act(async () => { + first = w.latest.promoteQueuedToSteer("target"); + second = w.latest.promoteQueuedToSteer("target"); + }); + assert.equal(world.calls.filter((call) => call.body?.type === "promote_queued_message").length, 1); + assert.deepEqual(w.latest.queuedMessages, { steering: [], followUp: ["target", "target"] }); + await act(async () => { + release({ value: { success: true, data: { promoted: true } } }); + await Promise.all([first, second]); + }); + assert.deepEqual(w.latest.queuedMessages, { steering: ["target"], followUp: ["target"] }); +}); + +test("delivery before promotion acknowledgement does not relabel the next duplicate or resurrect the delivered chip", async (t) => { + t.after(unmountAll); + resetWorld(); + primeSession("delivered-promotion", [userMsg("u0", "q")]); + const { w, es } = await startRun(t, "delivered-promotion", "run", true); + await act(async () => { + es.emit({ type: "agent_start" }); + await w.latest.handleFollowUp("target"); + await w.latest.handleFollowUp("target"); + }); + let release; + const acknowledgement = new Promise((resolve) => { release = resolve; }); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "promote_queued_message", + produce: () => acknowledgement, + }); + let promotion; + await act(async () => { promotion = w.latest.promoteQueuedToSteer("target"); }); + await act(async () => { es.emit({ type: "message_end", message: userMsg("delivered", "target") }); }); + assert.deepEqual(w.latest.queuedMessages, { steering: [], followUp: ["target"] }); + assert.equal(w.latest.messages.filter((message) => message.role === "user" && message.content === "target").length, 1); + await act(async () => { + release({ value: { success: true, data: { promoted: true } } }); + await promotion; + }); + assert.deepEqual(w.latest.queuedMessages, { steering: [], followUp: ["target"] }); +}); + +test("a batched local removal and promotion acknowledgement preserve the next duplicate in StrictMode", async (t) => { + t.after(unmountAll); + resetWorld(); + primeSession("removed-promotion", [userMsg("u0", "q")]); + const w = await mountSession("removed-promotion", undefined, true); + await act(async () => { + await w.latest.handleFollowUp("target"); + await w.latest.handleFollowUp("target"); + }); + let release; + const acknowledgement = new Promise((resolve) => { release = resolve; }); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "promote_queued_message", + produce: () => acknowledgement, + }); + let promotion; + await act(async () => { promotion = w.latest.promoteQueuedToSteer("target"); }); + await act(async () => { + React.startTransition(() => w.latest.removeQueuedMessage("target")); + release({ value: { success: true, data: { promoted: true } } }); + await promotion; + }); + assert.deepEqual(w.latest.queuedMessages, { steering: [], followUp: ["target"] }); + assert.deepEqual(w.latest.notices, []); +}); + +test("promotion acknowledgements after navigation cannot change the newly mounted session", async (t) => { + for (const response of [ + { value: { success: true, data: { promoted: true } } }, + { status: 400, value: { error: "Native promotion failed" } }, + ]) { + await t.test(response.status ? "error" : "success", async (t) => { + t.after(unmountAll); + resetWorld(); + primeSession("old-promotion", [userMsg("u0", "old")]); + primeSession("new-promotion", [userMsg("u1", "new")]); + const old = await mountSession("old-promotion"); + await act(async () => { await old.latest.handleFollowUp("target"); }); + let release; + const acknowledgement = new Promise((resolve) => { release = resolve; }); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "promote_queued_message", + produce: () => acknowledgement, + }); + let promotion; + await act(async () => { promotion = old.latest.promoteQueuedToSteer("target"); }); + await act(async () => { old.renderer.unmount(); }); + activeRenderers.delete(old.renderer); + const current = await mountSession("new-promotion"); + await act(async () => { await current.latest.handleFollowUp("target"); }); + await act(async () => { + release(response); + await promotion; + }); + assert.deepEqual(current.latest.queuedMessages, { steering: [], followUp: ["target"] }); + assert.deepEqual(current.latest.notices, []); + assert.equal(world.calls.some((call) => call.url === "/api/agent/new-promotion" && call.body?.type === "promote_queued_message"), false); + }); + } +}); + test("full run over fake SSE: optimistic bubble, coalesced streaming, terminal reload", async (t) => { t.after(unmountAll); resetWorld(); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 6434e7cf0..5e249fa7c 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -279,7 +279,16 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const [extensionCustomUi, setExtensionCustomUi] = useState(null); const [extensionStatuses, setExtensionStatuses] = useState([]); const [extensionWidgets, setExtensionWidgets] = useState([]); - const [queuedMessages, setQueuedMessages] = useState({ steering: [], followUp: [] }); + const [queuedMessages, setQueuedMessagesState] = useState(EMPTY_QUEUE); + const queuedMessagesRef = useRef(EMPTY_QUEUE); + // Serialize queue transitions in event/effect handlers, not React's + // replayable render-phase updaters. Promotion bookkeeping and its queue + // removal must observe the same transition, even before React commits. + const updateQueuedMessages = useCallback((update: QueuedMessages | ((prev: QueuedMessages) => QueuedMessages)) => { + const next = typeof update === "function" ? update(queuedMessagesRef.current) : update; + queuedMessagesRef.current = next; + setQueuedMessagesState(next); + }, []); const [subagents, setSubagents] = useState([]); const [subagentEvents, setSubagentEvents] = useState>({}); const [subagentTranscriptVersions, setSubagentTranscriptVersions] = useState>({}); @@ -309,6 +318,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // get_state snapshots may lag behind the RPC round-trip, so a snapshot // reporting queuedMessageCount === 0 must not wipe a queue we just wrote. const queueMutatedAtRef = useRef(0); + const queuedPromotionsRef = useRef | null>(null); + if (queuedPromotionsRef.current === null) queuedPromotionsRef.current = new Map(); + const queuedPromotions = queuedPromotionsRef.current; const agentRunningRef = useRef(false); const bashRunningRef = useRef(false); const bashRecoveryIdRef = useRef(0); @@ -730,9 +742,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (liveState.extensionStatuses !== undefined) setExtensionStatuses(liveState.extensionStatuses ?? []); if (liveState.extensionWidgets !== undefined) setExtensionWidgets(liveState.extensionWidgets ?? []); if (liveState.todoPhases !== undefined) setTodoPhases(liveState.todoPhases ?? []); - if (liveState.queuedMessageCount === 0 && Date.now() - queueMutatedAtRef.current >= 5000) setQueuedMessages(EMPTY_QUEUE); + if (liveState.queuedMessageCount === 0 && Date.now() - queueMutatedAtRef.current >= 5000) updateQueuedMessages(EMPTY_QUEUE); } else if (!agentState.running && Date.now() - queueMutatedAtRef.current >= 5000) { - setQueuedMessages(EMPTY_QUEUE); + updateQueuedMessages(EMPTY_QUEUE); } if (showLoading) setLoading(false); return agentState; @@ -757,7 +769,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // Ensure the flag is cleared even if the pre-state early-return path was taken if (showLoading && includeState && !messagesLoaded) initialHydrationPendingRef.current = false; } - }, [refreshSubagentHistory, applyAuthoritativeModel, beginAuthoritativeModelSync]); + }, [refreshSubagentHistory, applyAuthoritativeModel, beginAuthoritativeModelSync, updateQueuedMessages]); const loadContext = useCallback(async (sid: string, leafId: string | null, includePreCompaction = false): Promise => { const seq = ++contextRequestSeqRef.current; @@ -1462,7 +1474,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (state?.todoPhases !== undefined) setTodoPhases(state.todoPhases ?? []); // And the only reliable re-sync for a missed subagent lifecycle frame. void refreshSubagentRoster(sid); - if ((!state || state.queuedMessageCount === 0) && Date.now() - queueMutatedAtRef.current >= 5000) setQueuedMessages(EMPTY_QUEUE); + if ((!state || state.queuedMessageCount === 0) && Date.now() - queueMutatedAtRef.current >= 5000) updateQueuedMessages(EMPTY_QUEUE); const busy = data.running && state && (state.isStreaming || state.isPromptRunning || state.isCompacting); if (busy || !agentRunningRef.current) return; @@ -1486,7 +1498,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { void reconcileAgentState(sid); } } - }, [finishPromptWithoutStream, refreshSubagentRoster]); + }, [finishPromptWithoutStream, refreshSubagentRoster, updateQueuedMessages]); // Recovery net for missed SSE events: while the agent is running, verify // against the server periodically and whenever the tab returns to the @@ -1559,45 +1571,76 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const consumeQueuedMessage = useCallback((text: string) => { if (!text) return; - setQueuedMessages((prev) => { + const promotion = queuedPromotions.get(text); + const sid = sessionIdRef.current; + updateQueuedMessages((prev) => { const si = prev.steering.indexOf(text); if (si !== -1) return { ...prev, steering: prev.steering.filter((_, i) => i !== si) }; const fi = prev.followUp.indexOf(text); - if (fi !== -1) return { ...prev, followUp: prev.followUp.filter((_, i) => i !== fi) }; + if (fi !== -1) { + // A pending acknowledgement must not promote the next same-text item. + if (promotion?.sessionId === sid) promotion.consumed = true; + return { ...prev, followUp: prev.followUp.filter((_, i) => i !== fi) }; + } return prev; }); - }, []); + }, [queuedPromotions, updateQueuedMessages]); /** Remove one queued message from the client-side queue mirror. omp's RPC - * protocol has no queue-mutation commands, so this only affects the queue + * protocol has no queue-removal command, so this only affects the queue * panel: a message removed here may still be delivered by the running agent * (it then arrives in the chat like any delivered turn). */ const removeQueuedMessage = useCallback((text: string) => { if (!text) return; - setQueuedMessages((prev) => { + const promotion = queuedPromotions.get(text); + const sid = sessionIdRef.current; + updateQueuedMessages((prev) => { const si = prev.steering.indexOf(text); const fi = prev.followUp.indexOf(text); if (si === -1 && fi === -1) return prev; + if (fi !== -1 && promotion?.sessionId === sid) promotion.consumed = true; return { steering: si === -1 ? prev.steering : prev.steering.filter((_, i) => i !== si), followUp: fi === -1 ? prev.followUp : prev.followUp.filter((_, i) => i !== fi), }; }); - }, []); + }, [queuedPromotions, updateQueuedMessages]); - /** Promote the first queued follow-up to a steering message (client-side - * relabel; the delivery order itself is owned by omp). */ - const promoteQueuedToSteer = useCallback((text: string) => { - if (!text) return; - setQueuedMessages((prev) => { - const fi = prev.followUp.indexOf(text); - if (fi === -1) return prev; - return { - steering: [...prev.steering, text], - followUp: prev.followUp.filter((_, i) => i !== fi), - }; - }); - }, []); + /** Move the first matching native follow-up into steering, then relabel its + * still-undelivered chip. Never enqueue a second copy via steer. */ + const promoteQueuedToSteer = useCallback(async (text: string) => { + const sid = sessionIdRef.current; + if (!hookAliveRef.current || !sid || !text || !queuedMessages.followUp.includes(text)) return; + // Text is the existing chip identity. Suppress overlap, not later retries. + if (queuedPromotions.get(text)?.sessionId === sid) return; + const promotion = { sessionId: sid, consumed: false }; + queuedPromotions.set(text, promotion); + try { + const result = await sendAgentCommand<{ promoted: boolean }>(sid, { + type: "promote_queued_message", + message: text, + }); + if (!hookAliveRef.current || sessionIdRef.current !== sid) return; + if (result?.promoted !== true) { + addNotice({ type: "warning", message: translate("agentSession.queuedPromotionUnavailable") }); + return; + } + updateQueuedMessages((prev) => { + if (!hookAliveRef.current || sessionIdRef.current !== sid || promotion.consumed) return prev; + const fi = prev.followUp.indexOf(text); + if (fi === -1) return prev; + return { + steering: [...prev.steering, text], + followUp: prev.followUp.filter((_, i) => i !== fi), + }; + }); + } catch (error) { + if (!hookAliveRef.current || sessionIdRef.current !== sid) return; + addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); + } finally { + if (queuedPromotions.get(text) === promotion) queuedPromotions.delete(text); + } + }, [addNotice, queuedMessages.followUp, queuedPromotions, updateQueuedMessages]); // Mirror queued texts into sessionStorage so a reload can restore them. // The dirty gate keeps the initial empty state from wiping a stored queue @@ -1710,7 +1753,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (d.state?.todoPhases !== undefined) setTodoPhases(d.state.todoPhases ?? []); // omp reports only a queued count; an empty (or dead) session // means the client-tracked queue texts are stale. - if ((!d.state || d.state.queuedMessageCount === 0) && Date.now() - queueMutatedAtRef.current >= 5000) setQueuedMessages(EMPTY_QUEUE); + if ((!d.state || d.state.queuedMessageCount === 0) && Date.now() - queueMutatedAtRef.current >= 5000) updateQueuedMessages(EMPTY_QUEUE); }) .catch(() => {}); } @@ -2131,7 +2174,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { handleExtensionUiRequest(event as unknown as IncomingExtensionUiRequest); break; } - }, [addNotice, clearTerminalReconcileTimer, consumeQueuedMessage, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, mergeSubagents, onAgentEnd, reconcileAgentState, resetSubagentActivityState, applyAuthoritativeModel, beginAuthoritativeModelSync, surfaceQuotaOnStream]); + }, [addNotice, clearTerminalReconcileTimer, consumeQueuedMessage, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, mergeSubagents, onAgentEnd, reconcileAgentState, resetSubagentActivityState, applyAuthoritativeModel, beginAuthoritativeModelSync, surfaceQuotaOnStream, updateQueuedMessages]); handleAgentEventRef.current = handleAgentEvent; const handleSend = useCallback(async (message: string, images?: AttachedImage[]): Promise => { @@ -2789,13 +2832,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // omp emits no queue snapshots; track the queued text locally until it // is delivered (user message_end) or the queue count drops to zero. queueMutatedAtRef.current = Date.now(); - setQueuedMessages((prev) => ({ ...prev, steering: [...prev.steering, message] })); + updateQueuedMessages((prev) => ({ ...prev, steering: [...prev.steering, message] })); } catch (e) { console.error("Failed to steer:", e); addNotice({ type: "error", message: e instanceof Error ? e.message : String(e) }); opts.chatInputRef?.current?.insertIfEmpty(message); } - }, [addNotice, opts.chatInputRef]); + }, [addNotice, opts.chatInputRef, updateQueuedMessages]); const handlePromptWithStreamingBehavior = useCallback(async ( message: string, @@ -2813,7 +2856,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { ...(piImages?.length ? { images: piImages } : {}), }); queueMutatedAtRef.current = Date.now(); - setQueuedMessages((prev) => behavior === "steer" + updateQueuedMessages((prev) => behavior === "steer" ? { ...prev, steering: [...prev.steering, message] } : { ...prev, followUp: [...prev.followUp, message] }); } catch (e) { @@ -2821,7 +2864,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { addNotice({ type: "error", message: e instanceof Error ? e.message : String(e) }); opts.chatInputRef?.current?.insertIfEmpty(message); } - }, [addNotice, opts.chatInputRef]); + }, [addNotice, opts.chatInputRef, updateQueuedMessages]); const handleFollowUp = useCallback(async (message: string, images?: AttachedImage[]) => { const sid = sessionIdRef.current; @@ -2834,13 +2877,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { ...(piImages?.length ? { images: piImages } : {}), }); queueMutatedAtRef.current = Date.now(); - setQueuedMessages((prev) => ({ ...prev, followUp: [...prev.followUp, message] })); + updateQueuedMessages((prev) => ({ ...prev, followUp: [...prev.followUp, message] })); } catch (e) { console.error("Failed to follow up:", e); addNotice({ type: "error", message: e instanceof Error ? e.message : String(e) }); opts.chatInputRef?.current?.insertIfEmpty(message); } - }, [addNotice, opts.chatInputRef]); + }, [addNotice, opts.chatInputRef, updateQueuedMessages]); const handleAbortCompaction = useCallback(async () => { const sid = sessionIdRef.current; @@ -2963,7 +3006,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (agentState.state.extensionStatuses !== undefined) setExtensionStatuses(agentState.state.extensionStatuses ?? []); if (agentState.state.extensionWidgets !== undefined) setExtensionWidgets(agentState.state.extensionWidgets ?? []); if (agentState.state.queuedMessageCount === 0 && Date.now() - queueMutatedAtRef.current >= 5000) { - setQueuedMessages(EMPTY_QUEUE); + updateQueuedMessages(EMPTY_QUEUE); // The queue drained while the page was closed — a stored copy // from a previous page load is stale. clearPersistedQueue(session.id); @@ -2972,7 +3015,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // texts persisted by the previous page load. const persisted = readPersistedQueue(session.id); if (persisted) { - setQueuedMessages((prev) => (isEmptyQueue(prev) ? persisted : prev)); + updateQueuedMessages((prev) => (isEmptyQueue(prev) ? persisted : prev)); } } } @@ -3090,9 +3133,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [messages, streamState, agentRunning, agentPhase, extensionWidgets, isCompacting, retryInfo, activeSubagentCount, todoPhases, scrollToBottom, loading]); - useEffect(() => () => { - hookAliveRef.current = false; - if (followScrollFrameRef.current !== null) cancelAnimationFrame(followScrollFrameRef.current); + useEffect(() => { + hookAliveRef.current = true; + return () => { + hookAliveRef.current = false; + if (followScrollFrameRef.current !== null) cancelAnimationFrame(followScrollFrameRef.current); + }; }, []); // Load model list diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index bcea390af..6d34efcbe 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -21,6 +21,7 @@ "agentSession.sendFailed": "Failed to send message: {detail}", "agentSession.sessionRenamed": "Session renamed to {name}", "agentSession.shellSessionFailed": "Unable to create a session for the shell command", + "agentSession.queuedPromotionUnavailable": "The queued follow-up is no longer available to steer.", "agentSession.startingAgent": "Starting omp… the first launch of a session can take a while.", "agentSession.toolPresetNotice": "Tool presets apply when a session starts; this session keeps its current tools.", "archiveBrowser.title": "Archived Sessions", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 086a8d446..888a06743 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -21,6 +21,7 @@ "agentSession.sendFailed": "メッセージの送信に失敗しました: {detail}", "agentSession.sessionRenamed": "セッション名を {name} に変更しました", "agentSession.shellSessionFailed": "シェルコマンド用のセッションを作成できませんでした", + "agentSession.queuedPromotionUnavailable": "このフォローアップはキューに存在しないため、ステアリングに変更できません。", "agentSession.startingAgent": "omp を起動しています… セッションの初回起動には時間がかかる場合があります。", "agentSession.toolPresetNotice": "ツールプリセットはセッション開始時に適用されます。このセッションは現在のツールを維持します。", "archiveBrowser.title": "アーカイブされたセッション", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 2dccdc65d..5f0c42d1f 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -21,6 +21,7 @@ "agentSession.sendFailed": "发送消息失败:{detail}", "agentSession.sessionRenamed": "会话已重命名为 {name}", "agentSession.shellSessionFailed": "无法为 shell 命令创建会话", + "agentSession.queuedPromotionUnavailable": "该后续消息已不在队列中,无法转为引导消息。", "agentSession.startingAgent": "正在启动 omp……会话首次启动可能需要一些时间。", "agentSession.toolPresetNotice": "工具预设在会话启动时生效;当前会话将保留现有工具。", "archiveBrowser.title": "已归档会话", diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index de80c1e9a..5990d8d8a 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -82,6 +82,7 @@ const PENDING_UI_METHODS = new Set(["select", "confirm", "input", "editor", "ope const PASSTHROUGH_COMMANDS = new Set([ "abort", "abort_and_prompt", + "promote_queued_message", "set_thinking_level", "cycle_thinking_level", "cycle_model",