diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 85795fb82..4ecbff213 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -181,13 +181,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(); @@ -2778,6 +2780,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 763c6e851..39218d3b1 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 04af234fa..b73a0df27 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" }, @@ -1757,6 +1759,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 efce900b5..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"]]) { @@ -6816,7 +6843,7 @@ test("equal-path file tabs retain their originating session when the selected ow await sleep(60); }); await until(() => view.queryByText("FIRST OWNER CONTENT"), "the first owner file opens"); - await act(async () => { fireEvent.click(view.getByText("Worker two conversation")); await sleep(60); }); + await act(async () => { fireEvent.click(within(view.container.querySelector("#workspace-sidebar")).getByText("Worker two conversation")); await sleep(60); }); await act(async () => { stream.emit({ type: "host_tool_call", id: "second-open", sessionId: "worker-two", hostId: "h2", cwd: "/shared", toolName: "open_file", arguments: { path: "/shared/report.txt" } }); await sleep(60); @@ -6847,7 +6874,7 @@ test("a retained foreign-source tab cannot mention its path into the selected wo await sleep(60); }); await until(() => view.queryByText("FIRST OWNER CONTENT"), "the first owner's file opens"); - await act(async () => { fireEvent.click(view.getByText("Worker two conversation")); await sleep(60); }); + await act(async () => { fireEvent.click(within(view.container.querySelector("#workspace-sidebar")).getByText("Worker two conversation")); await sleep(60); }); await act(async () => { fireEvent.change(view.getByRole("textbox"), { target: { value: "Worker two draft" } }); stream.emit({ type: "host_tool_call", id: "mention-second-open", sessionId: "worker-two", hostId: "h2", cwd: "/shared", toolName: "open_file", arguments: { path: "/shared/report.txt" } }); @@ -6862,7 +6889,7 @@ test("a retained foreign-source tab cannot mention its path into the selected wo if (foreignMention) await act(async () => { fireEvent.click(foreignMention); }); assert.equal(view.getByRole("textbox").value, "Worker two draft", "a source-relative path must not be inserted into another worker's composer"); assert.equal(foreignMention === null || foreignMention.disabled, true, "the foreign-source action is unavailable"); - await act(async () => { fireEvent.click(view.getByText("Worker one conversation")); await sleep(60); }); + await act(async () => { fireEvent.click(within(view.container.querySelector("#workspace-sidebar")).getByText("Worker one conversation")); await sleep(60); }); const sourceMention = view.getByRole("button", { name: translate("appShell.mentionFileInChat") }); assert.equal(sourceMention.disabled, false, "returning to the source session restores the action"); await act(async () => { diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 0d3a9ed84..d3c466cb1 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; @@ -585,9 +588,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); @@ -937,13 +945,14 @@ 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))); return; } + advisorTouchedForNewRef.current = false; let stored = false; try { stored = localStorage.getItem(`omp-advisor-enabled:${sid}`) === "true"; @@ -954,12 +963,15 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // The spawn registry must match before any command POST can lazily start // the omp process; localStorage alone would leave resumed sessions dark. setSessionAdvisorSpawn(sid, stored); - }, [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 b7bda9c71..d61a47ca7 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1707,6 +1707,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.", "settingsConfig.automaticCompactionDesc": "Compact context before model context limit is hit.", "settingsConfig.continueAfterCompaction": "Continue After Compaction", "settingsConfig.continueAfterCompactionDesc": "Resume task execution after compaction completes.", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index f62f7bcb9..75a106bb9 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1667,6 +1667,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": "新しいセッションではアドバイザーがオンで開始します。各セッションはコンポーザーからオフにできます。", "settingsConfig.automaticCompactionDesc": "Compact context before model context limit is hit.", "settingsConfig.continueAfterCompaction": "Continue After Compaction", "settingsConfig.continueAfterCompactionDesc": "Resume task execution after compaction completes.", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index ac9dc1fbe..3db3d38ce 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1667,6 +1667,10 @@ "settingsConfig.contextCompaction": "上下文压缩", "settingsConfig.contextCompactionDesc": "OMP 会自动压缩超限的上下文以避免达到模型上下文上限。", "settingsConfig.automaticCompaction": "自动压缩", + "settingsConfig.advisor": "顾问", + "settingsConfig.advisorDesc": "独立顾问与智能体一起评审工作,不修改代码。", + "settingsConfig.advisorEnabled": "启用顾问", + "settingsConfig.advisorEnabledDesc": "新会话默认开启顾问;每个会话仍可在输入框中关闭。", "settingsConfig.automaticCompactionDesc": "在达到模型上下文上限前自动压缩上下文。", "settingsConfig.continueAfterCompaction": "压缩后继续执行", "settingsConfig.continueAfterCompactionDesc": "上下文压缩完成后自动恢复任务执行。", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 530707dd6..bbb40d88e 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -1707,6 +1707,10 @@ "settingsConfig.contextCompaction": "情境壓縮", "settingsConfig.contextCompactionDesc": "OMP 會自動壓縮過大的情境,以避免超出情境上限。", "settingsConfig.automaticCompaction": "自動壓縮", + "settingsConfig.advisor": "顧問", + "settingsConfig.advisorDesc": "獨立顧問與智能體一起評審工作,不修改程式碼。", + "settingsConfig.advisorEnabled": "啟用顧問", + "settingsConfig.advisorEnabledDesc": "新對話預設開啟顧問;每個對話仍可在輸入框中關閉。", "settingsConfig.automaticCompactionDesc": "在達到模型情境上限之前自動壓縮情境。", "settingsConfig.continueAfterCompaction": "壓縮後繼續執行", "settingsConfig.continueAfterCompactionDesc": "情境壓縮完成後繼續執行任務。",