From 92ac06e30684a3970ecd53018115b87985c5c7f1 Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:09:53 +0200 Subject: [PATCH] fix(settings): expose the Advisor default setting and wire it to new chats (fixes #323) Supersedes #557 (went dirty after #566 merged); same change rebased onto current main. --- components/AppShell.tsx | 5 +- components/ChatWindow.tsx | 6 +- components/SettingsConfig.advisor.test.mjs | 69 ++++++++++++++++++++++ components/SettingsConfig.tsx | 16 +++++ hooks/useAgentSession.rpc.test.mjs | 27 +++++++++ hooks/useAgentSession.ts | 30 +++++++--- lib/i18n/locales/en.json | 4 ++ lib/i18n/locales/ja.json | 4 ++ lib/i18n/locales/zh-CN.json | 4 ++ lib/i18n/locales/zh-TW.json | 4 ++ 10 files changed, 157 insertions(+), 12 deletions(-) create mode 100644 components/SettingsConfig.advisor.test.mjs diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 9398e09d2..a3d002fd3 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -217,13 +217,15 @@ export function AppShell({ appName }: { appName: string }) { // UI-only behavior, so it lives in localStorage rather than omp's config. const [expandThinkingByDefault, setExpandThinkingByDefault] = useState(false); const [hideThinkingBlock, setHideThinkingBlock] = useState(false); + // Global omp `advisor.enabled`: brand-new chats start with Advisor on. + const [advisorDefault, setAdvisorDefault] = useState(false); useEffect(() => { // omp's own setting, so the transcript hides thinking when the TUI does. // Re-read on focus: the TUI or another tab may have changed it. const load = () => { fetch("/api/omp-settings") .then((response) => (response.ok ? response.json() : null)) - .then((data: { settings?: { hideThinkingBlock?: boolean } } | null) => { if (data) setHideThinkingBlock(data.settings?.hideThinkingBlock === true); }) + .then((data: { settings?: { hideThinkingBlock?: boolean; advisor?: { enabled?: boolean } } } | null) => { if (data) { setHideThinkingBlock(data.settings?.hideThinkingBlock === true); setAdvisorDefault(data.settings?.advisor?.enabled === true); } }) .catch(() => {}); }; load(); @@ -2832,6 +2834,7 @@ export function AppShell({ appName }: { appName: string }) { showToolCallsUnfolded={showToolCallsUnfolded} expandThinkingByDefault={expandThinkingByDefault} hideThinkingBlock={hideThinkingBlock} + advisorDefault={advisorDefault} searchQuery={chatSearchQuery} searchTarget={searchMatchTarget && searchMatchTarget.sessionId === selectedSession?.id ? searchMatchTarget : null} onSearchTargetHandled={clearSearchMatchTarget} diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 78ad8bd7c..b826b0fc2 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -74,6 +74,8 @@ interface Props { expandThinkingByDefault?: boolean; /** omp `hideThinkingBlock`: omit thinking from the transcript. */ hideThinkingBlock?: boolean; + /** Global omp default (`advisor.enabled`): brand-new chats start with Advisor on when true. */ + advisorDefault?: boolean; onAgentEnd?: () => void; onSessionCreated?: (session: SessionInfo) => void; onSessionForked?: (newSessionId: string) => void; @@ -397,7 +399,7 @@ const CommittedTranscript = memo(function CommittedTranscript({ ); }); -export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, hostStatus: channelHostStatus, hostLabel, newSessionWorkspace, toolCallsDefaultCollapsed = true, hideToolActivity = true, neverFoldActivity = false, showToolCallsUnfolded = false, expandThinkingByDefault = false, hideThinkingBlock = false, onAgentEnd, onSessionCreated, onSessionForked, onSessionMoved, modelsRefreshKey, chatInputRef, sessionInfoContainer, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsChange, onSessionStatsPanelOpen, onProviderUsageContextChange, onGenerationSpeedChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, onOpenProviders, searchQuery = "", searchTarget = null, onSearchTargetHandled }: Props) { +export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, hostStatus: channelHostStatus, hostLabel, newSessionWorkspace, toolCallsDefaultCollapsed = true, hideToolActivity = true, neverFoldActivity = false, showToolCallsUnfolded = false, expandThinkingByDefault = false, hideThinkingBlock = false, advisorDefault = false, onAgentEnd, onSessionCreated, onSessionForked, onSessionMoved, modelsRefreshKey, chatInputRef, sessionInfoContainer, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsChange, onSessionStatsPanelOpen, onProviderUsageContextChange, onGenerationSpeedChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, onOpenProviders, searchQuery = "", searchTarget = null, onSearchTargetHandled }: Props) { const { t, tn } = useI18n(); const fileSource = useMemo(() => ({ hostId: session?.hostId ?? newSessionHostId ?? "local", @@ -470,7 +472,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio btw, askBtw, resolveUploadHost, } = useAgentSession({ - session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, onAgentEnd: wrappedOnAgentEnd, onSessionCreated, onSessionForked, onSessionMoved: handleSessionMoved, + session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, advisorDefault, onAgentEnd: wrappedOnAgentEnd, onSessionCreated, onSessionForked, onSessionMoved: handleSessionMoved, modelsRefreshKey, chatInputRef: composerRef, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsPanelOpen, onOpenFile: onOpenWorkspaceFile, onOpenUrl, }); diff --git a/components/SettingsConfig.advisor.test.mjs b/components/SettingsConfig.advisor.test.mjs new file mode 100644 index 000000000..1edfefcb2 --- /dev/null +++ b/components/SettingsConfig.advisor.test.mjs @@ -0,0 +1,69 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test from "node:test"; +import { act, createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { SettingsConfig } from "./SettingsConfig"; + +const noop = () => {}; + +/** Render the real Agent & Intelligence panel with a stubbed settings API. */ +async function renderIntelligenceTab(t, { advisorEnabled = true } = {}) { + const puts = []; + const originalFetch = globalThis.fetch; + globalThis.fetch = async (url, options = {}) => { + if (String(url) === "/api/omp-settings" && (options.method ?? "GET") === "PUT") { + const settings = JSON.parse(options.body).settings; + puts.push(settings); + return Response.json({ success: true, settings }); + } + if (String(url) === "/api/omp-settings") return Response.json({ settings: { advisor: { enabled: advisorEnabled } } }); + return Response.json({}); + }; + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + t.after(() => { + act(() => root.unmount()); + container.remove(); + globalThis.fetch = originalFetch; + }); + await act(async () => { + root.render(createElement(SettingsConfig, { + activeTab: "intelligence", + toolCallsDefaultCollapsed: false, onToolCallsDefaultCollapsedChange: noop, + hideToolActivity: false, onHideToolActivityChange: noop, + expandThinkingByDefault: false, onExpandThinkingByDefaultChange: noop, onHideThinkingBlockChange: noop, + providerUsageVisible: false, onProviderUsageVisibleChange: noop, + scopeNativeSelectAll: false, onScopeNativeSelectAllChange: noop, + openUrlAutomatically: false, onOpenUrlAutomaticallyChange: noop, + cwd: null, remoteHost: false, sessionId: null, + onModelsSaved: noop, onPluginsReloaded: noop, + appUpdate: null, onRefreshAppUpdate: async () => null, + onRequestAppUpdate: noop, onSelectTab: noop, onClose: noop, + })); + }); + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + return { container, puts }; +} + +const advisorSwitch = (container) => container.querySelector('[data-search-id="advisor-enabled"] button[role="switch"]'); + +test("Agent & Intelligence exposes the Advisor default and persists it", async (t) => { + const { container, puts } = await renderIntelligenceTab(t, { advisorEnabled: true }); + assert.ok(container.textContent.includes("Advisor"), "no Advisor section in the intelligence tab"); + const toggle = advisorSwitch(container); + assert.ok(toggle, "no Advisor toggle"); + assert.equal(toggle.getAttribute("aria-checked"), "true"); + act(() => toggle.click()); + await act(() => new Promise((resolve) => setTimeout(resolve, 50))); + assert.ok(puts.length >= 1, "toggling Advisor sent no PUT"); + assert.equal(puts.at(-1).advisor.enabled, false); +}); + +test("the Advisor toggle reflects a disabled global default", async (t) => { + const { container } = await renderIntelligenceTab(t, { advisorEnabled: false }); + const toggle = advisorSwitch(container); + assert.ok(toggle, "no Advisor toggle"); + assert.equal(toggle.getAttribute("aria-checked"), "false"); +}); diff --git a/components/SettingsConfig.tsx b/components/SettingsConfig.tsx index 4cb3143a1..c65536b42 100644 --- a/components/SettingsConfig.tsx +++ b/components/SettingsConfig.tsx @@ -178,6 +178,8 @@ const SETTING_INDEX: SettingIndexEntry[] = [ { id: "continue-after-compaction", tab: "intelligence", sectionKey: "settingsConfig.contextCompaction", labelKey: "settingsConfig.continueAfterCompaction", descKey: "settingsConfig.continueAfterCompactionDesc", fallbackSection: "Context Compaction", fallbackLabel: "Continue After Compaction", fallbackDesc: "Resume task execution after compaction completes.", scope: "Native OMP" }, { id: "compaction-method-order", tab: "intelligence", sectionKey: "settingsConfig.contextCompaction", labelKey: "settingsConfig.compactionMethodOrder", descKey: "settingsConfig.compactionMethodOrderDesc", fallbackSection: "Context Compaction", fallbackLabel: "Compaction Method Order", fallbackDesc: "Preferred fallback order for automatic context maintenance; unavailable or failed methods advance to the next choice.", scope: "Native OMP" }, { id: "compact-mid-turn", tab: "intelligence", sectionKey: "settingsConfig.contextCompaction", labelKey: "settingsConfig.compactMidTurn", descKey: "settingsConfig.compactMidTurnDesc", fallbackSection: "Context Compaction", fallbackLabel: "Compact Mid-Turn", fallbackDesc: "Check context limits between tool execution steps.", scope: "Native OMP" }, + // Advisor + { id: "advisor-enabled", tab: "intelligence", sectionKey: "settingsConfig.advisor", labelKey: "settingsConfig.advisorEnabled", descKey: "settingsConfig.advisorEnabledDesc", fallbackSection: "Advisor", fallbackLabel: "Enable Advisor", fallbackDesc: "New sessions start with Advisor on. The advisor reviews the work independently without changing code.", scope: "Native OMP" }, // Memory & Auto-Learn { id: "memory-backend", tab: "intelligence", sectionKey: "settingsConfig.memoryAutoLearn", labelKey: "settingsConfig.memoryBackend", descKey: "settingsConfig.memoryBackendDesc", fallbackSection: "Memory & Auto-Learn", fallbackLabel: "Memory Backend", fallbackDesc: "Where durable knowledge is stored across sessions.", scope: "Native OMP" }, { id: "enable-auto-learn", tab: "intelligence", sectionKey: "settingsConfig.memoryAutoLearn", labelKey: "settingsConfig.enableAutoLearn", descKey: "settingsConfig.enableAutoLearnDesc", fallbackSection: "Memory & Auto-Learn", fallbackLabel: "Enable Auto-Learn", fallbackDesc: "Capture reusable lessons after completed runs.", scope: "Native OMP" }, @@ -1776,6 +1778,20 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal + {/* Advisor Section */} +
+
{t("settingsConfig.advisor")}
+

{t("settingsConfig.advisorDesc")}

+
+ + patchSection("advisor", { enabled: checked })} + /> + +
+
+ {/* Memory & Auto-Learn Section */}
{t("settingsConfig.memoryAutoLearn")}
diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index f07c09c91..daa9251c2 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -4040,6 +4040,33 @@ test("forking carries the advisor choice to the child's next native command", as assert.ok(world.calls.some((call) => call.url === "/api/agent/advisor-child?advisor=1")); }); +test("a new chat starts with Advisor on when the global default enables it", async () => { + resetWorld(); + world.holds.push({ + match: (method, url) => method === "POST" && url === "/api/agent/new", + produce: async () => ({ value: { sessionId: "created" } }), + }); + const w = await mountSession(null, undefined, { newSessionCwd: "/workspace", advisorDefault: true }); + await act(async () => { assert.equal(w.latest.advisorEnabled, true); }); + await act(async () => { + // The send itself waits on the live stream; only the ensure_session + // request matters here, so assert on it and leave like the abandoned + // new-chat tests do. + void w.latest.handleSend("hello"); + await sleep(50); + }); + const created = world.calls.find((call) => call.url === "/api/agent/new"); + assert.equal(created?.body?.advisor, true, "the ensure_session request must carry the default"); + w.unmount(); +}); + +test("a new chat starts with Advisor off when the global default is absent", async () => { + resetWorld(); + const w = await mountSession(null, undefined, { newSessionCwd: "/workspace" }); + await act(async () => { assert.equal(w.latest.advisorEnabled, false); }); + w.unmount(); +}); + test("an edit-and-resend fork puts the branched prompt into the child's composer", async () => { const { getDraft, clearDraft } = await import("@/lib/draft-store"); for (const [editPrompt, child] of [[true, "edit-child"], [false, "keep-child"]]) { diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 17e664cc8..cfe1b4ab1 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -235,7 +235,10 @@ export interface UseAgentSessionOptions { /** Frozen ensure_session configuration retained by the existing navigation view. */ newSessionInitialization?: string; onNewSessionInitialization?: (body: string) => void; - advisorEnabled?: boolean; + /** Global omp default (`advisor.enabled` in settings): brand-new chats start + * with this until the user toggles the per-chat Advisor switch. Existing + * sessions keep their own stored choice. */ + advisorDefault?: boolean; onAgentEnd?: () => void; onSessionCreated?: (session: SessionInfo) => void; onSessionForked?: (newSessionId: string) => void; @@ -322,7 +325,7 @@ function reconcileConfirmedLocalOutbox(sessionId: string, localEntries: LocalOut export function useAgentSession(opts: UseAgentSessionOptions) { const { - session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, onAgentEnd, onSessionCreated, onSessionForked, onSessionMoved, + session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, advisorDefault, onAgentEnd, onSessionCreated, onSessionForked, onSessionMoved, modelsRefreshKey, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsPanelOpen, onOpenFile, onOpenUrl, } = opts; @@ -590,9 +593,14 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const [activeGoal, setActiveGoal] = useState(null); const [activePlan, setActivePlan] = useState(null); const [advisorActiveAt, setAdvisorActiveAt] = useState(0); - // Advisor is a per-chat toggle (composer Sparkles + /advisor command), not a - // global setting: each session remembers its own choice in localStorage. - const [advisorEnabled, setAdvisorEnabled] = useState(false); + // Advisor is a per-chat toggle (composer Sparkles + /advisor command): each + // session remembers its own choice in localStorage. Brand-new chats start + // from the global `advisor.enabled` default until the user toggles it. + const [advisorEnabled, setAdvisorEnabled] = useState(advisorDefault ?? false); + // A toggle flipped on a brand-new chat (no id yet, so nothing persisted) + // must survive the global default arriving late; the load effect below + // only applies the default while this is false. + const advisorTouchedForNewRef = useRef(false); const activeSubagentCount = subagents.filter((subagent) => subagent.source !== "history" && subagent.status === "started").length; const eventSourceRef = useRef(null); @@ -942,14 +950,15 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return null; }, [todoPhases]); // Load the per-session advisor choice on session switch; brand-new chats - // start disabled until the user toggles the composer icon. + // start from the global default until the user toggles the composer icon. useEffect(() => { const sid = session?.id; if (!sid) { - setAdvisorEnabled(false); + setAdvisorEnabled((prev) => (advisorTouchedForNewRef.current ? prev : (advisorDefault ?? false))); setSessionToolPresetState(null); return; } + advisorTouchedForNewRef.current = false; let stored = false; try { stored = localStorage.getItem(`omp-advisor-enabled:${sid}`) === "true"; @@ -962,12 +971,15 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setSessionAdvisorSpawn(sid, stored); // The preset this session was spawned with, if this browser recorded it. setSessionToolPresetState(getSessionToolPreset(sid)); - }, [session?.id]); + }, [session?.id, advisorDefault]); const handleAdvisorChange = useCallback((enabled: boolean) => { setAdvisorEnabled(enabled); const sid = sessionIdRef.current; - if (!sid) return; + if (!sid) { + advisorTouchedForNewRef.current = true; + return; + } setSessionAdvisorSpawn(sid, enabled); try { localStorage.setItem(`omp-advisor-enabled:${sid}`, String(enabled)); diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 214a4de5a..99c8be248 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1719,6 +1719,10 @@ "settingsConfig.contextCompaction": "Context Compaction", "settingsConfig.contextCompactionDesc": "OMP automatically compacts oversized context to prevent hitting context limits.", "settingsConfig.automaticCompaction": "Automatic Compaction", + "settingsConfig.advisor": "Advisor", + "settingsConfig.advisorDesc": "An independent advisor reviews the work alongside the agent, without changing code.", + "settingsConfig.advisorEnabled": "Enable Advisor", + "settingsConfig.advisorEnabledDesc": "New sessions start with Advisor on. Each session can still turn it off from the composer.", "sessionTabs.tabsLabel": "Open sessions", "sessionTabs.untitledSession": "Untitled session", "sessionTabs.closeTab": "Close {title} tab", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index c81980bd9..92d6bdf78 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1674,6 +1674,10 @@ "settingsConfig.contextCompaction": "Context Compaction", "settingsConfig.contextCompactionDesc": "OMP automatically compacts oversized context to prevent hitting context limits.", "settingsConfig.automaticCompaction": "Automatic Compaction", + "settingsConfig.advisor": "アドバイザー", + "settingsConfig.advisorDesc": "独立したアドバイザーがコードを変更せずにエージェントと並行して作業をレビューします。", + "settingsConfig.advisorEnabled": "アドバイザーを有効化", + "settingsConfig.advisorEnabledDesc": "新しいセッションではアドバイザーがオンで開始します。各セッションはコンポーザーからオフにできます。", "sessionTabs.tabsLabel": "開いているセッション", "sessionTabs.untitledSession": "無題のセッション", "sessionTabs.closeTab": "{title} タブを閉じる", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 6a9e39c6d..3750fa659 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1674,6 +1674,10 @@ "settingsConfig.contextCompaction": "上下文压缩", "settingsConfig.contextCompactionDesc": "OMP 会自动压缩超限的上下文以避免达到模型上下文上限。", "settingsConfig.automaticCompaction": "自动压缩", + "settingsConfig.advisor": "顾问", + "settingsConfig.advisorDesc": "独立顾问与智能体一起评审工作,不修改代码。", + "settingsConfig.advisorEnabled": "启用顾问", + "settingsConfig.advisorEnabledDesc": "新会话默认开启顾问;每个会话仍可在输入框中关闭。", "sessionTabs.tabsLabel": "打开的会话", "sessionTabs.untitledSession": "未命名会话", "sessionTabs.closeTab": "关闭 {title} 标签页", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 7ddbbc268..b69fef81a 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -1719,6 +1719,10 @@ "settingsConfig.contextCompaction": "情境壓縮", "settingsConfig.contextCompactionDesc": "OMP 會自動壓縮過大的情境,以避免超出情境上限。", "settingsConfig.automaticCompaction": "自動壓縮", + "settingsConfig.advisor": "顧問", + "settingsConfig.advisorDesc": "獨立顧問與智能體一起評審工作,不修改程式碼。", + "settingsConfig.advisorEnabled": "啟用顧問", + "settingsConfig.advisorEnabledDesc": "新對話預設開啟顧問;每個對話仍可在輸入框中關閉。", "sessionTabs.tabsLabel": "開啟的對話", "sessionTabs.untitledSession": "未命名對話", "sessionTabs.closeTab": "關閉 {title} 標籤頁",