From 959193dc494dcbbc28ac42b54b54c4bad4d6f2b6 Mon Sep 17 00:00:00 2001 From: killcerr Date: Thu, 29 Oct 2026 23:40:08 +0800 Subject: [PATCH 1/9] feat(chat): run omp slash commands natively and add goal mode - Forward every command omp reports (builtin, extension, custom, mcp_prompt, file, skill) through the prompt pipeline; the palette no longer hides builtins. - Replace the web /goal imitation with omp's goal RPC: create/pause/resume/drop, goal_updated/get_state.goal, and a real banner. Goal state is sequenced so stale snapshots cannot overwrite newer events. - Let /compact, /session, /review, and /advisor run natively; keep web-only prompt expansions only when omp does not own the name. - Intercept client-only commands while streaming so /goal never enters the prompt queue. - Document the TUI-only /plan and /loop limitation and the upstream paths. - Update tests, locales, AGENTS.md, CHANGELOG.md, and add the implementation spec. --- AGENTS.md | 27 ++ CHANGELOG.md | 1 + components/AppShell.tsx | 6 - components/ChatInput-banners.test.mjs | 67 +++ components/ChatInput-banners.tsx | 121 +++-- components/ChatInput-slash-commands.ts | 18 +- .../ChatInput.queue-attachments.test.mjs | 22 +- components/ChatInput.test.mjs | 14 +- components/ChatInput.tsx | 84 ++-- components/ChatWindow.tsx | 12 +- ...-29-native-slash-commands-and-goal-mode.md | 438 ++++++++++++++++++ hooks/useAgentSession-stream.ts | 43 +- hooks/useAgentSession.rpc.test.mjs | 96 +++- hooks/useAgentSession.ts | 196 ++++---- lib/goal-state.test.mjs | 81 ++++ lib/goal-state.ts | 99 ++++ lib/i18n/locales/en.json | 20 +- lib/i18n/locales/ja.json | 20 +- lib/i18n/locales/zh-CN.json | 20 +- lib/image-attachments.test.mjs | 2 +- lib/pi-types.ts | 32 ++ lib/rpc-manager.ts | 2 + lib/web-mode-state.test.mjs | 27 -- lib/web-mode-state.ts | 31 -- lib/web-slash-commands.test.mjs | 43 +- lib/web-slash-commands.ts | 52 +-- 26 files changed, 1233 insertions(+), 341 deletions(-) create mode 100644 components/ChatInput-banners.test.mjs create mode 100644 docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md create mode 100644 lib/goal-state.test.mjs create mode 100644 lib/goal-state.ts delete mode 100644 lib/web-mode-state.test.mjs diff --git a/AGENTS.md b/AGENTS.md index 7ea44cfe6..c6cbebdee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -945,6 +945,33 @@ errors surface as failed RPC responses plus `notice` events. New frame types (`turn_start/end`, `notice`, `todo_reminder`, ...) must be handled or safely ignored. +### Slash commands are omp's (`lib/web-slash-commands.ts`) +Full behavior and rationale: `docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md`. +- `get_available_commands` is authoritative. Every source it reports — + `builtin`, `extension`, `custom`, `mcp_prompt`, `file`, `skill` — runs + through `prompt`; never expand, hide, or shadow a name the catalog owns. The + palette shows all of them (`toSlashCommandInfo`), with `input.hint` as the + argument hint. +- Client-dispatched names are only the ones omp has no slash equivalent for: + `goal` (native `goal` RPC), `btw`, `reload`, `name`, `copy`. Web prompt + expansions (`plan`, `fix`, `test`, `explain`, `simplify`, `commit`, `loop`) + are used only when omp does not report the same name, so an extension or + skill command always wins. `/compact`, `/session`, `/review`, `/advisor` are + omp commands; the top-bar compact button and context ring remain the web + entry points for those panels. +- `/goal` is native goal mode: `{type:"goal",op:"create",objective}` plus + `goal_updated`/`get_state.goal`; pause/resume/drop send the matching op. No + `sessionStorage` goal state. Goal snapshots are sequenced so a slow + `get_state` cannot overwrite a newer `goal_updated` (same idea as the queue). +- TUI-only builtins (`guided-goal`, `vibe`, `budget`, and `/plan`/`/loop` when + absent from the catalog) have no RPC handler. `/plan`'s spec has only + `handleTui`, and `acp-builtins.ts` publishes only specs with a text-mode + `handle`. Hooks cannot call it either: hook `ctx` exposes a read-only + `sessionManager`, and extension `ctx.sessionModes` is undefined in + RPC/ACP. The hook warns once and still delivers the text. The only true + parity paths are an upstream text-mode `handle`/`set_mode` RPC or an embedded + PTY TUI. + ### Queued messages are omp-owned The queue panel renders omp's snapshot only: `get_state.queuedMessages` on load/reconcile/stream open and live `queue_update` frames. Never track chips diff --git a/CHANGELOG.md b/CHANGELOG.md index 33fc53506..a265c871b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -105,6 +105,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **The service installers set up the host daemon too.** `ompweb systemd install`, `ompweb-launchd install` and the Windows tray install now register `ompweb host` as a second unit (`ompweb-host`) next to the web service, restarting it after a 10 s delay so it can wait for the web server to write its host link on first install. `uninstall` and `status` cover both, and the tray menus show the daemon state. - **Forking a session or editing a message asks first.** The Fork button under a message and the Edit button under your own message now open a confirmation dialog, so a stray tap while scrolling no longer creates a new session or rewinds the current one. - **Expanded thinking blocks no longer collapse when a step finishes.** With "Expand thinking blocks by default" on, a thinking block opened while streaming, then moved into a closed Process details row as soon as the step committed. Thinking now stays out of the fold while the setting is on. +- **All omp slash commands run natively, including extension and skill commands.** The composer used to hide omp's builtins and expand `/goal`, `/review`, `/advisor`, `/compact`, and `/session` into text prompts. Every command omp reports in `get_available_commands` (builtin, extension, custom, MCP prompt, file, skill) is now shown and sent through omp's own prompt pipeline; web-only prompt expansions (`/plan`, `/fix`, `/test`, `/explain`, `/simplify`, `/commit`, `/loop`) yield to an omp command of the same name. `/goal` now uses omp's native goal RPC (`goal_updated` / `get_state.goal`) with pause, resume and drop controls instead of a `sessionStorage` imitation. TUI-only commands that omp does not expose over RPC still warn and are sent as plain text. - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. - **An update whose worker died is reported as failed.** A running update whose worker process is gone, or whose lease has expired, now becomes a failed attempt the dialog can show and clean up, instead of waiting forever. - **Upgrade ompweb before its hosts.** The web server links a host daemon one link protocol version older than its own, so a host keeps running sessions until its `ompweb` is updated. After a web restart the server adopts that daemon's live runs, as it does a current daemon's, without resuming them; only a large message from such a host still arrives whole instead of in pieces, which can stall that host's link on a slow connection. A daemon older than that, or newer than the web server, is still asked to upgrade. diff --git a/components/AppShell.tsx b/components/AppShell.tsx index cc14c0ddb..1e220a35d 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -752,11 +752,6 @@ export function AppShell({ appName }: { appName: string }) { }); }, [activeTopPanel, systemPrompt, systemPromptLoading, toggleTopPanel]); - // /session opens the same information panel as the top-bar control. - const openSessionStatsPanel = useCallback(() => { - chatInputRef.current?.openContextPanel(); - }, []); - const handleSidebarToggle = useCallback(() => { if (isMobile) { setActiveTopPanel(null); @@ -2596,7 +2591,6 @@ export function AppShell({ appName }: { appName: string }) { onSystemPromptChange={handleSystemPromptChange} onSystemPromptLoaderChange={handleSystemPromptLoaderChange} onSessionStatsChange={handleSessionStatsChange} - onSessionStatsPanelOpen={openSessionStatsPanel} sessionInfoContainer={sessionInfoContainer} onGenerationSpeedChange={handleGenerationSpeedChange} onOpenProviders={() => setSettingsTab("providers")} diff --git a/components/ChatInput-banners.test.mjs b/components/ChatInput-banners.test.mjs new file mode 100644 index 000000000..73397ab09 --- /dev/null +++ b/components/ChatInput-banners.test.mjs @@ -0,0 +1,67 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test, { afterEach } from "node:test"; +import React from "react"; +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react/pure.js"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tsconfigPaths: true }); +const { ComposerModeStatus } = await jiti.import("./ChatInput-banners.tsx"); + +const goal = (overrides = {}) => ({ + id: "g1", + objective: "ship the export", + status: "active", + tokensUsed: 1234, + timeUsedSeconds: 90, + createdAt: 1000, + updatedAt: Date.now(), + ...overrides, +}); +const state = (value) => ({ enabled: value.status === "active", mode: "active", goal: value }); +const flush = () => act(async () => { await Promise.resolve(); }); + +afterEach(async () => { + cleanup(); + await flush(); +}); + +test("an active goal shows its status, objective, tokens and pause/drop actions", async () => { + const actions = []; + render(React.createElement(ComposerModeStatus, { + goal: state(goal()), + onGoalAction: (op) => actions.push(op), + })); + + assert.match(screen.getByText(/ship the export/).textContent, /ship the export/); + assert.match(screen.getByText(/Goal active/).textContent, /1m/); + fireEvent.click(screen.getByRole("button", { name: /ship the export/ })); + + assert.match(screen.getByText(/1,234 tokens/).textContent, /1,234 tokens/); + fireEvent.click(screen.getByRole("button", { name: /^Pause$/ })); + await flush(); + fireEvent.click(screen.getByRole("button", { name: /^Drop$/ })); + await flush(); + assert.deepEqual(actions, ["pause", "drop"]); +}); + +test("a paused goal offers resume, and a finished goal offers no actions", async () => { + const actions = []; + const view = render(React.createElement(ComposerModeStatus, { + goal: state(goal({ status: "paused" })), + onGoalAction: (op) => actions.push(op), + })); + assert.match(screen.getByText(/Goal paused/).textContent, /Goal paused/); + fireEvent.click(screen.getByRole("button", { name: /ship the export/ })); + fireEvent.click(screen.getByRole("button", { name: /^Resume$/ })); + await flush(); + assert.deepEqual(actions, ["resume"]); + + view.rerender(React.createElement(ComposerModeStatus, { + goal: state(goal({ status: "completed" })), + onGoalAction: (op) => actions.push(op), + })); + fireEvent.click(screen.getByRole("button", { name: /ship the export/ })); + assert.match(screen.getByText(/Goal completed/).textContent, /Goal completed/); + assert.equal(screen.queryByRole("button", { name: /^(Pause|Resume|Drop)$/ }), null); +}); diff --git a/components/ChatInput-banners.tsx b/components/ChatInput-banners.tsx index 039a1b367..097dc49bb 100644 --- a/components/ChatInput-banners.tsx +++ b/components/ChatInput-banners.tsx @@ -1,9 +1,10 @@ "use client"; import React, { useEffect, useState } from "react"; -import { ListChecks, Target } from "lucide-react"; -import type { ActiveGoal, ActivePlan } from "@/lib/web-mode-state"; -import { formatGoalElapsed } from "@/lib/web-mode-state"; +import { ListChecks, Pause, Play, Target, Trash2 } from "lucide-react"; +import type { GoalModeState } from "@/lib/pi-types"; +import type { ActivePlan } from "@/lib/web-mode-state"; +import { formatGoalDuration, goalElapsedSeconds, isGoalControllable } from "@/lib/goal-state"; import { useI18n } from "@/lib/i18n"; /** Compact action button for the queued follow-up bar. */ @@ -99,46 +100,112 @@ export function ModelErrorBanner({ error }: { error?: string | null }) { ); } -export function ComposerModeStatus({ goal, plan }: { goal?: ActiveGoal | null; plan?: ActivePlan | null }) { - const { t } = useI18n(); +export function ComposerModeStatus({ + goal, + plan, + onGoalAction, +}: { + goal?: GoalModeState | null; + plan?: ActivePlan | null; + onGoalAction?: (op: "pause" | "resume" | "drop") => void | Promise; +}) { + const { t, locale } = useI18n(); const [expanded, setExpanded] = useState(false); const [now, setNow] = useState(() => Date.now()); + const [pendingAction, setPendingAction] = useState<"pause" | "resume" | "drop" | null>(null); + const goalInfo = goal?.goal ?? null; + const goalStatus = goalInfo?.status; + const goalId = goalInfo?.id ?? null; + const active = goalStatus === "active"; + const controllable = isGoalControllable(goal); useEffect(() => { - if (!goal) return; + if (!goalId) return; setExpanded(false); setNow(Date.now()); - const timer = window.setInterval(() => setNow(Date.now()), 30_000); + }, [goalId]); + + // omp streams updated timeUsedSeconds, but a live tick keeps the banner + // moving between frames. Display only — omp remains the state source. + useEffect(() => { + if (!active) return; + const timer = window.setInterval(() => setNow(Date.now()), 1_000); return () => window.clearInterval(timer); - }, [goal]); + }, [active]); + + if (!goalInfo && !plan) return null; + + const statusLabel = goalStatus === "active" + ? t("chatInput.goalActive") + : goalStatus === "paused" + ? t("chatInput.goalPaused") + : goalStatus === "completed" + ? t("chatInput.goalCompleted") + : goalStatus === "dropped" + ? t("chatInput.goalDropped") + : goalStatus ?? t("chatInput.goalActive"); + const runAction = (op: "pause" | "resume" | "drop") => { + if (!onGoalAction || pendingAction) return; + setPendingAction(op); + void Promise.resolve(onGoalAction(op)).finally(() => setPendingAction(null)); + }; - if (!goal && !plan) return null; return (
- {goal && ( - + + {expanded && ( +
+ + {t("chatInput.goalTokens", { count: new Intl.NumberFormat(locale).format(goalInfo.tokensUsed) })} + + {controllable && onGoalAction && ( +
+ {goalStatus === "active" ? ( + runAction("pause")} title={t("chatInput.pauseGoal")} disabled={pendingAction !== null}> + + ) : ( + runAction("resume")} title={t("chatInput.resumeGoal")} disabled={pendingAction !== null}> + + )} + runAction("drop")} title={t("chatInput.dropGoal")} disabled={pendingAction !== null}> + +
+ )} +
+ )} +
)} {plan && (
diff --git a/components/ChatInput-slash-commands.ts b/components/ChatInput-slash-commands.ts index fdfe83f29..3c04d2242 100644 --- a/components/ChatInput-slash-commands.ts +++ b/components/ChatInput-slash-commands.ts @@ -15,22 +15,30 @@ export function isDormantSkillCommand(command: SlashCommandPaletteItem, dormantN } export const BUILTIN_SLASH_COMMAND_DEFS: { name: string; descriptionKey: string; argumentHintKey?: string }[] = [ - // Web-native prompt-composing commands (goal/plan/... are TUI-only in omp and - // never execute over the RPC prompt path — see lib/web-slash-commands.ts). + // Web-native prompt-composing commands for names omp does not provide. When + // omp's catalog reports the same name (extension/custom/skill/builtin), the + // omp command wins and this entry is hidden. ...WEB_SLASH_COMMANDS.map((command) => ({ name: command.name, descriptionKey: command.descriptionKey, argumentHintKey: command.argumentHintKey, })), + // omp's goal mode is an RPC command, not a slash builtin. + { name: "goal", descriptionKey: "chatInput.cmdGoal", argumentHintKey: "chatInput.cmdGoalArg" }, { name: "btw", descriptionKey: "chatInput.cmdBtw", argumentHintKey: "chatInput.cmdBtwArg" }, - { name: "compact", descriptionKey: "chatInput.cmdCompact" }, { name: "reload", descriptionKey: "chatInput.cmdReload" }, { name: "name", descriptionKey: "chatInput.cmdName" }, - { name: "session", descriptionKey: "chatInput.cmdSession" }, { name: "copy", descriptionKey: "chatInput.cmdCopy" }, ]; -export const CLIENT_BUILTIN_COMMAND_NAMES = new Set(BUILTIN_SLASH_COMMAND_DEFS.map((def) => def.name)); +/** Commands omp has no slash equivalent for: the client always dispatches these. */ +export const CLIENT_ONLY_COMMAND_NAMES: Record = { + goal: true, + btw: true, + reload: true, + name: true, + copy: true, +}; export const SLASH_SOURCES: SlashCommandSource[] = ["builtin", "extension", "prompt", "skill", "ompBuiltin"]; diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 515de6902..16150e883 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -160,12 +160,30 @@ test("a queued web slash command is expanded and keeps the attachments", async ( window.HTMLElement.prototype.scrollIntoView = () => {}; const user = userEvent.setup(); const calls = await renderRunningWithAttachments(); - await user.type(screen.getByRole("textbox"), "/goal ship it"); + await user.type(screen.getByRole("textbox"), "/plan ship it"); await user.keyboard("{Enter}"); await waitFor(() => assert.equal(calls.length, 1)); delete window.HTMLElement.prototype.scrollIntoView; assert.equal(calls[0].name, "onFollowUp", "a slash command is held like any follow-up; the server sends it as a prompt"); - assertQueuedWithAttachments(calls[0], expandWebSlashCommand("/goal ship it").prompt); + assertQueuedWithAttachments(calls[0], expandWebSlashCommand("/plan ship it").prompt); +}); + +test("a queued /goal runs the native goal RPC instead of entering the prompt queue", async () => { + window.HTMLElement.prototype.scrollIntoView = () => {}; + const user = userEvent.setup(); + const builtins = []; + const calls = await renderRunningWithAttachments({ + onBuiltinCommand: async (message) => { + builtins.push(message); + return { handled: true }; + }, + }); + await user.type(screen.getByRole("textbox"), "/goal ship it"); + await user.keyboard("{Enter}"); + await waitFor(() => assert.deepEqual(builtins, ["/goal ship it"])); + delete window.HTMLElement.prototype.scrollIntoView; + assert.equal(calls.length, 0, "no prompt is queued"); + await waitFor(() => assert.equal(getDraft(KEY), null)); }); test("a queued message stays in the composer until the outbox has it, and stays whole when refused", async () => { diff --git a/components/ChatInput.test.mjs b/components/ChatInput.test.mjs index 15d9e3e15..1e50fdfe2 100644 --- a/components/ChatInput.test.mjs +++ b/components/ChatInput.test.mjs @@ -194,7 +194,19 @@ test("renders goal, planning, and advisor indicators at the composer", () => { model: { provider: "test", modelId: "model" }, modelList: [{ provider: "test", modelId: "model", id: "model", name: "Test model" }], modelNames: {}, - activeGoal: { objective: "Ship the active goal bar", startedAt: 0 }, + goalState: { + enabled: true, + mode: "active", + goal: { + id: "goal-1", + objective: "Ship the active goal bar", + status: "active", + tokensUsed: 42, + timeUsedSeconds: 60, + createdAt: 0, + updatedAt: 0, + }, + }, activePlan: { objective: "Plan the implementation" }, advisorEnabled: true, onAdvisorChange() {}, diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 0864a4441..0da08be1c 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -5,12 +5,12 @@ import { createPortal } from "react-dom"; import { ChevronDown, ClipboardPaste, CornerDownRight, ListChecks, Loader2, Mic, Paperclip, Plus, RotateCw, Shrink, Snail, Sparkles, Wrench, X, Zap } from "lucide-react"; import { getSubmitDuringRunBehavior, isWordCompletionEnabled } from "@/lib/composer-prefs"; import type { BuiltinSlashCommandResult, CompactResultInfo, PromptSubmissionResult, QueuedMessages, SlashCommandInfo } from "@/hooks/useAgentSession"; -import type { ActiveGoal, ActivePlan } from "@/lib/web-mode-state"; +import type { ActivePlan } from "@/lib/web-mode-state"; import { toast } from "@/components/ui/toast"; import { ConfirmDialog } from "@/components/ui/field"; import { useDictation } from "@/hooks/useDictation"; import { toastBtwError } from "@/hooks/useBtw"; -import type { GenerationSpeedInfo, SessionStatsInfo, SlowModeScope, UsageLimitState } from "@/lib/pi-types"; +import type { GenerationSpeedInfo, GoalModeState, SessionStatsInfo, SlowModeScope, UsageLimitState } from "@/lib/pi-types"; import type { SttAfter } from "@/lib/stt"; import { formatCompactNumber, formatPercent } from "@/lib/format"; import { ContextDetailPanel } from "./ComposerPanels"; @@ -40,7 +40,7 @@ import { MAX_UPLOAD_BYTES, MAX_UPLOADS_PER_MESSAGE } from "@/lib/upload-limits"; import { hostProjectKey, LOCAL_HOST_ID } from "@/lib/project-ordering"; import { BUILTIN_SLASH_COMMAND_DEFS, - CLIENT_BUILTIN_COMMAND_NAMES, + CLIENT_ONLY_COMMAND_NAMES, SLASH_SOURCE_GROUP_LABEL_KEYS, SLASH_SOURCE_ORDER, SLASH_SOURCES, @@ -257,7 +257,10 @@ interface Props { draftIdentityMove?: { from: string; to: string; sourceDraft?: ChatDraft }; /** Session working directory — enables the @ file autocomplete menu */ cwd?: string | null; - activeGoal?: ActiveGoal | null; + /** omp-owned goal mode snapshot (null = no goal, undefined = not reported yet). */ + goalState?: GoalModeState | null; + /** Pause/resume/drop the omp-owned goal. */ + onGoalAction?: (op: "pause" | "resume" | "drop") => void | Promise; activePlan?: ActivePlan | null; advisorEnabled?: boolean; /** Toggle the per-chat advisor (composer icon + /advisor command). */ @@ -276,7 +279,6 @@ export interface ChatInputHandle { insertIfEmpty: (text: string) => void; prependText: (text: string) => void; addFiles: (files: File[]) => void; - openContextPanel: () => void; /** Retarget captured queue recoveries before a confirmed move can render. */ retargetPendingRecovery: (from: string, to: string) => void; } @@ -382,7 +384,8 @@ export const ChatInput = memo(forwardRef(function ChatIn uploadHostId = LOCAL_HOST_ID, draftIdentityMove, cwd, - activeGoal, + goalState, + onGoalAction, activePlan, advisorEnabled, onAdvisorChange, @@ -421,6 +424,12 @@ export const ChatInput = memo(forwardRef(function ChatIn items[next]?.focus(); }, []); const { t, tn, locale } = useI18n(); + // Names omp's catalog reports. A web prompt expansion of the same name must + // yield to omp's own command (extension/custom/skill/builtin). + const ompCommandNames = React.useMemo( + () => new Set((slashCommands ?? []).map((command) => command.name)), + [slashCommands], + ); const usageLimitLabel = usageLimit ? formatUsageLimitLabel(usageLimit, t) : undefined; @@ -630,9 +639,6 @@ export const ChatInput = memo(forwardRef(function ChatIn addFiles(files: File[]) { processFiles(files); }, - openContextPanel() { - setContextOpen(true); - }, retargetPendingRecovery(from, to) { const identity = draftRecoveryIdentityRef.current; if (identity.key === from) { @@ -1253,7 +1259,10 @@ export const ChatInput = memo(forwardRef(function ChatIn if (rejectsPendingUploads()) return; const composedMessage = composeMessageWithTextAttachments(msg, attachedTextFilesRef.current); if (!attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length && msg.startsWith("/") && onBuiltinCommand) { - const expansion = expandWebSlashCommand(msg); + const commandName = msg.slice(1).split(/\s+/)[0]; + const expansion = ompCommandNames.has(commandName) + ? { kind: "not-web" as const } + : expandWebSlashCommand(msg); if (expansion.kind === "expand" && rejectsOversizedPrompt(expansion.prompt, attachedImagesRef.current)) return; if (await runBuiltinCommand(msg, overrideText)) return; } @@ -1293,7 +1302,7 @@ export const ChatInput = memo(forwardRef(function ChatIn if (key) recoverDraft(key, recovery); throw error; } - }, [value, isStreaming, onBuiltinCommand, onSend, outbox, clearInput, clearOnceStored, onAudioUnlock, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); + }, [value, isStreaming, onBuiltinCommand, onSend, outbox, clearInput, clearOnceStored, onAudioUnlock, ompCommandNames, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); const { isRecording, isPaused, @@ -1410,30 +1419,29 @@ export const ChatInput = memo(forwardRef(function ChatIn const builtinSlashCommands: SlashCommandPaletteItem[] = React.useMemo( () => BUILTIN_SLASH_COMMAND_DEFS - // The /advisor command is linked to Settings → Enable Advisor: hidden - // from the palette while the advisor is disabled. - .filter((def) => def.name !== "advisor" || advisorEnabled) + // Client-only actions always stay; web prompt expansions yield to an + // omp command with the same name. + .filter((def) => CLIENT_ONLY_COMMAND_NAMES[def.name] === true || !ompCommandNames.has(def.name)) .map((def) => ({ name: def.name, description: t(def.descriptionKey), ...(def.argumentHintKey ? { argumentHint: t(def.argumentHintKey) } : {}), source: "builtin" as const, })), - [t, advisorEnabled], + [t, ompCommandNames], ); - // Externally reported commands (extension/prompt/skill/ompBuiltin) group - // below the client built-ins; any name the web UI intercepts itself — - // whether an omp builtin or a user extension — is dropped so each command - // appears exactly once and the client interception behavior is unchanged. + // Externally reported commands group below the client built-ins. A name the + // client always dispatches itself is dropped so it appears exactly once. const externalSlashCommands: SlashCommandPaletteItem[] = React.useMemo( () => (slashCommands ?? []).flatMap((command): SlashCommandPaletteItem[] => { - const source = command.source as string; - if (CLIENT_BUILTIN_COMMAND_NAMES.has(command.name)) return []; - if (source === "builtin" || source === "ompBuiltin") { - return [{ name: command.name, description: command.description, source: "ompBuiltin" }]; - } - return [command]; + if (CLIENT_ONLY_COMMAND_NAMES[command.name] === true) return []; + return [{ + name: command.name, + description: command.description, + ...(command.argumentHint ? { argumentHint: command.argumentHint } : {}), + source: command.source === "builtin" ? "ompBuiltin" : command.source, + }]; }), [slashCommands], ); @@ -1772,19 +1780,23 @@ export const ChatInput = memo(forwardRef(function ChatIn }; const files = attachedTextFilesRef.current; onAudioUnlock?.(); + if (msg.startsWith("/")) { const commandName = msg.slice(1).split(/\s+/)[0]; - // Same gate as the direct path (useAgentSession refuses /advisor while - // disabled): queueing must not become a bypass around the toggle. - if (commandName === "advisor" && !advisorEnabled) { - toast.error(t("agentSession.advisorDisabled")); + // Client-dispatched commands (/goal uses the native goal RPC, /btw is a + // side question) must not enter the prompt queue: omp would treat the + // text as an ordinary message. Run them now, mid-run included. + if (CLIENT_ONLY_COMMAND_NAMES[commandName] === true) { + if (onBuiltinCommand) void runBuiltinCommand(msg, overrideText); return; } - // Web commands must be expanded even when queued: the raw slash text - // would otherwise reach omp as a literal message (its /goal //plan are - // TUI-only). Action commands (compact/...) keep the raw text so omp's - // own ACP handlers can run them. - const expansion = expandWebSlashCommand(msg); + // Web-only prompt expansions (/plan, /fix, ...) must be expanded even + // when queued. A name omp's catalog owns is never expanded: omp runs + // the original command line (extension/custom/skill/builtin) on + // delivery. + const expansion = ompCommandNames.has(commandName) + ? { kind: "not-web" as const } + : expandWebSlashCommand(msg); if (expansion.kind === "expand") { const prompt = composeMessageWithTextAttachments(expansion.prompt, files); if (rejectsOversizedPrompt(prompt, attachedImagesRef.current)) return; @@ -1802,7 +1814,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const composedMessage = composeMessageWithTextAttachments(msg, files); if (rejectsOversizedPrompt(composedMessage, attachedImagesRef.current)) return; hold(composedMessage); - }, [value, handleSend, onSteer, onFollowUp, clearOnceStored, onAudioUnlock, t, advisorEnabled, rejectsOversizedPrompt, rejectsPendingUploads, sendSideQuestion]); + }, [value, handleSend, onSteer, onFollowUp, clearOnceStored, onAudioUnlock, t, ompCommandNames, onBuiltinCommand, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); // A typed message or attachment during a run is a queued follow-up — and so // is a dictation in progress: the primary button must take the same state it // would have if the composer already held text. Keep Stop as the action @@ -2382,7 +2394,7 @@ export const ChatInput = memo(forwardRef(function ChatIn />
- + {/* Retry banner */} {retryInfo && (() => { const remainingSec = (retryInfo.delayMs !== undefined && retryInfo.startedAt !== undefined) diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 7f03f2777..0d79a82e5 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -81,7 +81,6 @@ interface Props { onSystemPromptChange?: (prompt: string | null) => void; onSystemPromptLoaderChange?: (loader: (() => Promise) | null) => void; onSessionStatsChange?: (stats: SessionStatsInfo | null) => void; - onSessionStatsPanelOpen?: () => void; onProviderUsageContextChange?: (context: ProviderUsageContext | null) => void; onOpenFile?: (filePath: string, name: string, source: WorkspaceFileSource) => void; /** Handles the open_url host tool; returns the result text for the agent. */ @@ -393,7 +392,7 @@ const CommittedTranscript = memo(function CommittedTranscript({ ); }); -export function ChatWindow({ session, newSessionCwd, newSessionHostId, 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, 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, onProviderUsageContextChange, onGenerationSpeedChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, onOpenProviders, searchQuery = "", searchTarget = null, onSearchTargetHandled }: Props) { const { t, tn } = useI18n(); const fileSource = useMemo(() => ({ hostId: session?.hostId ?? newSessionHostId ?? "local", @@ -452,13 +451,13 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu notices, dismissNotice, extensionDialog, extensionCustomUi, extensionStatuses, extensionWidgets, respondToExtensionUi, sendExtensionCustomInput, skillDiagnostics, setSkillStartupDiagnostics, isAutoModelSelection, - agentPhase, activeGoal, activePlan, + agentPhase, goalState, activePlan, liveToolResults, subagents, subagentEvents, subagentTranscriptVersions, activeSubagentCount, currentTodoPhase, todoPhases, isNew, hostStatus: frameHostStatus, sessionIdRef, messagesEndRef, scrollContainerRef, holdScrollPosition, handleSend, handleAbort, handleFork, handleEdit, handleModelChange, retrySession, - handleSteer, handleFollowUp, handleAbortCompaction, handleCompact, + handleSteer, handleFollowUp, handleAbortCompaction, handleCompact, handleGoalAction, heldMessages, deleteHeldMessage, removeQueuedMessage, promoteQueuedToSteer, handleBuiltinSlashCommand, togglePreCompactionHistory, @@ -467,7 +466,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu btw, askBtw, } = useAgentSession({ session, newSessionCwd, newSessionHostId, onAgentEnd: wrappedOnAgentEnd, onSessionCreated, onSessionForked, onSessionMoved: handleSessionMoved, - modelsRefreshKey, chatInputRef: composerRef, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsPanelOpen, + modelsRefreshKey, chatInputRef: composerRef, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, }); useEffect(() => { @@ -1050,7 +1049,8 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu thinkingLevelMap={currentThinkingLevelMap} modelNameOverride={liveModelMeta?.name ?? null} retryInfo={retryInfo} - activeGoal={activeGoal} + goalState={goalState} + onGoalAction={handleGoalAction} activePlan={activePlan} advisorEnabled={advisorEnabled} onAdvisorChange={handleAdvisorChange} diff --git a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md new file mode 100644 index 000000000..5afd67c76 --- /dev/null +++ b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md @@ -0,0 +1,438 @@ +# Native Slash Commands and Goal Mode + +- **Status:** Implemented +- **Date:** 2026-10-29 +- **Scope:** omp-web command dispatch, native goal mode, extension/skill commands +- **omp baseline:** 18.13.3+ (`rpc-ui` protocol) + +## 1. Summary + +omp-web used to treat `/goal`, `/review`, `/advisor`, `/compact`, and `/session` +as client-side prompt expansions, and it hid every `builtin` command from the +composer palette. That made real omp commands look unavailable and made a +text prompt look like goal mode. + +The implementation now treats `get_available_commands` as the single source of +truth: + +- Every command omp reports — `builtin`, `extension`, `custom`, `mcp_prompt`, + `file`, and `skill` — is shown in the palette and sent to omp through the + normal `prompt` path. +- `/goal` uses omp's native `goal` RPC and `goal_updated` / + `get_state.goal` state. +- Web-only prompt expansions are used only for names omp does not provide, and + they yield to an omp command of the same name. +- TUI-only commands that omp does not expose over RPC are still reported as + plain text with a warning; they are not simulated. + +## 2. Goals + +- `/goal ` creates a real omp goal, with pause/resume/drop and live + token/time/status state. +- No `sessionStorage` goal state and no fake "Goal active" banner. +- Refresh, a new tab, or a session switch shows the same goal state omp reports. +- All command sources are discoverable, including extension-registered and + skill commands. +- The composer never expands, hides, or blocks a name that omp's catalog owns. + +## 3. Non-goals + +- No token-budget UI (`goal` RPC supports `token_budget`, but the UI does not). +- No automatic writes to the user's omp `config.yml`. +- No TUI-only command emulation for commands with no RPC surface. +- No generic `run_command` RPC or embedded PTY terminal. + +## 4. Command architecture + +### 4.1 Catalog authority + +`get_available_commands` (and `available_commands_update`) is authoritative. +Each command carries `name`, `source`, optional `aliases`, `description`, +`input.hint`, and `subcommands`. + +omp's RPC prompt path executes: + +| Source | Execution | +| --- | --- | +| `builtin` | omp's text-mode builtin handler | +| `extension` | registered extension command handler | +| `custom` | TypeScript/MCP custom command | +| `mcp_prompt` | MCP prompt | +| `file` | markdown slash command | +| `skill` | `/skill:` injection | + +omp's own command pipeline handles these before the model request, so omp-web +sends the original command line. The client does not reimplement them. + +### 4.2 Client-owned commands + +These names have no omp slash equivalent and are dispatched by +`handleBuiltinSlashCommand`: + +- `goal` — native `goal` RPC (section 5). +- `btw` — side-question RPC and panel. +- `reload` — reload omp resources, slash commands, and models. +- `name` — `set_session_name`. +- `copy` — copy the last assistant text. + +They are listed in `CLIENT_ONLY_COMMAND_NAMES` +(`components/ChatInput-slash-commands.ts`). + +### 4.3 Web-only prompt expansions + +`lib/web-slash-commands.ts` keeps prompt expansions for names omp does not +provide: `plan`, `fix`, `test`, `explain`, `simplify`, `commit`, `loop`. + +Precedence rules: + +- If omp reports the same name, the web entry is hidden and the original + command line is sent to omp. +- If omp does not report it, the expansion is sent through the normal prompt + pipeline. +- The palette labels these under **Web commands**, separate from + **omp commands**, **Extensions**, **Prompts**, and **Skills**. + +### 4.4 Palette behavior + +- All sources are shown; `builtin` is no longer filtered out. +- `input.hint` becomes the argument hint. +- Client-owned names are dropped from the external list so each command appears + once. +- Web prompt expansions are dropped when `ompCommandNames` contains the name. +- While a run is streaming, client-owned commands are hidden from the palette + but still work when typed; the streaming path intercepts them before the + prompt queue. + +### 4.5 Streaming behavior + +`ChatInput.sendQueued` handles commands in this order: + +1. `/btw` — side question, never a prompt. +2. Client-owned command — `runBuiltinCommand` immediately, never queued. +3. Web-only expansion — expand and queue with `prompt` + + `streamingBehavior`. +4. omp command — queue the original command line; omp executes it on delivery + (extension commands run immediately; builtins/custom/file/skill follow + omp's streaming rules). + +This is what makes `/goal` work during a run: the goal RPC is sent while the +current turn continues, and omp decides continuation at the next terminal +`agent_end`. + +## 5. Native goal mode + +### 5.1 RPC surface + +omp exposes: + +```json +{ "type": "goal", "op": "get" | "create" | "resume" | "pause" | "drop", + "objective": "optional", "token_budget": 123 } +``` + +The command answers `{ goal: Goal | null, state: GoalModeState | null }`. +`get_state.goal` carries the same state. `goal_updated` reports every change, +including changes made by the agent's `goal` tool. + +Shapes: + +```json +{ + "id": "…", + "objective": "…", + "status": "active", + "tokensUsed": 0, + "timeUsedSeconds": 0, + "createdAt": 1793283016449, + "updatedAt": 1793283016449 +} +``` + +```json +{ "enabled": true, "mode": "active", "goal": { "…": "Goal or null" } } +``` + +Notes: + +- `get_state.goal` is `GoalModeState | null`. +- The command response is `{ goal, state }`; `drop` may answer + `state: null` while the event still carries a `dropped` state. +- Unknown statuses are preserved. +- `create` requires `goal.enabled`, a non-empty objective, and no active or + paused goal. It is refused in plan mode. +- RPC does not auto-continue goals unless `goal.continuationModes` contains + `"rpc"`. That is a user configuration choice, not an omp-web bug. + +### 5.2 Types and parsing + +`lib/pi-types.ts` defines `GoalStatus`, `Goal`, `GoalModeState`, and +`GoalCommandResponse`, and adds `goal?: GoalModeState | null` to +`RpcSessionState` and `WebSessionState`. + +`lib/goal-state.ts` provides defensive readers: + +- `readGoalModeState` +- `readGoalUpdatedEvent` +- `readGoalCommandResponse` +- `hasGoal` +- `isGoalControllable` +- `goalElapsedSeconds` +- `formatGoalDuration` +- `isStaleGoalState` + +A present-but-malformed goal is rejected rather than treated as "no goal". + +### 5.3 Server plumbing + +`lib/rpc-manager.ts`: + +- Adds `"goal"` to `PASSTHROUGH_COMMANDS`. +- Maps `state.goal` into `WebSessionState` when omp reports it. +- Forwards `goal_updated` through the existing default event path. + +`hooks/useAgentSession-stream.ts` adds `goal` to `AgentStateResponse`. + +### 5.4 Client state and race handling + +`hooks/useAgentSession.ts` owns `goalState` and a monotonic `goalSeqRef`: + +- `publishGoalState` increments the sequence and applies an event/response. +- `applyGoalSnapshot` applies a `get_state` snapshot only if no newer event or + response arrived while it was in flight. +- `isStaleGoalState` prevents a slower response with an older `updatedAt` from + overwriting a newer goal. +- `loadSession`, `refreshAgentSnapshots`, and `reconcileAgentState` all feed the + goal snapshot. +- `goal_updated` publishes the event state. + +Session switching: + +- A genuine switch clears the goal immediately and waits for the new session's + `get_state`. +- Promoting an empty new chat to its real session id is not a switch; the guard + `session.id === sessionIdRef.current` keeps the goal that was just created. + +### 5.5 UI + +`components/ChatInput-banners.tsx` renders the real state: + +- Status label: active, paused, completed, dropped, or the raw unknown status. +- Objective, `tokensUsed`, and `timeUsedSeconds`. +- A live timer extrapolates from `updatedAt` only while active; omp remains the + source of truth. +- Active: **Pause** and **Drop**. +- Paused: **Resume** and **Drop**. +- Completed/dropped: no actions; the banner disappears when omp sends `null`. +- Buttons disable while an action is in flight. + +`ChatWindow` passes `goalState` and `handleGoalAction` into `ChatInput`. + +### 5.6 Commands + +`/goal `: + +- Requires a non-empty objective. +- Sends `{ type: "goal", op: "create", objective }`. +- Never sends a prompt and never inserts the old + "Work toward this goal…" message. +- Promotes a new chat to the real session id after success. +- Shows omp's error and keeps the existing goal when create fails. + +`handleGoalAction("pause" | "resume" | "drop")` sends the matching RPC and +publishes the response state. + +## 6. Native `/compact` and `/session` + +- `/compact` is now omp's builtin, so `soft`, `remote`, `snapcompact`, and focus + text work. `manual_compaction_start` / `manual_compaction_end` update + `isCompacting`, `compactResult`, and `compactError`, then reload the session. + The composer/top-bar compact button still uses the `compact` RPC. +- `/session` is now omp's builtin (`info`, `delete`, `pin`). The web stats panel + is still available from the context ring; the old `/session` panel shortcut + and its `onSessionStatsPanelOpen` plumbing were removed. + +## 7. `/review` and `/advisor` + +Both were removed from the web expansion list. omp's `review` (custom or +builtin) and `advisor` builtin are shown in the catalog and executed by omp. +The composer's per-chat advisor toggle remains a web spawn flag; it is +independent of the native `/advisor` command. + +## 8. Skills and extension commands + +- `skill` commands appear when omp reports them (`/skill:`). +- Typed `/skill:` is forwarded through `prompt`; omp injects the skill + body and runs the turn. +- Extension and custom commands are shown with their source group and executed + by omp. +- `slashCommandRosterNames` includes aliases, so `/models` (alias of `/model`) + is recognized. +- `/reload` re-reads the catalog; a newly installed skill appears in the + **Skills** group after reload. + +## 9. `/plan` and `/loop` limitation + +omp has native `/plan` and `/loop`, but both are **TUI-only**. + +### 9.1 `/plan` + +```ts +// packages/coding-agent/src/slash-commands/builtin-modes.ts +{ + name: "plan", + description: "Toggle plan mode (agent plans before executing)", + allowArgs: true, + handleTui: async (command, runtime) => { + await runWithDetachedDraft(command, runtime, () => + runtime.ctx.handlePlanModeCommand(command.args || undefined, runtime.input), + ); + }, +} +``` + +```ts +// packages/coding-agent/src/slash-commands/acp-builtins.ts +export const ACP_BUILTIN_SLASH_COMMANDS = BUILTIN_SLASH_COMMANDS_INTERNAL + .filter(command => command.handle !== undefined); +``` + +Consequences: + +- `/plan` is absent from `get_available_commands`. +- `executeAcpBuiltinSlashCommand` returns `false` for a TUI-only entry, so a + `/plan` prompt is delivered as literal text. +- `AgentSession` has `getPlanModeState()` / `setPlanModeState()`, but RPC does + not expose them: `get_state` has no plan field and there is no `set_mode`, + `plan`, or `run_command` RPC. +- Hooks cannot call it: hook `ctx` exposes a read-only `sessionManager`, not + the `AgentSession`. +- Extension `ctx.sessionModes` is `undefined` in RPC/ACP; it is TUI-only. +- Monkey-patching `AgentSession.prototype` from an in-process extension is + technically possible but unsupported, version-fragile, and would have to + reimplement the TUI plan-mode transition (plan model switch, tool + restrictions, plan file, context injection). It is not shipped. + +### 9.2 `/loop` + +`/loop` has the same shape, with an even smaller surface: + +```ts +// packages/coding-agent/src/slash-commands/builtin-modes.ts +{ + name: "loop", + allowArgs: true, + handleTui: async (command, runtime) => { + const prompt = await runtime.ctx.handleLoopCommand(command.args); + clearSubmittedText(runtime); + if (prompt) return { prompt }; + }, +} +``` + +- The loop state (`loopModeEnabled`, `loopModePaused`, `loopPrompt`, + `loopLimit`, `loopCondition`) lives in `InteractiveModeContext`, not in + `AgentSession`. There is no session-level API to call and no `set_loop` + RPC. +- `ctx.sessionModes` can drive loop in the TUI, but it is `undefined` in + RPC/ACP. +- The web `/loop` entry is a prompt expansion that asks the model to retry up + to N attempts. It is **not** omp's loop mode: it does not resubmit after + each yield, has no pause/resume, no count/duration bound enforcement, and no + `--while` / `--until` condition. +- A client-side loop that resends after `agent_end` would be emulation, not + native support, and would have to reimplement bounds, conditions, pause, + and interruption semantics. It is out of scope. + +### 9.3 Shared limitation and upstream path + +omp-web therefore keeps `/plan` and `/loop` as clearly labeled **Web commands** +prompt expansions. If omp adds a text-mode `handle` or a `set_mode` RPC, +omp-web automatically defers to it: + +- The palette hides a web entry when `ompCommandNames` contains the same name. +- `handleBuiltinSlashCommand` returns `{ handled: false }` when the roster owns + the name, so the original command line reaches omp. + +## 10. Persistence and known limits + +- A goal is journaled by omp in the session. Reload restores it from + `get_state.goal` once the session has a `.jsonl` file. +- omp writes a session file lazily on the first message. A goal created on an + empty new chat and followed by an immediate full reload has no file to list, + so the session cannot be reopened until a message is sent. This is omp's + persistence behavior, not a web state source. +- Goal continuation over RPC requires `goal.continuationModes` to include + `"rpc"`; the default does not. +- TUI-only commands (`guided-goal`, `vibe`, `budget`, and `/plan`/`/loop` when + absent from the catalog) are sent as plain text with a one-time warning. +- A malformed or unsupported `goal` RPC (older omp) surfaces omp's error; there + is no fallback to the old fake goal. + +## 11. Implementation map + +- `lib/goal-state.ts` — defensive goal readers and formatting. +- `lib/pi-types.ts` — goal types and state fields. +- `lib/rpc-manager.ts` — `goal` passthrough and `get_state.goal` mapping. +- `hooks/useAgentSession-stream.ts` — `AgentStateResponse.goal`, catalog + mapping, roster aliases. +- `hooks/useAgentSession.ts` — goal state sequencing, `/goal`, goal actions, + command precedence, manual compaction events. +- `components/ChatInput.tsx` — catalog precedence, client-only commands, + streaming interception, goal props. +- `components/ChatInput-slash-commands.ts` — client-owned command sets and + palette defs. +- `components/ChatInput-banners.tsx` — real goal banner and controls. +- `components/ChatWindow.tsx` — goal plumbing. +- `lib/web-slash-commands.ts` — web-only expansions; `goal`, `review`, and + `advisor` removed. +- `lib/web-mode-state.ts` — `ActivePlan` only. +- `lib/i18n/locales/{en,zh-CN,ja}.json` — goal status/control copy and group + labels. +- `lib/goal-state.test.mjs`, `components/ChatInput-banners.test.mjs`, + `hooks/useAgentSession.rpc.test.mjs` — goal lifecycle, parsing, streaming, + persistence, and command routing. + +## 12. Verification + +- `tsc --noEmit` passes. +- `eslint .` reports 0 errors (existing warnings only). +- Full test suite: 1701 passed, 17 skipped. One environment-only failure in + `lib/project-registry.test.mjs` was caused by a broken `node` shim on the + test machine; re-running that file with a correct `PATH` passes 15/15. +- Headed-browser smoke test against a live omp child: + - `/goal ship the export feature` sent only + `{"type":"goal","op":"create","objective":"ship the export feature"}` and + showed an active goal banner. + - Pause, resume, and drop sent only the matching `goal` op; the banner + tracked each state. + - A goal created while the agent was streaming sent the goal RPC and did not + queue a `/goal` prompt. + - A page reload restored the active/paused goal from `get_state.goal`. + - `/session` and `/tools` produced omp's `command_output`; `/skill:` + injected the skill and returned the skill's answer. + - After `/reload`, the palette showed Web commands, Extensions, Prompts, + Skills, and 46 omp commands. + +## 13. Upstream follow-ups + +To make `/plan`, `/vibe`, and `/loop` truly available over RPC, omp needs one +of: + +1. A text-mode `handle` on the builtin spec (the `SlashCommandRuntime` already + exposes the `AgentSession`), or +2. An RPC `set_mode` / `sessionModes` surface, or +3. A generic `run_command` RPC. + +Until then, the only full-parity option is embedding a PTY running the real +omp TUI. + +## 14. References + +- omp RPC docs: `goal` payload, `goal_updated`, available commands. +- omp source: + - `packages/coding-agent/src/slash-commands/builtin-modes.ts` + - `packages/coding-agent/src/slash-commands/acp-builtins.ts` + - `packages/coding-agent/src/session/agent-session.ts` + - `packages/coding-agent/src/extensibility/extensions/types.ts` + - `packages/coding-agent/src/extensibility/extensions/runner.ts` +- omp-web docs: `AGENTS.md` (Slash commands), `CHANGELOG.md`. diff --git a/hooks/useAgentSession-stream.ts b/hooks/useAgentSession-stream.ts index 4b5b9e221..bb1d3f666 100644 --- a/hooks/useAgentSession-stream.ts +++ b/hooks/useAgentSession-stream.ts @@ -12,7 +12,7 @@ import type { } from "@/lib/types"; import type { EventStream } from "@/lib/event-stream"; import type { ThinkingModelMeta } from "@/lib/thinking-levels"; -import type { QueuedMessages, RpcAvailableSlashCommand, SlowModeScope, TodoPhase, UsageLimitState } from "@/lib/pi-types"; +import type { GoalModeState, QueuedMessages, RpcAvailableSlashCommand, SlowModeScope, TodoPhase, UsageLimitState } from "@/lib/pi-types"; import type { SubagentHistoryEntry, SubagentInfo, @@ -203,6 +203,8 @@ export type AgentStateResponse = { queuedMessages?: QueuedMessages; /** Untrusted until parsed by parseSkillDiagnosticsSnapshot. */ skillDiagnostics?: unknown; + /** omp goal mode; absent on builds without the goal RPC. */ + goal?: GoalModeState | null; todoPhases?: TodoPhase[]; }; @@ -241,7 +243,9 @@ export interface CompactResultInfo { export interface SlashCommandInfo { name: string; description?: string; - source: "extension" | "prompt" | "skill"; + source: "builtin" | "extension" | "prompt" | "skill"; + /** Bracketed argument hint from omp's `input.hint`. */ + argumentHint?: string; sourceInfo?: { path: string; source: string; @@ -253,7 +257,7 @@ export interface SlashCommandInfo { export type BuiltinSlashCommandResult = | { handled: false } - | { handled: true; message?: string; error?: string; action?: "openSessionStats"; retainInput?: boolean }; + | { handled: true; message?: string; error?: string; retainInput?: boolean }; export type ThinkingLevelOption = string; @@ -522,17 +526,29 @@ export type SlashCommandsResponse = { commands?: RpcAvailableSlashCommand[]; }; -// Map omp's slash-command sources onto the palette's grouping. Builtins are -// skipped: the client intercepts its own builtin set, and other omp builtins -// still work when typed (omp executes them via the prompt command). -export function toSlashCommandInfo(command: RpcAvailableSlashCommand): SlashCommandInfo | null { - if (command.source === "builtin") return null; +/** Every invocable spelling: primary names plus omp's aliases (`/models` for `/model`). */ +export function slashCommandRosterNames(commands: readonly RpcAvailableSlashCommand[]): string[] { + return commands.flatMap((command) => [command.name, ...(command.aliases ?? [])]); +} + +// Map omp's slash-command sources onto the palette's grouping. Every source is +// shown: omp's RPC catalog contains only text-capable commands, so a prompt +// carrying one executes it. The composer still hides names the client +// dispatches itself, so each command appears once. +export function toSlashCommandInfo(command: RpcAvailableSlashCommand): SlashCommandInfo { const source: SlashCommandInfo["source"] = command.source === "extension" ? "extension" : command.source === "skill" ? "skill" - : "prompt"; - return { name: command.name, description: command.description, source }; + : command.source === "builtin" + ? "builtin" + : "prompt"; + return { + name: command.name, + description: command.description, + source, + ...(command.input?.hint ? { argumentHint: command.input.hint } : {}), + }; } // omp exposes only the commands its RPC prompt path can actually run. TUI-only @@ -540,10 +556,9 @@ export function toSlashCommandInfo(command: RpcAvailableSlashCommand): SlashComm // so the client has no way to run them and sending one lands in the transcript // as literal prompt text with no hint that nothing happened (#167). // -// Callers pass the FULL command list — including the builtins that -// `toSlashCommandInfo` hides from the palette, which are still executed by omp -// when typed and therefore must not warn. An empty list means the roster has -// not arrived yet (or failed), in which case saying "unknown" would be a guess. +// Callers pass the FULL command list, builtins included. An empty list means +// the roster has not arrived yet (or failed), in which case saying "unknown" +// would be a guess. export function isUnknownSlashCommand(text: string, knownNames: readonly string[]): boolean { if (knownNames.length === 0) return false; const match = /^\/([A-Za-z][A-Za-z0-9_-]*)/.exec(text.trim()); diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 8d67c16c3..f00fd6d71 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1188,7 +1188,7 @@ test("ISSUE #167 a command missing from omp's roster is reported, not run silent assert.equal(isUnknownSlashCommand("/Goal", known), true, "matching is case-insensitive both ways"); assert.equal(isUnknownSlashCommand("/todo", known), false); assert.equal(isUnknownSlashCommand("/compact now", known), false); - // Builtins are hidden from the palette but still executed by omp. + // Builtins are shown in the palette and executed by omp. assert.equal(isUnknownSlashCommand("/shake", [...known, "shake"]), false); // No roster yet (or a failed fetch) is not evidence that anything is unknown. assert.equal(isUnknownSlashCommand("/guided-goal", []), false); @@ -1201,6 +1201,100 @@ test("ISSUE #167 a command missing from omp's roster is reported, not run silent assert.equal(slashCommandName("/todo"), "todo"); }); +const GOAL = { + id: "g1", + objective: "ship the export", + status: "active", + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: 1000, + updatedAt: 1000, +}; +const goalState = (goal = GOAL) => ({ enabled: goal.status === "active", mode: "active", goal }); + +test("GOAL /goal sends the native goal RPC and never a prompt", async () => { + resetWorld(); + primeSession("goal-create", [userMsg("u0", "loaded question")]); + const w = await mountSession("goal-create"); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => ({ value: { success: true, data: { goal: GOAL, state: goalState() } } }), + }); + + const result = await act(async () => w.latest.handleBuiltinSlashCommand("/goal ship the export")); + assert.equal(result.handled, true); + const goalCalls = world.calls.filter((call) => call.body?.type === "goal"); + assert.deepEqual(goalCalls.map((call) => call.body), [{ type: "goal", op: "create", objective: "ship the export" }]); + assert.equal(world.calls.some((call) => call.body?.type === "prompt"), false, "no prompt is sent"); + assert.equal(w.latest.goalState?.goal?.id, "g1"); +}); + +test("GOAL get_state and goal_updated both feed the banner", async () => { + resetWorld(); + primeSession("goal-restore", [userMsg("u0", "loaded question")]); + world.agents.set("goal-restore", { running: false, state: { goal: goalState() } }); + const w = await mountSession("goal-restore"); + assert.equal(w.latest.goalState?.goal?.objective, "ship the export", "restored from get_state"); + + const paused = { ...GOAL, status: "paused", updatedAt: 2000 }; + await act(async () => w.latest.handleAgentEventRef.current({ type: "goal_updated", goal: paused, state: goalState(paused) })); + assert.equal(w.latest.goalState?.goal?.status, "paused"); + + await act(async () => w.latest.handleAgentEventRef.current({ type: "goal_updated", goal: null, state: null })); + assert.equal(w.latest.goalState, null, "a cleared goal hides the banner"); +}); + +test("GOAL a failed create reports omp's error and keeps the existing goal", async () => { + resetWorld(); + primeSession("goal-conflict", [userMsg("u0", "loaded question")]); + world.agents.set("goal-conflict", { running: false, state: { goal: goalState() } }); + const w = await mountSession("goal-conflict"); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => ({ status: 400, value: { error: "A goal is already active. Drop it before creating another." } }), + }); + + const result = await act(async () => w.latest.handleBuiltinSlashCommand("/goal another")); + assert.equal(result.handled, true); + assert.match(result.error, /already active/); + assert.equal(w.latest.goalState?.goal?.id, "g1"); +}); + +test("GOAL pause, resume and drop send the matching RPC and update the banner", async () => { + resetWorld(); + primeSession("goal-actions", [userMsg("u0", "loaded question")]); + world.agents.set("goal-actions", { running: false, state: { goal: goalState() } }); + const w = await mountSession("goal-actions"); + + const paused = { ...GOAL, status: "paused", updatedAt: 2000 }; + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => ({ value: { success: true, data: { goal: paused, state: goalState(paused) } } }), + }); + await act(async () => w.latest.handleGoalAction("pause")); + assert.equal(w.latest.goalState?.goal?.status, "paused"); + + const resumed = { ...GOAL, updatedAt: 3000 }; + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => ({ value: { success: true, data: { goal: resumed, state: goalState(resumed) } } }), + }); + await act(async () => w.latest.handleGoalAction("resume")); + assert.equal(w.latest.goalState?.goal?.status, "active"); + + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => ({ value: { success: true, data: { goal: null, state: null } } }), + }); + await act(async () => w.latest.handleGoalAction("drop")); + assert.equal(w.latest.goalState, null); + + assert.deepEqual( + world.calls.filter((call) => call.body?.type === "goal").map((call) => call.body.op), + ["pause", "resume", "drop"], + ); +}); + test("ISSUE #167 sending a TUI-only command warns once and still delivers the text", async () => { resetWorld(); primeSession("tui-only", [userMsg("u0", "loaded question")]); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 0b27a1ee3..ff5bfe410 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -38,8 +38,9 @@ import { getPreferredToolPreset, setPreferredToolPreset } from "@/lib/tool-prese import { toast } from "@/components/ui/toast"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import { validateOutgoingPrompt } from "@/lib/image-attachments"; -import { createActiveGoal, parseActiveGoal, type ActiveGoal, type ActivePlan } from "@/lib/web-mode-state"; -import type { HostToolDefinition, HostUriSchemeDefinition, RpcAskDialogAnswer, RpcAvailableSlashCommand, SessionStatsInfo, SlowModeScope, TodoPhase, UsageLimitState } from "@/lib/pi-types"; +import { type ActivePlan } from "@/lib/web-mode-state"; +import { isStaleGoalState, readGoalCommandResponse, readGoalUpdatedEvent } from "@/lib/goal-state"; +import type { GoalCommandResponse, GoalModeState, HostToolDefinition, HostUriSchemeDefinition, RpcAskDialogAnswer, RpcAvailableSlashCommand, SessionStatsInfo, SlowModeScope, TodoPhase, UsageLimitState } from "@/lib/pi-types"; import { isRecord } from "@/lib/type-guards"; import { subscribeSessionsChanged } from "@/lib/session-change-bus"; import { EVENT_STREAM_CLOSED, EVENT_STREAM_OPEN, addToOutbox, dropFromOutbox, newOutboxId, openEventStream, subscribeOutbox, type EventStream, type LocalOutboxEntry } from "@/lib/event-stream"; @@ -104,6 +105,7 @@ import { streamReducer, isUnknownSlashCommand, slashCommandName, + slashCommandRosterNames, toSlashCommandInfo, toThinkingModelMeta, } from "./useAgentSession-stream"; @@ -234,7 +236,6 @@ export interface UseAgentSessionOptions { onSystemPromptChange?: (prompt: string | null) => void; /** Registers an action that lazily starts the session and loads its system prompt. */ onSystemPromptLoaderChange?: (loader: (() => Promise) | null) => void; - onSessionStatsPanelOpen?: () => void; setToolPreset?: (preset: "none" | "default" | "full") => void; /** Opens a file in the web UI's file viewer (used by the open_file host tool). */ onOpenFile?: (filePath: string, name: string, source: WorkspaceFileSource) => void; @@ -283,7 +284,7 @@ function unrecordedHeldBash(messag export function useAgentSession(opts: UseAgentSessionOptions) { const { session, newSessionCwd, newSessionHostId, onAgentEnd, onSessionCreated, onSessionForked, onSessionMoved, - modelsRefreshKey, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsPanelOpen, + modelsRefreshKey, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onOpenFile, onOpenUrl, } = opts; const reducedMotion = usePrefersReducedMotion(); @@ -505,11 +506,24 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (seq <= skillDiagnosticsAppliedSeqRef.current) return; publishSkillDiagnostics(seq, parseSkillDiagnosticsSnapshot(value) ?? null); }, [publishSkillDiagnostics]); + // Goal state has two live sources (goal_updated frames and get_state + // snapshots) plus command responses. A snapshot takes a sequence when it is + // requested and applies only if no newer frame/response arrived; an older + // updatedAt never overwrites a newer goal. + const goalSeqRef = useRef(0); + const applyGoalSnapshot = useCallback((seq: number, value: GoalModeState | null) => { + if (seq !== goalSeqRef.current) return; + setGoalState((prev) => (isStaleGoalState(prev, value) ? prev : value)); + }, []); + const publishGoalState = useCallback((value: GoalModeState | null) => { + goalSeqRef.current += 1; + setGoalState((prev) => (isStaleGoalState(prev, value) ? prev : value)); + }, []); const [subagents, setSubagents] = useState([]); const [subagentEvents, setSubagentEvents] = useState>({}); const [subagentTranscriptVersions, setSubagentTranscriptVersions] = useState>({}); const [todoPhases, setTodoPhases] = useState([]); - const [activeGoal, setActiveGoal] = useState(null); + const [goalState, setGoalState] = useState(null); const [activePlan, setActivePlan] = useState(null); const [advisorActiveAt, setAdvisorActiveAt] = useState(0); // Advisor is a per-chat toggle (composer Sparkles + /advisor command), not a @@ -804,16 +818,17 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } satisfies SessionStatsInfo; }, [messages, sessionStatsOverride, contextUsage, data?.filePath, session?.id, session?.name]); - // Goal mode is web-hosted because omp's native /goal is TUI-only. Keep it - // scoped to its session so switching conversations never leaks objectives. + // Goal state is omp-owned and scoped to its session. Clear it immediately on + // a switch; loadSession/reconcile fill it from the new session's get_state, + // and the sequence prevents the previous session's late snapshot from + // reappearing. useEffect(() => { - const sid = session?.id; setActivePlan(null); - if (!sid) { - setActiveGoal(null); - return; - } - setActiveGoal(parseActiveGoal(sessionStorage.getItem(`omp-web:goal:${sid}`))); + // Promoting the empty new-chat runtime to its real id is the same + // conversation, not a switch: keep the goal that was just created. + if (session?.id && session.id === sessionIdRef.current) return; + goalSeqRef.current += 1; + setGoalState(null); }, [session?.id]); // A plan request is in progress only for its current agent turn. @@ -1034,6 +1049,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { token: beginAuthoritativeModelSync(), queueRevision: ++queueSeqRef.current, skillDiagnosticsRevision: ++skillDiagnosticsSeqRef.current, + goalSnapshotSeq: goalSeqRef.current, response: fetch(`/api/sessions/${encodeURIComponent(sid)}/state`).then(async (stateRes) => { const agentState = await stateRes.json().catch(() => ({})) as { running: boolean; state?: AgentStateResponse; exited?: ExitedRpcSession; outbox?: OutboxEntry[]; outboxScope?: string; outboxSettledIds?: string[] }; if (hookAliveRef.current && sessionIdRef.current === sid && contextRequestSeqRef.current === requestSeq @@ -1094,7 +1110,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } try { - const { token, queueRevision, skillDiagnosticsRevision } = stateRequest; + const { token, queueRevision, skillDiagnosticsRevision, goalSnapshotSeq } = stateRequest; const reply = await stateRequest.response; if (!reply) { if (showLoading) setLoading(false); @@ -1136,6 +1152,7 @@ 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.goal !== undefined) applyGoalSnapshot(goalSnapshotSeq, liveState.goal ?? null); applyQueueStateSnapshot(queueRevision, liveState.queuedMessages); } else if (!agentState.running) { setSlowModeSupported(undefined); @@ -1164,7 +1181,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; } - }, [catchUp, refreshSubagentHistory, applyAuthoritativeModel, beginAuthoritativeModelSync, applyQueueStateSnapshot, applySkillDiagnosticsSnapshot]); + }, [catchUp, refreshSubagentHistory, applyAuthoritativeModel, beginAuthoritativeModelSync, applyGoalSnapshot, applyQueueStateSnapshot, applySkillDiagnosticsSnapshot]); const loadContext = useCallback(async (sid: string, leafId: string | null, includePreCompaction = false): Promise => { const seq = ++contextRequestSeqRef.current; @@ -1319,14 +1336,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { try { const data = await sendAgentCommand(sid, { type: "get_commands" }); const available = Array.isArray(data?.commands) ? data.commands : []; - // Keep the builtins too: they are hidden from the palette but omp still - // runs them when typed, so they must not be reported as unknown (#167). + // Keep every source, builtins included: omp runs them through the prompt + // path and they must not be reported as unknown (#167). // A reply carrying no list is not evidence that nothing is known, so it // must not erase a roster an earlier reply did supply. - if (available.length > 0) knownSlashCommandNamesRef.current = available.map((command) => command.name); - const commands = available - .map(toSlashCommandInfo) - .filter((c): c is SlashCommandInfo => c !== null); + if (available.length > 0) knownSlashCommandNamesRef.current = slashCommandRosterNames(available); + const commands = available.map(toSlashCommandInfo); setSlashCommands(commands); return commands; } catch (e) { @@ -1357,6 +1372,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const reconnectActionsRef = useRef<((sid: string) => void) | null>(null); const refreshAgentSnapshots = useCallback(async (sid: string) => { + const goalSnapshotSeq = goalSeqRef.current; const queueRevision = ++queueSeqRef.current; const skillDiagnosticsRevision = ++skillDiagnosticsSeqRef.current; try { @@ -1365,10 +1381,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const data = await res.json() as { state?: AgentStateResponse }; applyQueueStateSnapshot(queueRevision, data.state?.queuedMessages); applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, data.state?.skillDiagnostics); + if (data.state?.goal !== undefined) applyGoalSnapshot(goalSnapshotSeq, data.state.goal ?? null); } catch { // The next live update or state snapshot heals these views. } - }, [applyQueueStateSnapshot, applySkillDiagnosticsSnapshot]); + }, [applyGoalSnapshot, applyQueueStateSnapshot, applySkillDiagnosticsSnapshot]); // A held-message stream ("connected" mode) was opened without asking omp whether a run is going; the running // channel treats an open stream as carrying the run, so the chat asks once that stream attaches (below). @@ -2088,6 +2105,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const token = guard.tryAcquire(); if (token === null) return; try { + const goalSnapshotSeq = goalSeqRef.current; const queueRevision = ++queueSeqRef.current; const skillDiagnosticsRevision = ++skillDiagnosticsSeqRef.current; const res = await fetch(`/api/agent/${encodeURIComponent(sid)}`); @@ -2100,6 +2118,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { || responseRunVersionRef.current !== responseVersion) return; const state = data.state; applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, state?.skillDiagnostics); + if (state?.goal !== undefined) applyGoalSnapshot(goalSnapshotSeq, state.goal ?? null); if (!promptDispatchPendingRef.current && state?.responseObserved) runHadContentRef.current = true; // Manual compaction emits no completion event; native state releases // its controls independently of live transcript hydration. No state @@ -2642,8 +2661,31 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } case "available_commands_update": { const commands = (event.commands as RpcAvailableSlashCommand[] | undefined) ?? []; - knownSlashCommandNamesRef.current = commands.map((command) => command.name); - setSlashCommands(commands.map(toSlashCommandInfo).filter((c): c is SlashCommandInfo => c !== null)); + knownSlashCommandNamesRef.current = slashCommandRosterNames(commands); + setSlashCommands(commands.map(toSlashCommandInfo)); + break; + } + case "goal_updated": { + publishGoalState(readGoalUpdatedEvent(event)); + break; + } + case "manual_compaction_start": { + // `/compact` now runs through omp's own builtin; the RPC `compact` + // response only covers the web button. Keep both paths visible. + isCompactingRef.current = true; + setIsCompacting(true); + setCompactError(null); + setCompactResult(null); + break; + } + case "manual_compaction_end": { + isCompactingRef.current = false; + setIsCompacting(false); + const compacted = readCompactResult(event.result, typeof event.mode === "string" ? event.mode : "manual"); + if (compacted) setCompactResult(compacted); + else if (typeof event.errorMessage === "string" && event.errorMessage) setCompactError(event.errorMessage); + const sid = sessionIdRef.current; + if (sid) void loadSession(sid, true); break; } case "message_start": @@ -3004,7 +3046,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { handleExtensionUiRequest(event as unknown as IncomingExtensionUiRequest); break; } - }, [addNotice, addUnconfirmedRunErrorNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, refreshSubagentRoster, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync, setCompacting, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot]); + }, [addNotice, addUnconfirmedRunErrorNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, refreshSubagentRoster, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, publishGoalState, beginAuthoritativeModelSync, setCompacting, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot]); handleAgentEventRef.current = handleAgentEvent; syncActionsRef.current = { metadata: (context, version, hasLive = liveModelMeta !== null || currentModelOverride !== null) => { @@ -4077,37 +4119,18 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (!result.handled) return result; if (result.error) { addNotice({ type: "error", message: result.error }); - } else if (result.action !== "openSessionStats") { + } else { addNotice({ type: "success", message: result.message ?? translate("agentSession.commandCompleted") }); } return result; }; - let ownsCompaction = false; try { - // Commands that talk to the runtime create it here. /btw and the web - // prompt commands create it inside askBtw/handleSend, which attach their own stream. + // Commands that talk to the runtime create it here. /btw and + // the web prompt commands create it inside askBtw/handleSend, which + // attach their own stream. const ensureRuntime = async () => sessionIdRef.current ?? await ensureNewSession(); switch (commandName) { - case "compact": { - const sid = await ensureRuntime(); - if (!sid || isCompactingRef.current || isCompacting) return complete({ handled: true, error: translate("agentSession.noSessionToCompact") }); - ownsCompaction = true; - beginLocalCompaction(); - setCompactError(null); - setCompactResult(null); - const result = await sendAgentCommand(sid, { - type: "compact", - ...(args ? { customInstructions: args } : {}), - }); - setCompactResult(readCompactResult(result, "manual")); - await loadSession(sid, true); - // loadSession resolves to null unless state was requested, so promote - // unconditionally — promoteNewSession no-ops for existing sessions and - // is idempotent via newSessionPromotedRef. - promoteNewSession(); - return complete({ handled: true, message: translate("agentSession.compactedContext") }); - } case "reload": { const sid = await ensureRuntime(); @@ -4131,17 +4154,6 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return complete({ handled: true, message: translate("agentSession.sessionRenamed", { name: args }) }); } - case "session": { - const sid = await ensureRuntime(); - if (!sid) return complete({ handled: true, error: translate("agentSession.noActiveSession") }); - const stats = await sendAgentCommand(sid, { type: "get_session_stats" }); - if (stats) { - setSessionStatsOverride(stats); - } - onSessionStatsPanelOpen?.(); - return complete({ handled: true, action: "openSessionStats" }); - } - case "btw": { // `/btw` alone opens the history; with a question it asks one. if (!args) { @@ -4163,17 +4175,31 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return complete({ handled: true, message: translate("agentSession.copiedLastMessage") }); } + case "goal": { + const sid = await ensureRuntime(); + if (!sid) return complete({ handled: true, error: translate("agentSession.noActiveSession") }); + const objective = args.trim(); + if (!objective) return complete({ handled: true, error: translate("agentSession.goalUsage") }); + const result = await sendAgentCommand(sid, { + type: "goal", + op: "create", + objective, + }); + const parsed = readGoalCommandResponse(result); + if (parsed) publishGoalState(parsed.state); + // A goal created on the empty new-chat screen must adopt the real + // session so a reload opens it instead of a fresh composer. + promoteNewSession(); + return complete({ handled: true, message: translate("agentSession.goalStarted", { objective }) }); + } + default: { - // Web-native prompt commands (/goal, /plan, ...). omp's same-named - // builtins are TUI-only and never execute over RPC, so the palette - // shows these instead (CLIENT_BUILTIN_COMMAND_NAMES drops omp's - // copies). handleSend runs the full prompt pipeline — optimistic - // bubble, running state, settlement — with the expanded text. - // /advisor is gated on the per-chat composer toggle: refuse with a - // pointer to that toggle while the advisor is disabled. - if (commandName === "advisor" && !advisorEnabled) { - return complete({ handled: true, error: translate("agentSession.advisorDisabled") }); - } + // Anything omp's RPC catalog owns (builtin, extension, custom, MCP + // prompt, file, skill) is executed by omp itself: send the original + // command line through the prompt pipeline. Never expand a name omp + // already reports — an extension command must win over a web + // convenience of the same name. + if (knownSlashCommandNamesRef.current.includes(commandName)) return { handled: false }; const expansion = expandWebSlashCommand(text); if (expansion.kind === "not-web") return { handled: false }; if (expansion.kind === "usage-error") { @@ -4192,23 +4218,29 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (commandName === "plan") setActivePlan(null); return { handled: true, retainInput: true }; } - if (commandName === "goal") { - const goal = createActiveGoal(args); - setActiveGoal(goal); - const activeSessionId = sessionIdRef.current; - if (activeSessionId) sessionStorage.setItem(`omp-web:goal:${activeSessionId}`, JSON.stringify(goal)); - } return { handled: true }; } } } catch (e) { return complete({ handled: true, error: e instanceof Error ? e.message : String(e) }); - } finally { - if (ownsCompaction) { - endLocalCompaction(); - } } - }, [addNotice, advisorEnabled, askBtw, beginLocalCompaction, endLocalCompaction, ensureNewSession, handleSend, isCompacting, loadModels, loadSession, loadSlashCommands, openBtwHistory, promoteNewSession, onSessionStatsPanelOpen]); + }, [addNotice, askBtw, ensureNewSession, handleSend, loadModels, loadSession, loadSlashCommands, openBtwHistory, promoteNewSession, publishGoalState]); + + /** Pause/resume/drop the omp-owned goal. The banner disables its buttons while this runs. */ + const handleGoalAction = useCallback(async (op: "pause" | "resume" | "drop") => { + const sid = sessionIdRef.current; + if (!sid) { + addNotice({ type: "error", message: translate("agentSession.noActiveSession") }); + return; + } + try { + const result = await sendAgentCommand(sid, { type: "goal", op }); + const parsed = readGoalCommandResponse(result); + if (parsed) publishGoalState(parsed.state); + } catch (e) { + addNotice({ type: "error", message: e instanceof Error ? e.message : String(e) }); + } + }, [addNotice, publishGoalState]); // A steer or follow-up is held in the outbox like a prompt: its held bubble becomes omp's queue chip (queue_update) // or, delivered at once, the user message omp echoes. A slash command keeps its text; the server sends it as a @@ -4708,7 +4740,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { notices: noticeState.visible, dismissNotice, extensionDialog, extensionCustomUi, extensionStatuses, extensionWidgets, respondToExtensionUi, sendExtensionCustomInput, advisorActive: advisorActiveAt > 0, advisorEnabled, handleAdvisorChange, subagents, subagentEvents, subagentTranscriptVersions, activeSubagentCount, currentTodoPhase, todoPhases, - activeGoal, activePlan, + goalState, activePlan, isNew, // Refs sessionIdRef, messagesEndRef, scrollContainerRef, @@ -4716,7 +4748,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // Actions handleSend, handleAbort, handleFork, handleEdit, handleModelChange, handleFastModeChange, handleSlowModeChange, handleAutoRetryChange, handleInterruptModeChange, handleAutoCompactionChange, handleSteeringModeChange, handleFollowUpModeChange, handleCycleModel, handleCycleThinkingLevel, handleAbortRetry, handleInterruptAndReply, setSkillStartupDiagnostics, retrySession: () => { const sid = sessionIdRef.current; if (sid) void loadSession(sid, true, true); }, - handleCompact, handleHandoff, handleSteer, handleFollowUp, handleAbortCompaction, + handleCompact, handleHandoff, handleSteer, handleFollowUp, handleAbortCompaction, handleGoalAction, heldMessages, deleteHeldMessage, handleBuiltinSlashCommand, togglePreCompactionHistory, handleToolPresetChange, handleThinkingLevelChange, loadSlashCommands, removeQueuedMessage, promoteQueuedToSteer, setActiveLeafId, setData, setMessages, diff --git a/lib/goal-state.test.mjs b/lib/goal-state.test.mjs new file mode 100644 index 000000000..e604be65b --- /dev/null +++ b/lib/goal-state.test.mjs @@ -0,0 +1,81 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); +const { + formatGoalDuration, + goalElapsedSeconds, + isGoalControllable, + isStaleGoalState, + readGoalCommandResponse, + readGoalModeState, + readGoalUpdatedEvent, +} = await jiti.import("./goal-state.ts"); + +const GOAL = { + id: "g1", + objective: "Ship the export", + status: "active", + tokensUsed: 1200, + timeUsedSeconds: 90, + createdAt: 1000, + updatedAt: 2000, +}; + +test("reads omp's goal shapes defensively", () => { + assert.deepEqual(readGoalModeState({ enabled: true, mode: "active", goal: GOAL }), { + enabled: true, + mode: "active", + goal: GOAL, + }); + assert.deepEqual(readGoalModeState({ enabled: true, mode: "active", goal: null }), { + enabled: true, + mode: "active", + goal: null, + }); + // A present-but-malformed goal must not be mistaken for "no goal". + assert.equal(readGoalModeState({ enabled: true, mode: "active", goal: { objective: "" } }), null); + assert.equal(readGoalModeState("nope"), null); +}); + +test("goal_updated falls back to the bare goal and tolerates a dropped state", () => { + assert.equal(readGoalUpdatedEvent({ goal: GOAL })?.goal?.objective, "Ship the export"); + assert.deepEqual(readGoalUpdatedEvent({ goal: null }), null); + const dropped = readGoalUpdatedEvent({ + goal: { ...GOAL, status: "dropped", updatedAt: 3000 }, + state: { enabled: false, mode: "active", goal: { ...GOAL, status: "dropped", updatedAt: 3000 } }, + }); + assert.equal(dropped?.goal?.status, "dropped"); +}); + +test("the command response accepts drop's null state and synthesizes a bare goal", () => { + assert.deepEqual(readGoalCommandResponse({ goal: null, state: null }), { goal: null, state: null }); + const bare = readGoalCommandResponse({ goal: GOAL, state: null }); + assert.equal(bare?.state?.goal?.id, "g1"); + assert.equal(bare?.state?.enabled, true); +}); + +test("elapsed time extrapolates only while active and formats compactly", () => { + const active = { enabled: true, mode: "active", goal: GOAL }; + assert.equal(goalElapsedSeconds(active, 2500), 90.5); + assert.equal(goalElapsedSeconds({ ...active, goal: { ...GOAL, status: "paused" } }, 2500), 90); + assert.equal(formatGoalDuration(-1), "0s"); + assert.equal(formatGoalDuration(59), "59s"); + assert.equal(formatGoalDuration(60), "1m"); + assert.equal(formatGoalDuration(3660), "1h 1m"); +}); + +test("only active and paused goals are controllable; older snapshots lose", () => { + assert.equal(isGoalControllable({ enabled: true, mode: "active", goal: GOAL }), true); + assert.equal(isGoalControllable({ enabled: false, mode: "active", goal: { ...GOAL, status: "paused" } }), true); + assert.equal(isGoalControllable({ enabled: false, mode: "active", goal: { ...GOAL, status: "completed" } }), false); + assert.equal(isStaleGoalState( + { enabled: true, mode: "active", goal: GOAL }, + { enabled: true, mode: "active", goal: { ...GOAL, updatedAt: 1000 } }, + ), true); + assert.equal(isStaleGoalState( + { enabled: true, mode: "active", goal: GOAL }, + { enabled: true, mode: "active", goal: { ...GOAL, updatedAt: 3000 } }, + ), false); +}); diff --git a/lib/goal-state.ts b/lib/goal-state.ts new file mode 100644 index 000000000..9b5b3aad7 --- /dev/null +++ b/lib/goal-state.ts @@ -0,0 +1,99 @@ +/** + * Defensive readers for omp's goal payloads. + * + * `get_state.goal`, the `goal` command response and `goal_updated` events use + * three slightly different shapes (the command may answer `state: null` while + * the event still carries a `dropped` goal). Never hand an untrusted payload + * straight to the banner. + */ + +import type { Goal, GoalCommandResponse, GoalModeState, GoalStatus } from "./pi-types"; +import { asNumber, asString, isRecord } from "./type-guards"; + +function readGoal(value: unknown): Goal | null { + if (!isRecord(value)) return null; + const id = asString(value.id); + const objective = asString(value.objective)?.trim(); + if (!id || !objective) return null; + return { + id, + objective, + status: (asString(value.status) ?? "unknown") as GoalStatus, + tokensUsed: Math.max(0, asNumber(value.tokensUsed) ?? 0), + timeUsedSeconds: Math.max(0, asNumber(value.timeUsedSeconds) ?? 0), + createdAt: Math.max(0, asNumber(value.createdAt) ?? 0), + updatedAt: Math.max(0, asNumber(value.updatedAt) ?? 0), + }; +} + +/** A state without its envelope (older/partial payloads) is synthesized from the goal itself. */ +function stateFromGoal(goal: Goal | null): GoalModeState | null { + if (!goal) return null; + return { enabled: goal.status === "active", mode: goal.status, goal }; +} + +export function readGoalModeState(value: unknown): GoalModeState | null { + if (!isRecord(value)) return null; + const goal = readGoal(value.goal); + // A present-but-malformed goal is not "no goal": refuse the snapshot. + if (value.goal != null && !goal) return null; + const enabled = value.enabled; + const mode = asString(value.mode); + if (typeof enabled !== "boolean" || mode === undefined) return stateFromGoal(goal); + return { enabled, mode, goal }; +} + +/** `goal_updated` event: prefer the full state, fall back to the bare goal. */ +export function readGoalUpdatedEvent(value: unknown): GoalModeState | null { + if (!isRecord(value)) return null; + const state = readGoalModeState(value.state); + if (state) return state; + return stateFromGoal(readGoal(value.goal)); +} + +export function readGoalCommandResponse(value: unknown): GoalCommandResponse | null { + if (!isRecord(value)) return null; + if (!("goal" in value) && !("state" in value)) return null; + const state = readGoalModeState(value.state); + const goal = readGoal(value.goal); + if (value.goal != null && !goal) return null; + if (state || goal) return { goal: goal ?? state?.goal ?? null, state: state ?? stateFromGoal(goal) }; + // Both null is a valid "no goal" answer (drop/get). + return { goal: null, state: null }; +} + +/** True while the goal exists; completed/dropped are terminal and drop off when omp sends null. */ +export function hasGoal(state: GoalModeState | null | undefined): boolean { + return Boolean(state?.goal); +} + +export function isGoalControllable(state: GoalModeState | null | undefined): boolean { + return state?.goal?.status === "active" || state?.goal?.status === "paused"; +} + +/** omp reports `timeUsedSeconds`; while active, extrapolate from `updatedAt` for a live display. */ +export function goalElapsedSeconds(state: GoalModeState | null | undefined, now = Date.now()): number { + const goal = state?.goal; + if (!goal) return 0; + if (goal.status !== "active" || goal.updatedAt <= 0) return goal.timeUsedSeconds; + return goal.timeUsedSeconds + Math.max(0, (now - goal.updatedAt) / 1000); +} + +export function formatGoalDuration(seconds: number): string { + const total = Math.max(0, Math.floor(seconds)); + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + const secs = total % 60; + if (hours > 0) return `${hours}h ${minutes}m`; + if (minutes > 0) return `${minutes}m`; + return `${secs}s`; +} + +/** Keep an already-displayed goal when a slower response carries an older snapshot. */ +export function isStaleGoalState( + current: GoalModeState | null, + incoming: GoalModeState | null, +): boolean { + if (!current?.goal || !incoming?.goal) return false; + return incoming.goal.updatedAt < current.goal.updatedAt; +} diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index ddfdb2abf..a4142c7fd 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -35,11 +35,9 @@ "login.connectionFailed": "Could not sign in. Please check your connection and try again.", "login.unlocking": "Unlocking…", "login.unlock": "Unlock workspace", - "agentSession.advisorDisabled": "Advisor is disabled — enable it with the sparkles toggle in the composer.", "agentSession.commandCompleted": "Command completed", "agentSession.commandRequiresArgs": "Usage: {command} {usage}", "agentSession.commandFailed": "Command failed", - "agentSession.compactedContext": "Compacted context", "agentSession.copiedLastMessage": "Copied last assistant message", "agentSession.eventStreamFailed": "Failed to connect to the agent event stream. Please try again.", "agentSession.eventStreamTimeout": "Timed out connecting to the agent event stream. Please try again.", @@ -47,7 +45,8 @@ "agentSession.noActiveSession": "No active session", "agentSession.noMessageToCopy": "No assistant message to copy", "agentSession.noMessages": "(no messages)", - "agentSession.noSessionToCompact": "No active session to compact", + "agentSession.goalStarted": "Goal started: {objective}", + "agentSession.goalUsage": "Usage: /goal ", "agentSession.noSessionToName": "No active session to name", "agentSession.noSessionToReload": "No active session to reload", "agentSession.openInBrowser": "Open in your browser: {url}", @@ -456,18 +455,22 @@ "chatInput.toolPresetNone": "No tools", "chatInput.toolPresetDefault": "Read, bash, edit, write", "chatInput.toolPresetFull": "All tools, including subagents", - "chatInput.cmdCompact": "Compress context, optionally with instructions", "chatInput.commandUsageTitle": "Command usage", "chatInput.cmdGoal": "Set the goal for this session", "chatInput.cmdGoalArg": "[goal]", "chatInput.goalActive": "Goal active", + "chatInput.goalPaused": "Goal paused", + "chatInput.goalCompleted": "Goal completed", + "chatInput.goalDropped": "Goal dropped", + "chatInput.goalTokens": "{count} tokens", + "chatInput.pauseGoal": "Pause", + "chatInput.resumeGoal": "Resume", + "chatInput.dropGoal": "Drop", "chatInput.expandGoal": "Expand active goal", "chatInput.collapseGoal": "Collapse active goal", "chatInput.cmdPlan": "Create a step-by-step plan", "chatInput.cmdPlanArg": "[task]", "chatInput.planningInProgress": "Planning in progress", - "chatInput.cmdReview": "Review project state and changes", - "chatInput.cmdReviewArg": "[scope]", "chatInput.cmdFix": "Fix a reported issue", "chatInput.cmdFixArg": "[issue]", "chatInput.cmdTest": "Write and run tests", @@ -482,12 +485,9 @@ "chatInput.cmdBtw": "Ask a side question without adding it to the conversation", "chatInput.cmdBtwArg": "[question]", "chatInput.cmdName": "Set the session display name", - "chatInput.cmdAdvisor": "Get an independent advisory review of the current work", - "chatInput.cmdAdvisorArg": "[topic]", "chatInput.cmdLoop": "Repeat a task until done, up to N attempts", "chatInput.cmdLoopArg": "[count] [task]", "chatInput.cmdReload": "Reload extensions, skills, prompts, and tools", - "chatInput.cmdSession": "Show session message, token, and cost stats", "chatInput.collapseControls": "Collapse controls", "chatInput.commandCount.one": "1 command", "chatInput.commandCount.other": "{count} commands", @@ -506,7 +506,7 @@ "chatInput.filesHeader": "Files · {countLabel}", "chatInput.followUp": "Follow-up", "chatInput.followUpTitle": "Queue this message after the agent finishes", - "chatInput.groupBuiltin": "Built-in", + "chatInput.groupBuiltin": "Web commands", "chatInput.groupExtensions": "Extensions", "chatInput.groupOmpBuiltin": "omp commands", "chatInput.groupPrompts": "Prompts", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 7411bc7cd..38fb5184e 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -35,11 +35,9 @@ "login.connectionFailed": "ログインできませんでした。接続を確認して再試行してください。", "login.unlocking": "ロック解除中…", "login.unlock": "ワークスペースをアンロック", - "agentSession.advisorDisabled": "アドバイザーが無効です — コンポーザーのスパークルアイコンで有効にしてください。", "agentSession.commandCompleted": "コマンドが完了しました", "agentSession.commandRequiresArgs": "使用法: {command} {usage}", "agentSession.commandFailed": "コマンドが失敗しました", - "agentSession.compactedContext": "コンテキストを圧縮しました", "agentSession.copiedLastMessage": "最後のアシスタントメッセージをコピーしました", "agentSession.eventStreamFailed": "エージェントのイベントストリームに接続できませんでした。もう一度お試しください。", "agentSession.eventStreamTimeout": "エージェントのイベントストリームへの接続がタイムアウトしました。もう一度お試しください。", @@ -47,7 +45,8 @@ "agentSession.noActiveSession": "アクティブなセッションがありません", "agentSession.noMessageToCopy": "コピーできるアシスタントメッセージがありません", "agentSession.noMessages": "(メッセージなし)", - "agentSession.noSessionToCompact": "圧縮できるアクティブなセッションがありません", + "agentSession.goalStarted": "目標を開始しました: {objective}", + "agentSession.goalUsage": "使用法: /goal <目標>", "agentSession.noSessionToName": "名前を付けられるアクティブなセッションがありません", "agentSession.noSessionToReload": "再読み込みできるアクティブなセッションがありません", "agentSession.openInBrowser": "ブラウザで開いてください: {url}", @@ -439,18 +438,22 @@ "chatInput.toolPresetNone": "ツールなし", "chatInput.toolPresetDefault": "read、bash、edit、write", "chatInput.toolPresetFull": "すべてのツール(サブエージェントを含む)", - "chatInput.cmdCompact": "コンテキストを圧縮します(任意で指示を追加できます)", "chatInput.commandUsageTitle": "コマンドの使い方", "chatInput.cmdGoal": "セッションの目標を設定する", "chatInput.cmdGoalArg": "[目標]", "chatInput.goalActive": "目標が有効", + "chatInput.goalPaused": "目標は一時停止中", + "chatInput.goalCompleted": "目標を達成しました", + "chatInput.goalDropped": "目標を破棄しました", + "chatInput.goalTokens": "{count} トークン", + "chatInput.pauseGoal": "一時停止", + "chatInput.resumeGoal": "再開", + "chatInput.dropGoal": "破棄", "chatInput.expandGoal": "有効な目標を展開", "chatInput.collapseGoal": "有効な目標を折りたたむ", "chatInput.cmdPlan": "ステップごとの計画を作成する", "chatInput.cmdPlanArg": "[タスク]", "chatInput.planningInProgress": "計画を作成中", - "chatInput.cmdReview": "プロジェクトの状態と変更をレビューする", - "chatInput.cmdReviewArg": "[範囲]", "chatInput.cmdFix": "報告された問題を修正する", "chatInput.cmdFixArg": "[問題]", "chatInput.cmdTest": "テストを書いて実行する", @@ -465,12 +468,9 @@ "chatInput.cmdBtw": "会話に残さずにサイド質問をします", "chatInput.cmdBtwArg": "[質問]", "chatInput.cmdName": "セッションの表示名を設定します", - "chatInput.cmdAdvisor": "現在の作業について独立したアドバイザリーレビューを受ける", - "chatInput.cmdAdvisorArg": "[トピック]", "chatInput.cmdLoop": "タスクが完了するまで最大N回繰り返す", "chatInput.cmdLoopArg": "[回数] [タスク]", "chatInput.cmdReload": "拡張機能、スキル、プロンプト、ツールを再読み込みします", - "chatInput.cmdSession": "セッションのメッセージ・トークン・コストの統計を表示します", "chatInput.collapseControls": "コントロールを折りたたむ", "chatInput.commandCount.one": "{count} 件のコマンド", "chatInput.commandCount.other": "{count} 件のコマンド", @@ -489,7 +489,7 @@ "chatInput.filesHeader": "ファイル · {countLabel}", "chatInput.followUp": "フォローアップ", "chatInput.followUpTitle": "エージェントの完了後にこのメッセージを送信します", - "chatInput.groupBuiltin": "組み込み", + "chatInput.groupBuiltin": "Web コマンド", "chatInput.groupExtensions": "拡張機能", "chatInput.groupOmpBuiltin": "omp コマンド", "chatInput.groupPrompts": "プロンプト", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 7599b575c..137f8478b 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -35,11 +35,9 @@ "login.connectionFailed": "无法登录,请检查连接后重试。", "login.unlocking": "正在解锁…", "login.unlock": "解锁工作区", - "agentSession.advisorDisabled": "顾问已禁用 — 请通过输入框中的星形图标启用。", "agentSession.commandCompleted": "命令已完成", "agentSession.commandRequiresArgs": "用法:{command} {usage}", "agentSession.commandFailed": "命令失败", - "agentSession.compactedContext": "已压缩上下文", "agentSession.copiedLastMessage": "已复制最后一条助手消息", "agentSession.eventStreamFailed": "无法连接到智能体事件流,请重试。", "agentSession.eventStreamTimeout": "连接智能体事件流超时,请重试。", @@ -47,7 +45,8 @@ "agentSession.noActiveSession": "没有活动会话", "agentSession.noMessageToCopy": "没有可复制的助手消息", "agentSession.noMessages": "(暂无消息)", - "agentSession.noSessionToCompact": "没有可压缩上下文的活动会话", + "agentSession.goalStarted": "目标已开始:{objective}", + "agentSession.goalUsage": "用法:/goal <目标>", "agentSession.noSessionToName": "没有可命名的活动会话", "agentSession.noSessionToReload": "没有可重新加载的活动会话", "agentSession.openInBrowser": "请在浏览器中打开:{url}", @@ -439,18 +438,22 @@ "chatInput.toolPresetNone": "无工具", "chatInput.toolPresetDefault": "read、bash、edit、write", "chatInput.toolPresetFull": "全部工具(含子代理)", - "chatInput.cmdCompact": "压缩上下文,可附加说明", "chatInput.commandUsageTitle": "命令用法", "chatInput.cmdGoal": "设定本次会话的目标", "chatInput.cmdGoalArg": "[目标]", "chatInput.goalActive": "目标进行中", + "chatInput.goalPaused": "目标已暂停", + "chatInput.goalCompleted": "目标已完成", + "chatInput.goalDropped": "目标已放弃", + "chatInput.goalTokens": "{count} token", + "chatInput.pauseGoal": "暂停", + "chatInput.resumeGoal": "继续", + "chatInput.dropGoal": "放弃", "chatInput.expandGoal": "展开当前目标", "chatInput.collapseGoal": "收起当前目标", "chatInput.cmdPlan": "制定分步计划", "chatInput.cmdPlanArg": "[任务]", "chatInput.planningInProgress": "正在制定计划", - "chatInput.cmdReview": "审查项目状态与改动", - "chatInput.cmdReviewArg": "[范围]", "chatInput.cmdFix": "修复报告的问题", "chatInput.cmdFixArg": "[问题]", "chatInput.cmdTest": "编写并运行测试", @@ -465,12 +468,9 @@ "chatInput.cmdBtw": "提出一个不写入对话的旁支问题", "chatInput.cmdBtwArg": "[问题]", "chatInput.cmdName": "设置会话显示名称", - "chatInput.cmdAdvisor": "对当前工作进行独立的顾问评审", - "chatInput.cmdAdvisorArg": "[主题]", "chatInput.cmdLoop": "重复执行任务直到完成,最多 N 次", "chatInput.cmdLoopArg": "[次数] [任务]", "chatInput.cmdReload": "重新加载扩展、技能、提示词和工具", - "chatInput.cmdSession": "显示会话的消息、token 和费用统计", "chatInput.collapseControls": "收起控件", "chatInput.commandCount.one": "{count} 个命令", "chatInput.commandCount.other": "{count} 个命令", @@ -489,7 +489,7 @@ "chatInput.filesHeader": "文件 · {countLabel}", "chatInput.followUp": "追加消息", "chatInput.followUpTitle": "将此消息排队,待智能体完成后发送", - "chatInput.groupBuiltin": "内置", + "chatInput.groupBuiltin": "Web 命令", "chatInput.groupExtensions": "扩展", "chatInput.groupOmpBuiltin": "omp 命令", "chatInput.groupPrompts": "提示词", diff --git a/lib/image-attachments.test.mjs b/lib/image-attachments.test.mjs index 5d6aa6ebe..ffe91a338 100644 --- a/lib/image-attachments.test.mjs +++ b/lib/image-attachments.test.mjs @@ -80,7 +80,7 @@ test("rejects a prompt whose JSON body would exceed the agent request cap", asyn test("validates the expanded web slash prompt rather than its shorter command text", async () => { const { MAX_AGENT_COMMAND_REQUEST_BYTES, validateOutgoingPrompt } = await loadSubject(); const { expandWebSlashCommand } = await import("./web-slash-commands.ts"); - const commandPrefix = "/goal "; + const commandPrefix = "/plan "; const raw = `${commandPrefix}${"x".repeat(MAX_AGENT_COMMAND_REQUEST_BYTES - 256 - 2 - commandPrefix.length - 50)}`; const expansion = expandWebSlashCommand(raw); diff --git a/lib/pi-types.ts b/lib/pi-types.ts index c0b5e67a5..d9843104a 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -63,6 +63,34 @@ export interface QueuedMessages { followUp: string[]; } +/** + * omp goal mode (RPC `goal` command and `goal_updated` event). + * Unknown statuses are preserved: a newer omp may add lifecycle states. + */ +export type GoalStatus = "active" | "paused" | "completed" | "dropped" | (string & {}); + +export interface Goal { + id: string; + objective: string; + status: GoalStatus; + tokensUsed: number; + timeUsedSeconds: number; + createdAt: number; + updatedAt: number; +} + +export interface GoalModeState { + enabled: boolean; + mode: string; + goal: Goal | null; +} + +/** `goal` command response; drop may answer `state: null` while the event still carries `dropped`. */ +export interface GoalCommandResponse { + goal: Goal | null; + state: GoalModeState | null; +} + /** Mirror of omp's RpcSessionState (the raw `get_state` payload). */ export interface RpcSessionState { model?: OmpModel; @@ -102,6 +130,8 @@ export interface RpcSessionState { tokensPerSecond?: number | null; /** Structured skill resolution diagnostics; absent on older OMP builds. */ skillDiagnostics?: SkillDiagnosticsSnapshot; + /** Goal mode snapshot; absent on OMP builds without the `goal` RPC. */ + goal?: GoalModeState | null; } /** @@ -139,6 +169,8 @@ export interface WebSessionState { tokensPerSecond?: number | null; /** Parsed public diagnostics DTO; absent means unsupported or malformed. */ skillDiagnostics?: SkillDiagnosticsSnapshot; + /** Goal mode snapshot; absent when the live child has not reported it. */ + goal?: GoalModeState | null; todoPhases: TodoPhase[]; extensionStatuses: Array<{ key: string; text: string }>; extensionWidgets: Array<{ key: string; lines: string[]; placement: "aboveEditor" | "belowEditor" }>; diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 9436d4df2..11e5db355 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -169,6 +169,7 @@ const PASSTHROUGH_COMMANDS = new Set([ "btw", "btw_cancel", "get_btw_history", + "goal", ]); // Outlasts omp's cold prediction-daemon start (up to 3 × 30s start rounds plus a @@ -2123,6 +2124,7 @@ export class AgentSessionWrapper { slowModeScope: state.slowModeScope, usageLimit: state.usageLimit, ...(skillDiagnostics ? { skillDiagnostics } : {}), + ...(state.goal !== undefined ? { goal: state.goal } : {}), todoPhases: state.todoPhases ?? [], extensionStatuses: Array.from(this.extensionStatuses, ([key, text]) => ({ key, text })), extensionWidgets: Array.from(this.extensionWidgets.values()), diff --git a/lib/web-mode-state.test.mjs b/lib/web-mode-state.test.mjs deleted file mode 100644 index 0051150d0..000000000 --- a/lib/web-mode-state.test.mjs +++ /dev/null @@ -1,27 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { createActiveGoal, formatGoalElapsed, parseActiveGoal } from "./web-mode-state.ts"; - -test("goal state trims its objective and keeps its start time", () => { - assert.deepEqual(createActiveGoal(" Ship the sidebar ", 123), { - objective: "Ship the sidebar", - startedAt: 123, - }); -}); - -test("goal state parser accepts only valid persisted goal records", () => { - assert.deepEqual(parseActiveGoal('{"objective":"Ship it","startedAt":123}'), { - objective: "Ship it", - startedAt: 123, - }); - assert.equal(parseActiveGoal('{"objective":"","startedAt":123}'), null); - assert.equal(parseActiveGoal('{"objective":"Ship it","startedAt":"123"}'), null); - assert.equal(parseActiveGoal("not JSON"), null); -}); - -test("goal elapsed formatter is stable at minute and hour boundaries", () => { - assert.equal(formatGoalElapsed(-1), "0m"); - assert.equal(formatGoalElapsed(59_999), "0m"); - assert.equal(formatGoalElapsed(60_000), "1m"); - assert.equal(formatGoalElapsed(3_660_000), "1h 1m"); -}); diff --git a/lib/web-mode-state.ts b/lib/web-mode-state.ts index 3e9dfb2e8..47423063b 100644 --- a/lib/web-mode-state.ts +++ b/lib/web-mode-state.ts @@ -1,34 +1,3 @@ -export interface ActiveGoal { - objective: string; - startedAt: number; -} - export interface ActivePlan { objective: string; } - -export function createActiveGoal(objective: string, startedAt = Date.now()): ActiveGoal { - return { objective: objective.trim(), startedAt }; -} - -/** Parse sessionStorage safely: user data and old versions must never break chat. */ -export function parseActiveGoal(value: string | null): ActiveGoal | null { - if (!value) return null; - try { - const parsed: unknown = JSON.parse(value); - if (!parsed || typeof parsed !== "object") return null; - const { objective, startedAt } = parsed as Record; - if (typeof objective !== "string" || !objective.trim() - || typeof startedAt !== "number" || !Number.isFinite(startedAt) || startedAt < 0) return null; - return { objective, startedAt }; - } catch { - return null; - } -} - -export function formatGoalElapsed(elapsedMs: number): string { - const elapsedMinutes = Math.max(0, Math.floor(elapsedMs / 60_000)); - const hours = Math.floor(elapsedMinutes / 60); - const minutes = elapsedMinutes % 60; - return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`; -} diff --git a/lib/web-slash-commands.test.mjs b/lib/web-slash-commands.test.mjs index 2f6d9558a..af9399e4e 100644 --- a/lib/web-slash-commands.test.mjs +++ b/lib/web-slash-commands.test.mjs @@ -9,17 +9,17 @@ test("exposes the expected command set with hints and arg requirements", async ( const { WEB_SLASH_COMMANDS } = await loadSubject(); const names = WEB_SLASH_COMMANDS.map((command) => command.name); - assert.deepEqual(names, ["goal", "plan", "review", "fix", "test", "explain", "simplify", "commit", "advisor", "loop"]); + assert.deepEqual(names, ["plan", "fix", "test", "explain", "simplify", "commit", "loop"]); assert.ok(WEB_SLASH_COMMANDS.every((command) => command.descriptionKey.startsWith("chatInput.cmd"))); assert.ok(WEB_SLASH_COMMANDS.every((command) => command.argumentHintKey.startsWith("chatInput.cmd"))); const required = new Set(WEB_SLASH_COMMANDS.filter((command) => command.requiresArgs).map((command) => command.name)); - assert.deepEqual(required, new Set(["goal", "plan", "fix", "test", "explain", "simplify", "loop"])); + assert.deepEqual(required, new Set(["plan", "fix", "test", "explain", "simplify", "loop"])); }); test("lookup resolves by primary name only", async () => { const { getWebSlashCommand } = await loadSubject(); - assert.equal(getWebSlashCommand("goal")?.name, "goal"); + assert.equal(getWebSlashCommand("goal"), undefined); assert.equal(getWebSlashCommand("plan")?.name, "plan"); assert.equal(getWebSlashCommand("vibe"), undefined); assert.equal(getWebSlashCommand("GOAL"), undefined); @@ -27,57 +27,40 @@ test("lookup resolves by primary name only", async () => { test("required-arg commands embed the args verbatim", async () => { const { getWebSlashCommand } = await loadSubject(); - const goal = getWebSlashCommand("goal"); - assert.ok(goal); - const prompt = goal.buildPrompt("ship the export feature"); + const plan = getWebSlashCommand("plan"); + assert.ok(plan); + const prompt = plan.buildPrompt("ship the export feature"); - assert.match(prompt, /Work toward this goal for the rest of the session/); + assert.match(prompt, /Create a plan for this task/); assert.ok(prompt.includes("ship the export feature")); }); test("optional-arg commands degrade to a default when no args are given", async () => { const { getWebSlashCommand } = await loadSubject(); - const review = getWebSlashCommand("review"); const commit = getWebSlashCommand("commit"); - assert.ok(review); assert.ok(commit); - assert.match(review.buildPrompt(""), /current project state and recent changes/); - assert.match(review.buildPrompt("lib/model-catalog.ts"), /Review lib\/model-catalog\.ts for bugs/); - assert.match(commit.buildPrompt(""), /clear conventional commit message/); assert.match(commit.buildPrompt("feat: add catalog"), /commit the current changes with this message: "feat: add catalog"/); }); -test("advisor command reviews with or without a topic", async () => { - const { getWebSlashCommand, expandWebSlashCommand } = await loadSubject(); - const advisor = getWebSlashCommand("advisor"); - assert.ok(advisor); - - assert.match(advisor.buildPrompt(""), /independent advisor reviewing the current work/); - assert.match(advisor.buildPrompt("the retry logic"), /reviewing this work: the retry logic/); - - const expanded = expandWebSlashCommand("/advisor the retry logic"); - assert.equal(expanded.kind, "expand"); - if (expanded.kind === "expand") assert.match(expanded.prompt, /the retry logic/); -}); - test("expansion expands web commands, rejects missing args, and passes others through", async () => { const { expandWebSlashCommand } = await loadSubject(); - const expanded = expandWebSlashCommand("/goal ship the export"); + const expanded = expandWebSlashCommand("/plan ship the export"); assert.equal(expanded.kind, "expand"); if (expanded.kind === "expand") assert.match(expanded.prompt, /ship the export/); - const usage = expandWebSlashCommand("/goal "); + const usage = expandWebSlashCommand("/plan "); assert.equal(usage.kind, "usage-error"); if (usage.kind === "usage-error") { - assert.equal(usage.command, "/goal"); - assert.equal(usage.argumentHintKey, "chatInput.cmdGoalArg"); + assert.equal(usage.command, "/plan"); + assert.equal(usage.argumentHintKey, "chatInput.cmdPlanArg"); } - // Plain messages and non-web commands are not the client's business. + // Plain messages and commands omp owns are not the client's business. assert.equal(expandWebSlashCommand("just a message").kind, "not-web"); + assert.equal(expandWebSlashCommand("/goal ship the export").kind, "not-web"); assert.equal(expandWebSlashCommand("/compact").kind, "not-web"); assert.equal(expandWebSlashCommand("/vibe go fast").kind, "not-web"); }); diff --git a/lib/web-slash-commands.ts b/lib/web-slash-commands.ts index 0cd1bcddd..b34a3844a 100644 --- a/lib/web-slash-commands.ts +++ b/lib/web-slash-commands.ts @@ -1,12 +1,14 @@ /** * Web-native slash commands (prompt-composing). * - * omp's own `/goal`, `/plan`, `/vibe`, ... are TUI-only builtins (`handleTui`); - * the RPC prompt path (which omp-web uses) forwards them as literal user text - * instead of executing them. These client-side commands fill that gap: the - * palette advertises them and the client built-in dispatcher expands them into - * effective prompts sent through the normal prompt pipeline, so the agent - * actually receives a clear instruction rather than a stray "/goal ..." line. + * omp executes every command in its RPC catalog (builtin, extension, custom, + * MCP prompt, file, skill) when it arrives through `prompt`, so those are never + * expanded here. The entries below are omp-web conveniences for names omp does + * not provide; the dispatcher only uses one when omp's catalog does not already + * own that name, so an extension/skill command always wins. + * + * `/goal` is not here either: it uses omp's native `goal` RPC (goal mode is not + * a slash builtin over RPC). * * Pure definitions — no I/O. Prompt text is deliberately concise; the args are * user-supplied and embedded verbatim. @@ -15,24 +17,16 @@ export interface WebSlashCommandDef { name: string; descriptionKey: string; - /** i18n key for the bracketed argument hint shown in the palette, e.g. "[goal]". */ + /** i18n key for the bracketed argument hint shown in the palette, e.g. "[task]". */ argumentHintKey: string; /** Commands without args refuse to run and surface usage instead. */ requiresArgs: boolean; buildPrompt: (args: string) => string; } -const GOAL_PROMPT = (args: string) => - `Work toward this goal for the rest of the session:\n\n${args}\n\nTreat it as the objective to prioritize when deciding what to do next.`; - const PLAN_PROMPT = (args: string) => `Create a plan for this task before doing anything else:\n\n${args}\n\nThink it through step by step, list concrete steps, and state what you will verify when done.`; -const REVIEW_PROMPT = (args: string) => - args - ? `Review ${args} for bugs, security issues, and opportunities to simplify. Summarize what you find, then fix anything clearly wrong.` - : `Review the current project state and recent changes for bugs, security issues, and opportunities to simplify. Summarize what you find, then fix anything clearly wrong.`; - const FIX_PROMPT = (args: string) => `Fix this issue:\n\n${args}\n\nReproduce the problem, apply the smallest correct fix, and verify it works before finishing.`; @@ -50,11 +44,6 @@ const COMMIT_PROMPT = (args: string) => ? `Stage the relevant files and commit the current changes with this message: ${JSON.stringify(args)}. Run the project's checks first so the commit is green.` : `Stage the relevant files and commit the current changes with a clear conventional commit message. Run the project's checks first so the commit is green.`; -const ADVISOR_PROMPT = (args: string) => - args - ? `Act as an independent advisor reviewing this work: ${args}. Assess the approach, point out risks, gaps, and better alternatives, and give concrete recommendations without changing any code.` - : `Act as an independent advisor reviewing the current work. Assess the recent changes and overall direction, point out risks, gaps, and better alternatives, and give concrete recommendations without changing any code.`; - const LOOP_MAX_ATTEMPTS = 10; const LOOP_DEFAULT_ATTEMPTS = 3; @@ -66,13 +55,6 @@ const LOOP_PROMPT = (args: string) => { }; export const WEB_SLASH_COMMANDS: readonly WebSlashCommandDef[] = [ - { - name: "goal", - descriptionKey: "chatInput.cmdGoal", - argumentHintKey: "chatInput.cmdGoalArg", - requiresArgs: true, - buildPrompt: GOAL_PROMPT, - }, { name: "plan", descriptionKey: "chatInput.cmdPlan", @@ -80,13 +62,6 @@ export const WEB_SLASH_COMMANDS: readonly WebSlashCommandDef[] = [ requiresArgs: true, buildPrompt: PLAN_PROMPT, }, - { - name: "review", - descriptionKey: "chatInput.cmdReview", - argumentHintKey: "chatInput.cmdReviewArg", - requiresArgs: false, - buildPrompt: REVIEW_PROMPT, - }, { name: "fix", descriptionKey: "chatInput.cmdFix", @@ -122,13 +97,6 @@ export const WEB_SLASH_COMMANDS: readonly WebSlashCommandDef[] = [ requiresArgs: false, buildPrompt: COMMIT_PROMPT, }, - { - name: "advisor", - descriptionKey: "chatInput.cmdAdvisor", - argumentHintKey: "chatInput.cmdAdvisorArg", - requiresArgs: false, - buildPrompt: ADVISOR_PROMPT, - }, { name: "loop", descriptionKey: "chatInput.cmdLoop", @@ -149,7 +117,7 @@ export type WebSlashCommandExpansion = | { kind: "not-web" }; /** - * Resolve a full command line (e.g. "/goal ship the export") into either the + * Resolve a full command line (e.g. "/plan ship the export") into either the * expanded prompt to send, a usage error for a required-arg command with no * args, or "not-web" for commands the client does not own. Single source of * truth for both the idle dispatcher and the streaming queue path, so a web From 8ca4359486adb51fe9bc5696e2e6ee42b0f006b3 Mon Sep 17 00:00:00 2001 From: killcerr Date: Fri, 30 Oct 2026 00:22:59 +0800 Subject: [PATCH 2/9] fix(chat): harden native command routing and goal state - Skip malformed goal_updated payloads instead of treating them as clears. - Require a returned goal before publishing/promoting, and fence late goal replies/actions to their session. - Refuse client-only commands with attachments instead of silently dropping them. - Let catalog names and aliases win over client-only dispatch, including the palette ownership check. - Patch manual compaction results and fence goal mutations during history edits. - Add regression tests for the new edge cases. --- AGENTS.md | 8 +- components/ChatInput-banners.test.mjs | 29 +++++++ .../ChatInput.queue-attachments.test.mjs | 82 ++++++++++++++++--- components/ChatInput.tsx | 26 ++++-- ...-29-native-slash-commands-and-goal-mode.md | 30 +++++-- hooks/useAgentSession-stream.ts | 3 + hooks/useAgentSession.rpc.test.mjs | 54 ++++++++++++ hooks/useAgentSession.ts | 15 +++- lib/goal-state.test.mjs | 9 ++ lib/goal-state.ts | 27 ++++-- lib/i18n/locales/en.json | 2 + lib/i18n/locales/ja.json | 2 + lib/i18n/locales/zh-CN.json | 2 + lib/rpc-manager.ts | 23 +++++- 14 files changed, 272 insertions(+), 40 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c6cbebdee..41811615c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -956,9 +956,11 @@ Full behavior and rationale: `docs/specs/2026-10-29-native-slash-commands-and-go `goal` (native `goal` RPC), `btw`, `reload`, `name`, `copy`. Web prompt expansions (`plan`, `fix`, `test`, `explain`, `simplify`, `commit`, `loop`) are used only when omp does not report the same name, so an extension or - skill command always wins. `/compact`, `/session`, `/review`, `/advisor` are - omp commands; the top-bar compact button and context ring remain the web - entry points for those panels. + skill command always wins. Catalog names and aliases always win over a + client entry, including the client-only names. Client-only commands refuse + attachments and keep the draft. `/compact`, `/session`, `/review`, + `/advisor` are omp commands; the top-bar compact button and context ring + remain the web entry points for those panels. - `/goal` is native goal mode: `{type:"goal",op:"create",objective}` plus `goal_updated`/`get_state.goal`; pause/resume/drop send the matching op. No `sessionStorage` goal state. Goal snapshots are sequenced so a slow diff --git a/components/ChatInput-banners.test.mjs b/components/ChatInput-banners.test.mjs index 73397ab09..4a4cadbf0 100644 --- a/components/ChatInput-banners.test.mjs +++ b/components/ChatInput-banners.test.mjs @@ -45,6 +45,35 @@ test("an active goal shows its status, objective, tokens and pause/drop actions" assert.deepEqual(actions, ["pause", "drop"]); }); +test("goal controls stay disabled until a pending action settles", async () => { + const actions = []; + let release; + render(React.createElement(ComposerModeStatus, { + goal: state(goal()), + onGoalAction: (op) => { + actions.push(op); + return new Promise((resolve) => { release = resolve; }); + }, + })); + + fireEvent.click(screen.getByRole("button", { name: /ship the export/ })); + fireEvent.click(screen.getByRole("button", { name: /^Pause$/ })); + const pause = screen.getByRole("button", { name: /^Pause$/ }); + const drop = screen.getByRole("button", { name: /^Drop$/ }); + assert.equal(pause.disabled, true); + assert.equal(drop.disabled, true); + + fireEvent.click(drop); + assert.deepEqual(actions, ["pause"]); + + await act(async () => { + release(); + await Promise.resolve(); + }); + assert.equal(pause.disabled, false); + assert.equal(drop.disabled, false); +}); + test("a paused goal offers resume, and a finished goal offers no actions", async () => { const actions = []; const view = render(React.createElement(ComposerModeStatus, { diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 16150e883..2aa88e6d5 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -60,7 +60,7 @@ afterEach(() => { }); /** A composer with an image and a text file attached through the picker path. */ -async function renderWithAttachments({ queued = true, queueCallbacks = true, ...props } = {}) { +async function renderWithAttachments({ queued = true, queueCallbacks = true, attachments = true, ...props } = {}) { const calls = []; // Images are the last argument of every queue callback, which resolves // false when omp refused the message. @@ -81,17 +81,19 @@ async function renderWithAttachments({ queued = true, queueCallbacks = true, ... ...props, }; const view = render(React.createElement(ChatInput, inputProps)); - await act(async () => { - ref.current.addFiles([ - new File([Buffer.from(PNG, "base64")], "dot.png", { type: "image/png" }), - new File(["hello"], "notes.txt", { type: "text/plain" }), - ]); - }); - await waitFor(() => { - const draft = getDraft(KEY); - assert.equal(draft?.images.length, 1, "the image is attached"); - assert.equal(draft?.files.length, 1); - }); + if (attachments) { + await act(async () => { + ref.current.addFiles([ + new File([Buffer.from(PNG, "base64")], "dot.png", { type: "image/png" }), + new File(["hello"], "notes.txt", { type: "text/plain" }), + ]); + }); + await waitFor(() => { + const draft = getDraft(KEY); + assert.equal(draft?.images.length, 1, "the image is attached"); + assert.equal(draft?.files.length, 1); + }); + } return { calls, ref, @@ -173,6 +175,7 @@ test("a queued /goal runs the native goal RPC instead of entering the prompt que const user = userEvent.setup(); const builtins = []; const calls = await renderRunningWithAttachments({ + attachments: false, onBuiltinCommand: async (message) => { builtins.push(message); return { handled: true }; @@ -186,6 +189,47 @@ test("a queued /goal runs the native goal RPC instead of entering the prompt que await waitFor(() => assert.equal(getDraft(KEY), null)); }); +test("a queued /goal with attachments is refused and keeps the draft", async () => { + window.HTMLElement.prototype.scrollIntoView = () => {}; + const user = userEvent.setup(); + const builtins = []; + const calls = await renderRunningWithAttachments({ + onBuiltinCommand: async (message) => { + builtins.push(message); + return { handled: true }; + }, + }); + await user.type(screen.getByRole("textbox"), "/goal ship it"); + await user.keyboard("{Enter}"); + await waitFor(() => assert.equal(screen.getByRole("textbox").value, "/goal ship it")); + delete window.HTMLElement.prototype.scrollIntoView; + assert.deepEqual(builtins, [], "no goal RPC with attachments"); + assert.equal(calls.length, 0, "no prompt is queued"); + assert.equal(getDraft(KEY)?.images.length, 1); + assert.equal(getDraft(KEY)?.files.length, 1); +}); + +test("an idle /goal with attachments is refused and keeps the draft", async () => { + window.HTMLElement.prototype.scrollIntoView = () => {}; + const user = userEvent.setup(); + const builtins = []; + const calls = await renderRunningWithAttachments({ + isStreaming: false, + onBuiltinCommand: async (message) => { + builtins.push(message); + return { handled: true }; + }, + }); + await user.type(screen.getByRole("textbox"), "/goal ship it"); + await user.keyboard("{Enter}"); + await waitFor(() => assert.equal(screen.getByRole("textbox").value, "/goal ship it")); + delete window.HTMLElement.prototype.scrollIntoView; + assert.deepEqual(builtins, [], "no goal RPC with attachments"); + assert.equal(calls.length, 0, "no prompt is sent"); + assert.equal(getDraft(KEY)?.images.length, 1); + assert.equal(getDraft(KEY)?.files.length, 1); +}); + test("a queued message stays in the composer until the outbox has it, and stays whole when refused", async () => { let refuse; const calls = await renderRunningWithAttachments({ queued: new Promise((resolve) => { refuse = () => resolve(false); }) }); @@ -199,6 +243,20 @@ test("a queued message stays in the composer until the outbox has it, and stays assert.equal(getDraft(KEY)?.files.length, 1); }); +test("a refused follow-up goes back whole to its draft, ahead of what was typed meanwhile", async () => { + let refuse; + const calls = await renderRunningWithAttachments({ queued: new Promise((resolve) => { refuse = () => resolve(false); }) }); + fireEvent.click(screen.getByRole("button", { name: /queue/i })); + await waitFor(() => assert.equal(calls.length, 1)); + assert.equal(screen.getByRole("status").textContent, "Sending…", "the in-flight message shows until omp answers"); + fireEvent.change(screen.getByRole("textbox"), { target: { value: "typed meanwhile" } }); + await act(async () => { refuse(); }); + await waitFor(() => assert.equal(screen.queryByRole("status"), null, "the sending row goes once omp answered")); + await waitFor(() => assert.deepEqual(getDraft(KEY)?.images, [{ data: PNG, mimeType: "image/png" }])); + assert.equal(getDraft(KEY)?.value, `${calls[0].message}\n\ntyped meanwhile`, "the text, file contents included, comes back too"); + assert.equal(screen.getByRole("textbox").value, `${calls[0].message}\n\ntyped meanwhile`); +}); + test("a queued message is not cleared once stored if the composer changed meanwhile", async () => { let store; const calls = await renderRunningWithAttachments({ queued: new Promise((resolve) => { store = () => resolve(true); }) }); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 0da08be1c..6691aa087 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -427,7 +427,7 @@ export const ChatInput = memo(forwardRef(function ChatIn // Names omp's catalog reports. A web prompt expansion of the same name must // yield to omp's own command (extension/custom/skill/builtin). const ompCommandNames = React.useMemo( - () => new Set((slashCommands ?? []).map((command) => command.name)), + () => new Set((slashCommands ?? []).flatMap((command) => [command.name, ...(command.aliases ?? [])])), [slashCommands], ); const usageLimitLabel = usageLimit @@ -1257,6 +1257,13 @@ export const ChatInput = memo(forwardRef(function ChatIn onAudioUnlock?.(); if (sendSideQuestion(msg, overrideText)) return; if (rejectsPendingUploads()) return; + if (msg.startsWith("/") && (attachedImagesRef.current.length || attachedTextFilesRef.current.length || attachedUploadsRef.current.length)) { + const commandName = msg.slice(1).split(/\s+/)[0]; + if (CLIENT_ONLY_COMMAND_NAMES[commandName] === true && !ompCommandNames.has(commandName)) { + toast.error(t("chatInput.commandAttachmentsUnsupported")); + return; + } + } const composedMessage = composeMessageWithTextAttachments(msg, attachedTextFilesRef.current); if (!attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length && msg.startsWith("/") && onBuiltinCommand) { const commandName = msg.slice(1).split(/\s+/)[0]; @@ -1302,7 +1309,7 @@ export const ChatInput = memo(forwardRef(function ChatIn if (key) recoverDraft(key, recovery); throw error; } - }, [value, isStreaming, onBuiltinCommand, onSend, outbox, clearInput, clearOnceStored, onAudioUnlock, ompCommandNames, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); + }, [value, isStreaming, onBuiltinCommand, onSend, outbox, clearInput, clearOnceStored, onAudioUnlock, ompCommandNames, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion, t]); const { isRecording, isPaused, @@ -1419,9 +1426,8 @@ export const ChatInput = memo(forwardRef(function ChatIn const builtinSlashCommands: SlashCommandPaletteItem[] = React.useMemo( () => BUILTIN_SLASH_COMMAND_DEFS - // Client-only actions always stay; web prompt expansions yield to an - // omp command with the same name. - .filter((def) => CLIENT_ONLY_COMMAND_NAMES[def.name] === true || !ompCommandNames.has(def.name)) + // The catalog wins over every client entry, including client-only names. + .filter((def) => !ompCommandNames.has(def.name)) .map((def) => ({ name: def.name, description: t(def.descriptionKey), @@ -1435,7 +1441,7 @@ export const ChatInput = memo(forwardRef(function ChatIn // client always dispatches itself is dropped so it appears exactly once. const externalSlashCommands: SlashCommandPaletteItem[] = React.useMemo( () => (slashCommands ?? []).flatMap((command): SlashCommandPaletteItem[] => { - if (CLIENT_ONLY_COMMAND_NAMES[command.name] === true) return []; + if (CLIENT_ONLY_COMMAND_NAMES[command.name] === true && !ompCommandNames.has(command.name)) return []; return [{ name: command.name, description: command.description, @@ -1443,7 +1449,7 @@ export const ChatInput = memo(forwardRef(function ChatIn source: command.source === "builtin" ? "ompBuiltin" : command.source, }]; }), - [slashCommands], + [slashCommands, ompCommandNames], ); const filteredSlashCommands = (() => { @@ -1786,7 +1792,11 @@ export const ChatInput = memo(forwardRef(function ChatIn // Client-dispatched commands (/goal uses the native goal RPC, /btw is a // side question) must not enter the prompt queue: omp would treat the // text as an ordinary message. Run them now, mid-run included. - if (CLIENT_ONLY_COMMAND_NAMES[commandName] === true) { + if (CLIENT_ONLY_COMMAND_NAMES[commandName] === true && !ompCommandNames.has(commandName)) { + if (attachedImagesRef.current.length || attachedTextFilesRef.current.length) { + toast.error(t("chatInput.commandAttachmentsUnsupported")); + return; + } if (onBuiltinCommand) void runBuiltinCommand(msg, overrideText); return; } diff --git a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md index 5afd67c76..11dfb05d5 100644 --- a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md +++ b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md @@ -76,7 +76,9 @@ These names have no omp slash equivalent and are dispatched by - `copy` — copy the last assistant text. They are listed in `CLIENT_ONLY_COMMAND_NAMES` -(`components/ChatInput-slash-commands.ts`). +(`components/ChatInput-slash-commands.ts`). They cannot carry attachments: the +composer refuses the command with a notice and keeps the draft and files, +rather than silently dropping them. ### 4.3 Web-only prompt expansions @@ -96,9 +98,11 @@ Precedence rules: - All sources are shown; `builtin` is no longer filtered out. - `input.hint` becomes the argument hint. -- Client-owned names are dropped from the external list so each command appears - once. +- Client-owned names are dropped from the external list unless omp reports the + same name, so each command appears once and the catalog still wins. - Web prompt expansions are dropped when `ompCommandNames` contains the name. +- `ompCommandNames` includes primary names and aliases, so an alias that + matches a web name still routes to omp. - While a run is streaming, client-owned commands are hidden from the palette but still work when typed; the streaming path intercepts them before the prompt queue. @@ -117,7 +121,8 @@ Precedence rules: This is what makes `/goal` work during a run: the goal RPC is sent while the current turn continues, and omp decides continuation at the next terminal -`agent_end`. +`agent_end`. A client-owned command with attachments is refused before any of +these steps, so a queued `/goal` cannot clear an attached file. ## 5. Native goal mode @@ -187,7 +192,11 @@ A present-but-malformed goal is rejected rather than treated as "no goal". `lib/rpc-manager.ts`: - Adds `"goal"` to `PASSTHROUGH_COMMANDS`. -- Maps `state.goal` into `WebSessionState` when omp reports it. +- Validates `state.goal` with `readGoalModeState` before mapping it into + `WebSessionState`: a valid `null` clears, a malformed snapshot is omitted + rather than forwarded. +- Fences goal `create` / `resume` / `pause` / `drop` against a history edit, + while the read-only `get` op stays available. - Forwards `goal_updated` through the existing default event path. `hooks/useAgentSession-stream.ts` adds `goal` to `AgentStateResponse`. @@ -203,7 +212,8 @@ A present-but-malformed goal is rejected rather than treated as "no goal". overwriting a newer goal. - `loadSession`, `refreshAgentSnapshots`, and `reconcileAgentState` all feed the goal snapshot. -- `goal_updated` publishes the event state. +- `goal_updated` publishes the event state; a malformed payload is skipped + instead of being treated as a clear. Session switching: @@ -235,6 +245,11 @@ Session switching: - Sends `{ type: "goal", op: "create", objective }`. - Never sends a prompt and never inserts the old "Work toward this goal…" message. +- Requires a returned goal before publishing state, promoting the session, or + announcing success; an empty or data-less success reply is an error and + keeps the existing goal. +- Fences the reply to the session that sent it: a late reply after a switch or + unmount is ignored. - Promotes a new chat to the real session id after success. - Shows omp's error and keeps the existing goal when create fails. @@ -246,6 +261,9 @@ publishes the response state. - `/compact` is now omp's builtin, so `soft`, `remote`, `snapcompact`, and focus text work. `manual_compaction_start` / `manual_compaction_end` update `isCompacting`, `compactResult`, and `compactError`, then reload the session. + The server patches `manual_compaction_end.result` with + `patchEstimatedTokensAfter` before forwarding it, so a result without + `estimatedTokensAfter` does not show the full pre-compaction count as saved. The composer/top-bar compact button still uses the `compact` RPC. - `/session` is now omp's builtin (`info`, `delete`, `pin`). The web stats panel is still available from the context ring; the old `/session` panel shortcut diff --git a/hooks/useAgentSession-stream.ts b/hooks/useAgentSession-stream.ts index bb1d3f666..c95d0f469 100644 --- a/hooks/useAgentSession-stream.ts +++ b/hooks/useAgentSession-stream.ts @@ -242,6 +242,8 @@ export interface CompactResultInfo { export interface SlashCommandInfo { name: string; + /** omp aliases (`models` for `model`); they invoke the same command. */ + aliases?: string[]; description?: string; source: "builtin" | "extension" | "prompt" | "skill"; /** Bracketed argument hint from omp's `input.hint`. */ @@ -545,6 +547,7 @@ export function toSlashCommandInfo(command: RpcAvailableSlashCommand): SlashComm : "prompt"; return { name: command.name, + ...(command.aliases?.length ? { aliases: command.aliases } : {}), description: command.description, source, ...(command.input?.hint ? { argumentHint: command.input.hint } : {}), diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index f00fd6d71..0f0b65c8f 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1260,6 +1260,60 @@ test("GOAL a failed create reports omp's error and keeps the existing goal", asy assert.equal(w.latest.goalState?.goal?.id, "g1"); }); +test("GOAL an empty create reply reports a failure and keeps the existing goal", async () => { + resetWorld(); + primeSession("goal-empty", [userMsg("u0", "loaded question")]); + world.agents.set("goal-empty", { running: false, state: { goal: goalState() } }); + const w = await mountSession("goal-empty"); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => ({ value: { success: true, data: { goal: null, state: null } } }), + }); + + const result = await act(async () => w.latest.handleBuiltinSlashCommand("/goal ship the export")); + assert.equal(result.message, undefined, "no start notice without a goal"); + assert.ok(result.error, "an empty create reply reports a failure"); + assert.equal(w.latest.goalState?.goal?.id, "g1"); +}); + +test("GOAL a success reply with no data does not announce a started goal", async () => { + resetWorld(); + primeSession("goal-no-data", [userMsg("u0", "loaded question")]); + const w = await mountSession("goal-no-data"); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => ({ value: { success: true } }), + }); + + const result = await act(async () => w.latest.handleBuiltinSlashCommand("/goal ship the export")); + assert.equal(result.message, undefined, "no start notice without data"); + assert.ok(result.error, "a reply without data reports a failure"); +}); + +test("GOAL a malformed goal_updated does not clear the banner", async () => { + resetWorld(); + primeSession("goal-malformed", [userMsg("u0", "loaded question")]); + world.agents.set("goal-malformed", { running: false, state: { goal: goalState() } }); + const w = await mountSession("goal-malformed"); + + await act(async () => w.latest.handleAgentEventRef.current({ type: "goal_updated", goal: null, state: { enabled: true } })); + assert.equal(w.latest.goalState?.goal?.id, "g1"); +}); + +test("GOAL an omp command named goal wins over the client dispatch", async () => { + resetWorld(); + primeSession("goal-shadow", [userMsg("u0", "loaded question")]); + const w = await mountSession("goal-shadow"); + await act(async () => w.latest.handleAgentEventRef.current({ + type: "available_commands_update", + commands: [{ name: "goal", source: "extension", description: "extension goal" }], + })); + + const result = await act(async () => w.latest.handleBuiltinSlashCommand("/goal ship it")); + assert.deepEqual(result, { handled: false }); + assert.equal(world.calls.some((call) => call.body?.type === "goal"), false, "no native goal RPC"); +}); + test("GOAL pause, resume and drop send the matching RPC and update the banner", async () => { resetWorld(); primeSession("goal-actions", [userMsg("u0", "loaded question")]); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index ff5bfe410..46d93184f 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -2666,7 +2666,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { break; } case "goal_updated": { - publishGoalState(readGoalUpdatedEvent(event)); + const nextGoal = readGoalUpdatedEvent(event); + if (nextGoal !== undefined) publishGoalState(nextGoal); break; } case "manual_compaction_start": { @@ -4130,6 +4131,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // the web prompt commands create it inside askBtw/handleSend, which // attach their own stream. const ensureRuntime = async () => sessionIdRef.current ?? await ensureNewSession(); + // The catalog wins over every client handler, including the client-only + // names: an extension/skill command called `goal`, `btw`, `reload`, + // `name`, or `copy` must not be shadowed. + if (knownSlashCommandNamesRef.current.includes(commandName)) return { handled: false }; switch (commandName) { case "reload": { @@ -4185,8 +4190,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { op: "create", objective, }); + if (!hookAliveRef.current || sessionIdRef.current !== sid) return { handled: true }; const parsed = readGoalCommandResponse(result); - if (parsed) publishGoalState(parsed.state); + if (!parsed?.goal) { + return complete({ handled: true, error: translate("agentSession.goalCreateFailed") }); + } + publishGoalState(parsed.state); // A goal created on the empty new-chat screen must adopt the real // session so a reload opens it instead of a fresh composer. promoteNewSession(); @@ -4199,7 +4208,6 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // command line through the prompt pipeline. Never expand a name omp // already reports — an extension command must win over a web // convenience of the same name. - if (knownSlashCommandNamesRef.current.includes(commandName)) return { handled: false }; const expansion = expandWebSlashCommand(text); if (expansion.kind === "not-web") return { handled: false }; if (expansion.kind === "usage-error") { @@ -4235,6 +4243,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } try { const result = await sendAgentCommand(sid, { type: "goal", op }); + if (!hookAliveRef.current || sessionIdRef.current !== sid) return; const parsed = readGoalCommandResponse(result); if (parsed) publishGoalState(parsed.state); } catch (e) { diff --git a/lib/goal-state.test.mjs b/lib/goal-state.test.mjs index e604be65b..c7059821f 100644 --- a/lib/goal-state.test.mjs +++ b/lib/goal-state.test.mjs @@ -56,6 +56,15 @@ test("the command response accepts drop's null state and synthesizes a bare goal assert.equal(bare?.state?.enabled, true); }); +test("malformed goal payloads never look like a valid clear", () => { + // A broken state alongside a null goal must be skipped, not published as a + // clear that hides the banner. + assert.equal(readGoalUpdatedEvent({ goal: null, state: { enabled: true } }), undefined); + assert.equal(readGoalUpdatedEvent({ goal: { objective: "" }, state: null }), undefined); + assert.equal(readGoalUpdatedEvent({}), undefined); + assert.equal(readGoalCommandResponse({ goal: null, state: { enabled: true } }), null); +}); + test("elapsed time extrapolates only while active and formats compactly", () => { const active = { enabled: true, mode: "active", goal: GOAL }; assert.equal(goalElapsedSeconds(active, 2500), 90.5); diff --git a/lib/goal-state.ts b/lib/goal-state.ts index 9b5b3aad7..6d22fddc6 100644 --- a/lib/goal-state.ts +++ b/lib/goal-state.ts @@ -43,12 +43,26 @@ export function readGoalModeState(value: unknown): GoalModeState | null { return { enabled, mode, goal }; } -/** `goal_updated` event: prefer the full state, fall back to the bare goal. */ -export function readGoalUpdatedEvent(value: unknown): GoalModeState | null { - if (!isRecord(value)) return null; - const state = readGoalModeState(value.state); - if (state) return state; - return stateFromGoal(readGoal(value.goal)); +/** + * `goal_updated` event: prefer the full state, fall back to the bare goal. + * `undefined` means the payload is malformed and must not clear a displayed + * goal; `null` is a valid clear (`goal: null`). + */ +export function readGoalUpdatedEvent(value: unknown): GoalModeState | null | undefined { + if (!isRecord(value)) return undefined; + const hasGoal = "goal" in value; + const hasState = "state" in value; + if (!hasGoal && !hasState) return undefined; + + if (value.state != null) { + const state = readGoalModeState(value.state); + if (state) return state; + // A malformed state is only recoverable from a valid bare goal. + if (!hasGoal || value.goal == null) return undefined; + } + + if (value.goal === null) return null; + return stateFromGoal(readGoal(value.goal)) ?? undefined; } export function readGoalCommandResponse(value: unknown): GoalCommandResponse | null { @@ -57,6 +71,7 @@ export function readGoalCommandResponse(value: unknown): GoalCommandResponse | n const state = readGoalModeState(value.state); const goal = readGoal(value.goal); if (value.goal != null && !goal) return null; + if (value.state != null && !state) return null; if (state || goal) return { goal: goal ?? state?.goal ?? null, state: state ?? stateFromGoal(goal) }; // Both null is a valid "no goal" answer (drop/get). return { goal: null, state: null }; diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index a4142c7fd..6da27fa7b 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -47,6 +47,7 @@ "agentSession.noMessages": "(no messages)", "agentSession.goalStarted": "Goal started: {objective}", "agentSession.goalUsage": "Usage: /goal ", + "agentSession.goalCreateFailed": "OMP did not return a goal. The existing goal was kept.", "agentSession.noSessionToName": "No active session to name", "agentSession.noSessionToReload": "No active session to reload", "agentSession.openInBrowser": "Open in your browser: {url}", @@ -456,6 +457,7 @@ "chatInput.toolPresetDefault": "Read, bash, edit, write", "chatInput.toolPresetFull": "All tools, including subagents", "chatInput.commandUsageTitle": "Command usage", + "chatInput.commandAttachmentsUnsupported": "This command can't include attachments. Remove them, or send the message as a normal prompt.", "chatInput.cmdGoal": "Set the goal for this session", "chatInput.cmdGoalArg": "[goal]", "chatInput.goalActive": "Goal active", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 38fb5184e..564d89a54 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -47,6 +47,7 @@ "agentSession.noMessages": "(メッセージなし)", "agentSession.goalStarted": "目標を開始しました: {objective}", "agentSession.goalUsage": "使用法: /goal <目標>", + "agentSession.goalCreateFailed": "OMP が目標を返しませんでした。既存の目標を保持しました。", "agentSession.noSessionToName": "名前を付けられるアクティブなセッションがありません", "agentSession.noSessionToReload": "再読み込みできるアクティブなセッションがありません", "agentSession.openInBrowser": "ブラウザで開いてください: {url}", @@ -439,6 +440,7 @@ "chatInput.toolPresetDefault": "read、bash、edit、write", "chatInput.toolPresetFull": "すべてのツール(サブエージェントを含む)", "chatInput.commandUsageTitle": "コマンドの使い方", + "chatInput.commandAttachmentsUnsupported": "このコマンドには添付ファイルを含められません。添付を外すか、通常のメッセージとして送信してください。", "chatInput.cmdGoal": "セッションの目標を設定する", "chatInput.cmdGoalArg": "[目標]", "chatInput.goalActive": "目標が有効", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 137f8478b..f050eb5f9 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -47,6 +47,7 @@ "agentSession.noMessages": "(暂无消息)", "agentSession.goalStarted": "目标已开始:{objective}", "agentSession.goalUsage": "用法:/goal <目标>", + "agentSession.goalCreateFailed": "OMP 未返回目标,已保留原目标。", "agentSession.noSessionToName": "没有可命名的活动会话", "agentSession.noSessionToReload": "没有可重新加载的活动会话", "agentSession.openInBrowser": "请在浏览器中打开:{url}", @@ -439,6 +440,7 @@ "chatInput.toolPresetDefault": "read、bash、edit、write", "chatInput.toolPresetFull": "全部工具(含子代理)", "chatInput.commandUsageTitle": "命令用法", + "chatInput.commandAttachmentsUnsupported": "该命令不能包含附件。请移除附件,或作为普通消息发送。", "chatInput.cmdGoal": "设定本次会话的目标", "chatInput.cmdGoalArg": "[目标]", "chatInput.goalActive": "目标进行中", diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 11e5db355..b4fdde03b 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -21,12 +21,14 @@ import { markShuttingDown, recordRunningSessions, resumeOnHostLink, takeInterrup import { RESUME_PROMPT } from "./hosts/host-resume"; import { samePath } from "./paths"; import { isRecord } from "./type-guards"; +import { readGoalModeState } from "./goal-state"; import { BLOCKING_UI_METHODS, createNotificationDetector } from "./notification-events"; import { publishNotification } from "./notification-hub"; import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "./skill-diagnostics"; import { eventWithToolResultImageUrls } from "./media-cache"; import type { BashResultInfo, + GoalModeState, OmpModel, RpcAvailableSlashCommand, RpcSessionState, @@ -1263,6 +1265,11 @@ export class AgentSessionWrapper { patchEstimatedTokensAfter(event.result); this.invalidateSessionLists(); break; + case "manual_compaction_end": + // `/compact` runs through omp's builtin; the client reads this event + // result for the banner, so patch it like the RPC response path. + patchEstimatedTokensAfter(event.result); + break; case "notice": if (event.source === "session-persistence") void this.followSessionMove(); break; @@ -2083,6 +2090,13 @@ export class AgentSessionWrapper { notifyRunningChange(); } const skillDiagnostics = parseSkillDiagnosticsSnapshot(state.skillDiagnostics); + // `get_state.goal` is untrusted wire data. Preserve a valid null clear and + // omit a malformed snapshot instead of forwarding it to the banner. + const goal: GoalModeState | null | undefined = state.goal === undefined + ? undefined + : state.goal === null + ? null + : readGoalModeState(state.goal) ?? undefined; return { sessionId: state.sessionId, sessionFile: state.sessionFile ?? "", @@ -2124,7 +2138,7 @@ export class AgentSessionWrapper { slowModeScope: state.slowModeScope, usageLimit: state.usageLimit, ...(skillDiagnostics ? { skillDiagnostics } : {}), - ...(state.goal !== undefined ? { goal: state.goal } : {}), + ...(goal !== undefined ? { goal } : {}), todoPhases: state.todoPhases ?? [], extensionStatuses: Array.from(this.extensionStatuses, ([key, text]) => ({ key, text })), extensionWidgets: Array.from(this.extensionWidgets.values()), @@ -2513,7 +2527,12 @@ export class AgentSessionWrapper { if (typeof command.type === "string" && command.type.startsWith("abort")) { console.info("[omp-web] cancellation-command", JSON.stringify({ sessionId: this._sessionId, type: command.type, at: new Date().toISOString() })); } - const mutatesHistory = HISTORY_MUTATING_COMMANDS.has(command.type as string); + const commandType = command.type as string; + // Goal mutations change session state and the active tool set, so they + // must not race a history edit. The read-only `get` op stays available. + const mutatesHistory = + HISTORY_MUTATING_COMMANDS.has(commandType) + || (commandType === "goal" && command.op !== "get"); if (mutatesHistory && this.historyEditInFlight) { throw new WebRpcError("Wait for the history edit to finish", "session_busy"); } From f99fd7b36b6cfd6afa33f5d2c6938bfcf5a4626d Mon Sep 17 00:00:00 2001 From: killcerr Date: Fri, 30 Oct 2026 00:56:21 +0800 Subject: [PATCH 3/9] fix(chat): address the follow-up goal and btw review findings - Fence pause/resume/drop replies against a newer goal_updated. - Let a catalog-owned btw command bypass the client side-question panel. - Reject a goal command reply whose state describes a different goal. - Document that cold/reaped sessions restore the goal only after omp starts. - Add a composer regression test for a catalog-owned /goal. --- .../ChatInput.queue-attachments.test.mjs | 17 +++++++++ components/ChatInput.tsx | 5 +-- ...-29-native-slash-commands-and-goal-mode.md | 8 +++-- hooks/useAgentSession.rpc.test.mjs | 35 +++++++++++++++++++ hooks/useAgentSession.ts | 3 +- lib/goal-state.test.mjs | 8 +++++ lib/goal-state.ts | 1 + 7 files changed, 72 insertions(+), 5 deletions(-) diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 2aa88e6d5..64e032aed 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -230,6 +230,23 @@ test("an idle /goal with attachments is refused and keeps the draft", async () = assert.equal(getDraft(KEY)?.files.length, 1); }); +test("a catalog-owned /goal is forwarded to onSend", async () => { + window.HTMLElement.prototype.scrollIntoView = () => {}; + const user = userEvent.setup(); + const calls = await renderRunningWithAttachments({ + attachments: false, + isStreaming: false, + slashCommands: [{ name: "goal", source: "extension", description: "extension goal" }], + onBuiltinCommand: async () => ({ handled: false }), + }); + await user.type(screen.getByRole("textbox"), "/goal ship it"); + await user.keyboard("{Enter}"); + await waitFor(() => assert.equal(calls.length, 1)); + delete window.HTMLElement.prototype.scrollIntoView; + assert.equal(calls[0].name, "onSend"); + assert.equal(calls[0].message, "/goal ship it"); +}); + test("a queued message stays in the composer until the outbox has it, and stays whole when refused", async () => { let refuse; const calls = await renderRunningWithAttachments({ queued: new Promise((resolve) => { refuse = () => resolve(false); }) }); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 6691aa087..cb06ed287 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -1238,14 +1238,15 @@ export const ChatInput = memo(forwardRef(function ChatIn * queued. Attachments cannot ride along, so refuse and keep the draft * rather than drop them. False when `msg` is not `/btw`. */ const sendSideQuestion = useCallback((msg: string, overrideText?: string): boolean => { - if (!/^\/btw(\s|$)/.test(msg) || !onBuiltinCommand) return false; + // A catalog command named `btw` wins over the client side-question panel. + if (!/^\/btw(\s|$)/.test(msg) || !onBuiltinCommand || ompCommandNames.has("btw")) return false; if (attachedImagesRef.current.length || attachedTextFilesRef.current.length || attachedUploadsRef.current.length) { toast.error(t("btw.attachmentsUnsupported")); return true; } runBuiltinCommand(msg, overrideText).catch(toastBtwError); return true; - }, [onBuiltinCommand, runBuiltinCommand, t]); + }, [onBuiltinCommand, ompCommandNames, runBuiltinCommand, t]); const handleSend = useCallback(async (overrideText?: string) => { const raw = overrideText ?? value; diff --git a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md index 11dfb05d5..9940eaa12 100644 --- a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md +++ b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md @@ -373,8 +373,12 @@ omp-web automatically defers to it: ## 10. Persistence and known limits -- A goal is journaled by omp in the session. Reload restores it from - `get_state.goal` once the session has a `.jsonl` file. +- A goal is journaled by omp in the session. With a live RPC child, reload + restores it from `get_state.goal`. A cold or reaped session has no child: + `/api/sessions/[id]/state` returns `{ running: false }` without a goal, so + the banner appears only after omp starts. The web does not parse the goal + journal (`mode_change` entries) today; that is the follow-up if cold-session + banners are required. - omp writes a session file lazily on the first message. A goal created on an empty new chat and followed by an immediate full reload has no file to list, so the session cannot be reopened until a message is sent. This is omp's diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 0f0b65c8f..f02801dc2 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1349,6 +1349,41 @@ test("GOAL pause, resume and drop send the matching RPC and update the banner", ); }); +test("GOAL an action reply cannot overwrite a newer goal_updated", async () => { + resetWorld(); + primeSession("goal-action-race", [userMsg("u0", "loaded question")]); + world.agents.set("goal-action-race", { running: false, state: { goal: goalState() } }); + const w = await mountSession("goal-action-race"); + + let release; + const responseGoal = { ...GOAL, updatedAt: 2000 }; + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => new Promise((resolve) => { + release = () => resolve({ + value: { success: true, data: { goal: responseGoal, state: goalState(responseGoal) } }, + }); + }), + }); + let action; + await act(async () => { + action = w.latest.handleGoalAction("pause"); + await sleep(20); + }); + + const paused = { ...GOAL, status: "paused", updatedAt: 2000 }; + await act(async () => { + w.latest.handleAgentEventRef.current({ type: "goal_updated", goal: paused, state: goalState(paused) }); + }); + await act(async () => { + release(); + await action; + }); + + assert.equal(w.latest.goalState?.goal?.status, "paused"); + assert.equal(w.latest.goalState?.goal?.updatedAt, 2000); +}); + test("ISSUE #167 sending a TUI-only command warns once and still delivers the text", async () => { resetWorld(); primeSession("tui-only", [userMsg("u0", "loaded question")]); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 46d93184f..711cf5004 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -4242,8 +4242,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return; } try { + const goalSeq = goalSeqRef.current; const result = await sendAgentCommand(sid, { type: "goal", op }); - if (!hookAliveRef.current || sessionIdRef.current !== sid) return; + if (!hookAliveRef.current || sessionIdRef.current !== sid || goalSeq !== goalSeqRef.current) return; const parsed = readGoalCommandResponse(result); if (parsed) publishGoalState(parsed.state); } catch (e) { diff --git a/lib/goal-state.test.mjs b/lib/goal-state.test.mjs index c7059821f..f69ef8b19 100644 --- a/lib/goal-state.test.mjs +++ b/lib/goal-state.test.mjs @@ -63,6 +63,14 @@ test("malformed goal payloads never look like a valid clear", () => { assert.equal(readGoalUpdatedEvent({ goal: { objective: "" }, state: null }), undefined); assert.equal(readGoalUpdatedEvent({}), undefined); assert.equal(readGoalCommandResponse({ goal: null, state: { enabled: true } }), null); + assert.equal(readGoalCommandResponse({ + goal: GOAL, + state: { enabled: true, mode: "active", goal: { ...GOAL, id: "g2" } }, + }), null); + assert.equal(readGoalCommandResponse({ + goal: GOAL, + state: { enabled: true, mode: "active", goal: null }, + }), null); }); test("elapsed time extrapolates only while active and formats compactly", () => { diff --git a/lib/goal-state.ts b/lib/goal-state.ts index 6d22fddc6..24d9fe14f 100644 --- a/lib/goal-state.ts +++ b/lib/goal-state.ts @@ -72,6 +72,7 @@ export function readGoalCommandResponse(value: unknown): GoalCommandResponse | n const goal = readGoal(value.goal); if (value.goal != null && !goal) return null; if (value.state != null && !state) return null; + if (goal && state && state.goal?.id !== goal.id) return null; if (state || goal) return { goal: goal ?? state?.goal ?? null, state: state ?? stateFromGoal(goal) }; // Both null is a valid "no goal" answer (drop/get). return { goal: null, state: null }; From 7e53298c880ec46aabf16cc5d8709de497184b4e Mon Sep 17 00:00:00 2001 From: killcerr Date: Fri, 30 Oct 2026 01:13:57 +0800 Subject: [PATCH 4/9] fix(chat): start a new goal with the objective prompt The TUI's /goal enters goal mode and submits the objective as the first prompt. The RPC goal create only changes state, so omp-web now sends the objective when idle; during a run it still only creates the goal. Documented the TUI parity and the continuationModes limit. --- AGENTS.md | 4 +++- ...-10-29-native-slash-commands-and-goal-mode.md | 11 ++++++----- hooks/useAgentSession.rpc.test.mjs | 16 +++++++++++++--- hooks/useAgentSession.ts | 10 ++++++++++ lib/i18n/locales/en.json | 1 + lib/i18n/locales/ja.json | 1 + lib/i18n/locales/zh-CN.json | 1 + 7 files changed, 35 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 41811615c..3e42b0bec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -963,7 +963,9 @@ Full behavior and rationale: `docs/specs/2026-10-29-native-slash-commands-and-go remain the web entry points for those panels. - `/goal` is native goal mode: `{type:"goal",op:"create",objective}` plus `goal_updated`/`get_state.goal`; pause/resume/drop send the matching op. No - `sessionStorage` goal state. Goal snapshots are sequenced so a slow + `sessionStorage` goal state. When idle, `/goal ` also sends the + objective as the first prompt (TUI parity); while a run is active it only + creates the goal. Goal snapshots are sequenced so a slow `get_state` cannot overwrite a newer `goal_updated` (same idea as the queue). - TUI-only builtins (`guided-goal`, `vibe`, `budget`, and `/plan`/`/loop` when absent from the catalog) have no RPC handler. `/plan`'s spec has only diff --git a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md index 9940eaa12..7ea884ae4 100644 --- a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md +++ b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md @@ -243,8 +243,10 @@ Session switching: - Requires a non-empty objective. - Sends `{ type: "goal", op: "create", objective }`. -- Never sends a prompt and never inserts the old - "Work toward this goal…" message. +- When idle, also submits the objective as the first prompt, matching the + TUI's `/goal ` (`handleGoalModeCommand` → `session.prompt(objective)`). + During a run it only creates the goal; the objective joins the next turn. +- Never inserts the old "Work toward this goal…" message. - Requires a returned goal before publishing state, promoting the session, or announcing success; an empty or data-less success reply is an error and keeps the existing goal. @@ -422,9 +424,8 @@ omp-web automatically defers to it: `lib/project-registry.test.mjs` was caused by a broken `node` shim on the test machine; re-running that file with a correct `PATH` passes 15/15. - Headed-browser smoke test against a live omp child: - - `/goal ship the export feature` sent only - `{"type":"goal","op":"create","objective":"ship the export feature"}` and - showed an active goal banner. + - `/goal ship the export feature` created the goal and, when idle, sent the + objective as the first prompt; the active goal banner showed. - Pause, resume, and drop sent only the matching `goal` op; the banner tracked each state. - A goal created while the agent was streaming sent the goal RPC and did not diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index f02801dc2..c136bd811 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1212,7 +1212,7 @@ const GOAL = { }; const goalState = (goal = GOAL) => ({ enabled: goal.status === "active", mode: "active", goal }); -test("GOAL /goal sends the native goal RPC and never a prompt", async () => { +test("GOAL /goal creates the goal and sends the objective as the first prompt", async () => { resetWorld(); primeSession("goal-create", [userMsg("u0", "loaded question")]); const w = await mountSession("goal-create"); @@ -1221,11 +1221,21 @@ test("GOAL /goal sends the native goal RPC and never a prompt", async () => { produce: () => ({ value: { success: true, data: { goal: GOAL, state: goalState() } } }), }); - const result = await act(async () => w.latest.handleBuiltinSlashCommand("/goal ship the export")); + let command; + await act(async () => { + command = w.latest.handleBuiltinSlashCommand("/goal ship the export"); + await sleep(30); + }); + let result; + await act(async () => { + lastEs().open(); + result = await command; + }); assert.equal(result.handled, true); const goalCalls = world.calls.filter((call) => call.body?.type === "goal"); assert.deepEqual(goalCalls.map((call) => call.body), [{ type: "goal", op: "create", objective: "ship the export" }]); - assert.equal(world.calls.some((call) => call.body?.type === "prompt"), false, "no prompt is sent"); + const promptCalls = world.calls.filter((call) => call.body?.type === "prompt"); + assert.deepEqual(promptCalls.map((call) => call.body), [{ type: "prompt", message: "ship the export" }]); assert.equal(w.latest.goalState?.goal?.id, "g1"); }); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 711cf5004..5fc755303 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -4199,6 +4199,16 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // A goal created on the empty new-chat screen must adopt the real // session so a reload opens it instead of a fresh composer. promoteNewSession(); + // The TUI's `/goal ` both enters goal mode and submits + // the objective as the first prompt. `goal create` alone does not + // start a turn, so do the same here when idle. During a run the + // goal is created only; the objective joins the next turn. + if (!agentRunningRef.current) { + const sent = await handleSend(objective); + if (sent.status !== "accepted") { + return complete({ handled: true, error: translate("agentSession.goalStartFailed") }); + } + } return complete({ handled: true, message: translate("agentSession.goalStarted", { objective }) }); } diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 6da27fa7b..08f583329 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -48,6 +48,7 @@ "agentSession.goalStarted": "Goal started: {objective}", "agentSession.goalUsage": "Usage: /goal ", "agentSession.goalCreateFailed": "OMP did not return a goal. The existing goal was kept.", + "agentSession.goalStartFailed": "Goal created, but the first prompt could not be sent.", "agentSession.noSessionToName": "No active session to name", "agentSession.noSessionToReload": "No active session to reload", "agentSession.openInBrowser": "Open in your browser: {url}", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 564d89a54..4833ed93a 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -48,6 +48,7 @@ "agentSession.goalStarted": "目標を開始しました: {objective}", "agentSession.goalUsage": "使用法: /goal <目標>", "agentSession.goalCreateFailed": "OMP が目標を返しませんでした。既存の目標を保持しました。", + "agentSession.goalStartFailed": "目標は作成されましたが、最初のプロンプトを送信できませんでした。", "agentSession.noSessionToName": "名前を付けられるアクティブなセッションがありません", "agentSession.noSessionToReload": "再読み込みできるアクティブなセッションがありません", "agentSession.openInBrowser": "ブラウザで開いてください: {url}", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index f050eb5f9..e78d24597 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -48,6 +48,7 @@ "agentSession.goalStarted": "目标已开始:{objective}", "agentSession.goalUsage": "用法:/goal <目标>", "agentSession.goalCreateFailed": "OMP 未返回目标,已保留原目标。", + "agentSession.goalStartFailed": "目标已创建,但首条消息发送失败。", "agentSession.noSessionToName": "没有可命名的活动会话", "agentSession.noSessionToReload": "没有可重新加载的活动会话", "agentSession.openInBrowser": "请在浏览器中打开:{url}", From cbecdee4de460f3ddd96b2c5a5dd2e77323c3da0 Mon Sep 17 00:00:00 2001 From: killcerr Date: Sat, 31 Oct 2026 19:52:15 +0800 Subject: [PATCH 5/9] fix(chat): preserve drafts and goal state across delayed commands --- CHANGELOG.md | 1 + .../ChatInput.queue-attachments.test.mjs | 61 ++++++++++++++++++- components/ChatInput.tsx | 22 +++++-- ...-29-native-slash-commands-and-goal-mode.md | 11 ++++ hooks/useAgentSession.rpc.test.mjs | 43 +++++++++++++ hooks/useAgentSession.ts | 20 ++++-- 6 files changed, 148 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a265c871b..39c109526 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -105,6 +105,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **The service installers set up the host daemon too.** `ompweb systemd install`, `ompweb-launchd install` and the Windows tray install now register `ompweb host` as a second unit (`ompweb-host`) next to the web service, restarting it after a 10 s delay so it can wait for the web server to write its host link on first install. `uninstall` and `status` cover both, and the tray menus show the daemon state. - **Forking a session or editing a message asks first.** The Fork button under a message and the Edit button under your own message now open a confirmation dialog, so a stray tap while scrolling no longer creates a new session or rewinds the current one. - **Expanded thinking blocks no longer collapse when a step finishes.** With "Expand thinking blocks by default" on, a thinking block opened while streaming, then moved into a closed Process details row as soon as the step committed. Thinking now stays out of the fold while the setting is on. +- **Delayed goal commands preserve newer user intent.** A dictated command no longer clears text or attachments added while its reply is pending, including attachment reads still in progress. A delayed goal-create reply cannot restore a paused, dropped, cleared or replaced goal or start its objective after that newer state arrives. - **All omp slash commands run natively, including extension and skill commands.** The composer used to hide omp's builtins and expand `/goal`, `/review`, `/advisor`, `/compact`, and `/session` into text prompts. Every command omp reports in `get_available_commands` (builtin, extension, custom, MCP prompt, file, skill) is now shown and sent through omp's own prompt pipeline; web-only prompt expansions (`/plan`, `/fix`, `/test`, `/explain`, `/simplify`, `/commit`, `/loop`) yield to an omp command of the same name. `/goal` now uses omp's native goal RPC (`goal_updated` / `get_state.goal`) with pause, resume and drop controls instead of a `sessionStorage` imitation. TUI-only commands that omp does not expose over RPC still warn and are sent as plain text. - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. - **An update whose worker died is reported as failed.** A running update whose worker process is gone, or whose lease has expired, now becomes a failed attempt the dialog can show and clean up, instead of waiting forever. diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 64e032aed..c441aaadd 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -670,7 +670,7 @@ test("recovered images past the attachment cap all stay in the composer", async // Keep the real useDictation hook: only browser capture and the STT job API // are controlled. Polls expose status; only the owner's claim returns text // and the send intent, matching the server job boundary. -function installPendingDictation({ holdUpload = false, holdClaim = false, after = "send" } = {}) { +function installPendingDictation({ holdUpload = false, holdClaim = false, after = "send", text = "transcribed words" } = {}) { const uploads = []; const polls = []; const claims = []; @@ -740,7 +740,7 @@ function installPendingDictation({ holdUpload = false, holdClaim = false, after await claimReady; return response({ status: "done", - text: "transcribed words", + text, after: claim.owner === uploads[0]?.owner ? after : undefined, }); } @@ -755,6 +755,63 @@ function installPendingDictation({ holdUpload = false, holdClaim = false, after }; } +for (const change of ["immediate", "none", "text", "attachments", "pending attachment"]) { + test(`a dictated goal only clears its unchanged draft after success: ${change}`, async () => { + const dictation = installPendingDictation({ text: "/goal ship it" }); + const user = userEvent.setup(); + const commands = []; + let release; + const { ref, calls } = await renderWithAttachments({ + attachments: false, + onBuiltinCommand: (message) => { + commands.push(message); + if (change === "immediate") return Promise.resolve({ handled: true }); + return new Promise((resolve) => { release = () => resolve({ handled: true }); }); + }, + }); + await user.click(screen.getByRole("button", { name: "Start dictation" })); + await user.click(screen.getByRole("button", { name: /^Queue$/ })); + await waitFor(() => assert.equal(dictation.uploads.length, 1)); + dictation.complete(); + await waitFor(() => assert.deepEqual(commands, ["/goal ship it"]), { timeout: 3000 }); + if (change === "immediate") { + await waitFor(() => assert.equal(screen.getByRole("textbox").value, "")); + assert.equal(getDraft(KEY), null); + assert.deepEqual(calls, []); + return; + } + await waitFor(() => assert.equal(screen.getByRole("textbox").value, "/goal ship it")); + + let finishRead; + if (change === "text") await user.type(screen.getByRole("textbox"), " newer draft"); + if (change === "attachments") { + await act(async () => ref.current.addFiles([ + new File([Buffer.from(PNG, "base64")], "new.png", { type: "image/png" }), + new File(["new contents"], "new.txt", { type: "text/plain" }), + ])); + await waitFor(() => assert.equal(getDraft(KEY)?.files.length, 1)); + } + if (change === "pending attachment") { + const file = new File(["pending contents"], "pending.txt", { type: "text/plain" }); + file.text = () => new Promise((resolve) => { finishRead = () => resolve("pending contents"); }); + await act(async () => ref.current.addFiles([file])); + } + const beforeReply = getDraft(KEY); + await act(async () => release()); + if (change === "none") { + assert.equal(screen.getByRole("textbox").value, ""); + assert.equal(getDraft(KEY), null); + } else { + assert.deepEqual(getDraft(KEY), beforeReply, "success must not clear a changed or still-reading draft"); + if (finishRead) { + await act(async () => finishRead()); + await waitFor(() => assert.equal(getDraft(KEY)?.files[0]?.content, "pending contents")); + } + } + assert.deepEqual(calls, [], "the command never enters the prompt queue"); + }); +} + for (const isStreaming of [false, true]) { for (const edit of ["unchanged", "newer text", "equal-text retype"]) { test(`automatic dictated ${isStreaming ? "queue" : "send"} ${edit === "unchanged" ? "clears after durable acceptance" : `preserves ${edit} through delayed acceptance`}`, async () => { diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index cb06ed287..62f5f9ba5 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -574,8 +574,9 @@ export const ChatInput = memo(forwardRef(function ChatIn const ta = textareaRef.current; if (!ta) { const current = valueRef.current; - valueRef.current = current + (current ? " " : "") + text; - setValue((v) => v + (v ? " " : "") + text); + const next = current + (current ? " " : "") + text; + valueRef.current = next; + setValue((value) => value + (value ? " " : "") + text); return; } const start = ta.selectionStart ?? ta.value.length; @@ -584,6 +585,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const after = ta.value.slice(end); const sep = before.length > 0 && !before.endsWith(" ") ? " " : ""; const newVal = before + sep + text + after; + // A command may finish before this insertion's React commit. valueRef.current = newVal; setValue(newVal); setAtQuery(null); @@ -1221,12 +1223,24 @@ export const ChatInput = memo(forwardRef(function ChatIn * started typing while the command ran). */ const runBuiltinCommand = useCallback(async (msg: string, overrideText?: string): Promise => { if (submissionBlockedRef.current || holdingRef.current || !onBuiltinCommand) return false; - const stored = clearOnceStored(overrideText ?? valueRef.current); + const sentValue = overrideText ?? valueRef.current; + const revision = attachmentRevisionRef.current; + const images = attachedImagesRef.current; + const files = attachedTextFilesRef.current; + // Dictation inserts overrideText in the same batch as dispatch. It still + // must match on completion; an override does not own subsequent typing. + const stored = clearOnceStored(sentValue); holdingRef.current = true; try { const result = await onBuiltinCommand(msg); if (!result.handled) return false; - if (!submissionBlockedRef.current && !result.error && !result.retainInput) stored(); + const unchanged = valueRef.current === sentValue + && attachmentRevisionRef.current === revision + && attachedImagesRef.current === images + && attachedTextFilesRef.current === files + && pendingImageCountRef.current === 0 + && pendingTextFileCountRef.current === 0; + if (!submissionBlockedRef.current && !result.error && !result.retainInput && unchanged) stored(); return true; } finally { stored.release(); diff --git a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md index 7ea884ae4..42bef7df8 100644 --- a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md +++ b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md @@ -124,6 +124,12 @@ current turn continues, and omp decides continuation at the next terminal `agent_end`. A client-owned command with attachments is refused before any of these steps, so a queued `/goal` cannot clear an attached file. +An asynchronous client command clears only its unchanged originating draft on +success. Dictation's explicit text override does not bypass that check: newer +typing, changed attachments and pending attachment reads are retained. Text +insertion updates the command's synchronous view before React commits, while +functional draft updates preserve same-batch recovery and identity-move merges. + ## 5. Native goal mode ### 5.1 RPC surface @@ -214,6 +220,11 @@ A present-but-malformed goal is rejected rather than treated as "no goal". goal snapshot. - `goal_updated` publishes the event state; a malformed payload is skipped instead of being treated as a clear. +- A synchronous `goalStateRef` mirrors accepted snapshots/events so a command + continuation sees updates received before React commits. A create reply is + published only if no newer goal event/response arrived; its automatic first + prompt requires that the same goal is still active. The normal active create + echo does not prevent the initial prompt. Session switching: diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index c136bd811..22cc5418e 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1239,6 +1239,49 @@ test("GOAL /goal creates the goal and sends the objective as the first prompt", assert.equal(w.latest.goalState?.goal?.id, "g1"); }); +for (const status of ["active", "paused", "dropped", "cleared", "replaced"]) { + test(`GOAL a delayed create reply respects the newer ${status} event`, async () => { + resetWorld(); + const sid = `goal-create-race-${status}`; + primeSession(sid, [userMsg("u0", "loaded question")]); + const w = await mountSession(sid); + let release; + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => new Promise((resolve) => { + release = () => resolve({ value: { success: true, data: { goal: GOAL, state: goalState() } } }); + }), + }); + let command; + await act(async () => { + command = w.latest.handleBuiltinSlashCommand("/goal ship the export"); + await sleep(20); + }); + const nextGoal = status === "cleared" ? null : { + ...GOAL, + id: status === "replaced" ? "g2" : GOAL.id, + status: status === "replaced" ? "active" : status, + updatedAt: 2000, + }; + const nextState = nextGoal ? goalState(nextGoal) : null; + // Deliver the event and old reply in one React batch: dispatch must use + // the latest wire state, not the state captured by the last render. + await act(async () => { + w.latest.handleAgentEventRef.current({ type: "goal_updated", goal: nextGoal, state: nextState }); + release(); + await sleep(30); + lastEs()?.open(); + await command; + }); + assert.deepEqual(w.latest.goalState, nextState); + assert.deepEqual( + world.calls.filter((call) => call.body?.type === "prompt").map((call) => call.body.message), + status === "active" ? ["ship the export"] : [], + "only the still-active created goal may start its objective", + ); + }); +} + test("GOAL get_state and goal_updated both feed the banner", async () => { resetWorld(); primeSession("goal-restore", [userMsg("u0", "loaded question")]); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 5fc755303..0309c9bd9 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -511,13 +511,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // requested and applies only if no newer frame/response arrived; an older // updatedAt never overwrites a newer goal. const goalSeqRef = useRef(0); + // Event handlers can run before React commits their state. Command + // continuations must still observe a pause/drop received in the same batch. + const goalStateRef = useRef(null); const applyGoalSnapshot = useCallback((seq: number, value: GoalModeState | null) => { - if (seq !== goalSeqRef.current) return; - setGoalState((prev) => (isStaleGoalState(prev, value) ? prev : value)); + if (seq !== goalSeqRef.current || isStaleGoalState(goalStateRef.current, value)) return; + goalStateRef.current = value; + setGoalState(value); }, []); const publishGoalState = useCallback((value: GoalModeState | null) => { goalSeqRef.current += 1; - setGoalState((prev) => (isStaleGoalState(prev, value) ? prev : value)); + if (isStaleGoalState(goalStateRef.current, value)) return; + goalStateRef.current = value; + setGoalState(value); }, []); const [subagents, setSubagents] = useState([]); const [subagentEvents, setSubagentEvents] = useState>({}); @@ -828,6 +834,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // conversation, not a switch: keep the goal that was just created. if (session?.id && session.id === sessionIdRef.current) return; goalSeqRef.current += 1; + goalStateRef.current = null; setGoalState(null); }, [session?.id]); @@ -4185,6 +4192,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (!sid) return complete({ handled: true, error: translate("agentSession.noActiveSession") }); const objective = args.trim(); if (!objective) return complete({ handled: true, error: translate("agentSession.goalUsage") }); + const goalSeq = goalSeqRef.current; const result = await sendAgentCommand(sid, { type: "goal", op: "create", @@ -4195,7 +4203,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (!parsed?.goal) { return complete({ handled: true, error: translate("agentSession.goalCreateFailed") }); } - publishGoalState(parsed.state); + // The create echo may precede HTTP, but a later pause/drop/replace + // must win over the reply and cancel its automatic first prompt. + if (goalSeq === goalSeqRef.current) publishGoalState(parsed.state); + const currentGoal = goalStateRef.current?.goal; + if (currentGoal?.id !== parsed.goal.id || currentGoal.status !== "active") return { handled: true }; // A goal created on the empty new-chat screen must adopt the real // session so a reload opens it instead of a fresh composer. promoteNewSession(); From fa7323003a579c424087e1fb6e77c267b88f0be8 Mon Sep 17 00:00:00 2001 From: killcerr Date: Thu, 5 Nov 2026 23:12:12 +0800 Subject: [PATCH 6/9] fix(chat): carry slash commands and goals onto the Bun host runtime Rebase repairs for the new server/daemon architecture: - keep the upload attachment kind alongside images and text files in the client-only command refusal and the expanded queue path; - restore the uploads-aware send tracking in the queued prompt expansion; - drop the now-dead session-stats panel hook and handle method: `/session` is omp's command, so the client callback had no caller left; - load Testing Library after the jsdom setup and drop jiti from the new test files, as the Bun test migration does everywhere else. --- components/ChatInput-banners.test.mjs | 9 +++++---- components/ChatInput.tsx | 4 ++-- lib/goal-state.test.mjs | 4 +--- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/components/ChatInput-banners.test.mjs b/components/ChatInput-banners.test.mjs index 4a4cadbf0..9ce03bc9c 100644 --- a/components/ChatInput-banners.test.mjs +++ b/components/ChatInput-banners.test.mjs @@ -2,11 +2,12 @@ import "../tests/setup-dom.mjs"; import assert from "node:assert/strict"; import test, { afterEach } from "node:test"; import React from "react"; -import { act, cleanup, fireEvent, render, screen } from "@testing-library/react/pure.js"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tsconfigPaths: true }); -const { ComposerModeStatus } = await jiti.import("./ChatInput-banners.tsx"); +// Imported after the jsdom globals exist: Testing Library binds its queries at +// module evaluation, and a static import can run before `setup-dom.mjs`. +const { act, cleanup, fireEvent, render, screen } = await import("@testing-library/react/pure.js"); + +const { ComposerModeStatus } = await import("./ChatInput-banners.tsx"); const goal = (overrides = {}) => ({ id: "g1", diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 62f5f9ba5..88463c536 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -279,7 +279,7 @@ export interface ChatInputHandle { insertIfEmpty: (text: string) => void; prependText: (text: string) => void; addFiles: (files: File[]) => void; - /** Retarget captured queue recoveries before a confirmed move can render. */ + /** Retarget pending sends and captured queue recoveries before a confirmed move can render. */ retargetPendingRecovery: (from: string, to: string) => void; } const COMPOSITION_END_ENTER_GRACE_MS = 100; @@ -1808,7 +1808,7 @@ export const ChatInput = memo(forwardRef(function ChatIn // side question) must not enter the prompt queue: omp would treat the // text as an ordinary message. Run them now, mid-run included. if (CLIENT_ONLY_COMMAND_NAMES[commandName] === true && !ompCommandNames.has(commandName)) { - if (attachedImagesRef.current.length || attachedTextFilesRef.current.length) { + if (attachedImagesRef.current.length || attachedTextFilesRef.current.length || attachedUploadsRef.current.length) { toast.error(t("chatInput.commandAttachmentsUnsupported")); return; } diff --git a/lib/goal-state.test.mjs b/lib/goal-state.test.mjs index f69ef8b19..2f883625c 100644 --- a/lib/goal-state.test.mjs +++ b/lib/goal-state.test.mjs @@ -1,8 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); const { formatGoalDuration, goalElapsedSeconds, @@ -11,7 +9,7 @@ const { readGoalCommandResponse, readGoalModeState, readGoalUpdatedEvent, -} = await jiti.import("./goal-state.ts"); +} = await import("./goal-state.ts"); const GOAL = { id: "g1", From 048d6c556a90200dae6d83dfb489bc52979be5a8 Mon Sep 17 00:00:00 2001 From: killcerr Date: Mon, 9 Nov 2026 11:20:05 +0800 Subject: [PATCH 7/9] fix(chat): hide a dropped goal and load the command roster before dispatch - A dropped goal is never visible. omp keeps the record in its state and answers `drop` with `{goal: null, state: null}`; either the event or the reply can arrive first and neither is repeated later, so `withoutDroppedGoal` maps it to "no goal" in both publishers. The raw record stays in `goalStateRef`, so staleness and the create fence still compare timestamps. Both orderings are tested through the real hook. - The command roster is authoritative for dispatch, not only for the palette: `handleBuiltinSlashCommand` fetches it once before the client switch when a session exists, so a pasted or dictated command cannot hit a client handler whose name an extension, skill or custom command owns. Concurrent `get_commands` requests share one promise. A brand-new chat keeps its first command's own runtime start (starting omp there would attach an observer stream beside the command's own); later dispatches see the roster. - Manual compaction start/end now go through the same generation, local and native-compaction refs as auto-compaction instead of clearing `isCompacting` directly, so a local compaction settling cannot release a native one. --- .../ChatInput.queue-attachments.test.mjs | 48 +++++--- components/ChatInput.tsx | 57 +++++++-- ...-29-native-slash-commands-and-goal-mode.md | 14 +++ hooks/useAgentSession.rpc.test.mjs | 42 ++++++- hooks/useAgentSession.ts | 112 +++++++++++------- lib/goal-state.test.mjs | 9 ++ lib/goal-state.ts | 11 ++ 7 files changed, 225 insertions(+), 68 deletions(-) diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index c441aaadd..0cc50c9b0 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -157,6 +157,40 @@ test("a stored Steer preference turns the primary button into Steer, which steer assertQueuedWithAttachments(calls[0], "look at this"); }); +test("a catalog-owned goal with attachments is forwarded once the catalog answers", async () => { + window.HTMLElement.prototype.scrollIntoView = () => {}; + const user = userEvent.setup(); + let release; + let loads = 0; + const catalog = new Promise((resolve) => { + release = () => resolve([{ name: "goal", source: "extension", description: "extension goal" }]); + }); + const builtins = []; + const { calls } = await renderWithAttachments({ + isStreaming: false, + slashCommands: [], + onBuiltinCommand: async (message) => { + builtins.push(message); + return { handled: false }; + }, + onLoadSlashCommands: () => { + loads += 1; + return catalog; + }, + }); + await user.type(screen.getByRole("textbox"), "/goal ship it"); + await user.keyboard("{Enter}"); + await waitFor(() => assert.ok(loads >= 1), { timeout: 2000 }); + assert.equal(calls.length, 0, "nothing is dispatched before the catalog answers"); + await act(async () => release()); + await waitFor(() => assert.equal(calls.length, 1)); + delete window.HTMLElement.prototype.scrollIntoView; + assert.equal(calls[0].name, "onSend", "omp owns the name once the catalog reports it"); + assert.ok(calls[0].message.startsWith("/goal ship it"), "the command line leads the forwarded prompt"); + assert.match(calls[0].message, /Attached file: notes\.txt/, "attachments ride along"); + assert.deepEqual(builtins, [], "with attachments the command goes straight to the prompt"); +}); + test("a queued web slash command is expanded and keeps the attachments", async () => { const { expandWebSlashCommand } = await import("@/lib/web-slash-commands"); window.HTMLElement.prototype.scrollIntoView = () => {}; @@ -260,20 +294,6 @@ test("a queued message stays in the composer until the outbox has it, and stays assert.equal(getDraft(KEY)?.files.length, 1); }); -test("a refused follow-up goes back whole to its draft, ahead of what was typed meanwhile", async () => { - let refuse; - const calls = await renderRunningWithAttachments({ queued: new Promise((resolve) => { refuse = () => resolve(false); }) }); - fireEvent.click(screen.getByRole("button", { name: /queue/i })); - await waitFor(() => assert.equal(calls.length, 1)); - assert.equal(screen.getByRole("status").textContent, "Sending…", "the in-flight message shows until omp answers"); - fireEvent.change(screen.getByRole("textbox"), { target: { value: "typed meanwhile" } }); - await act(async () => { refuse(); }); - await waitFor(() => assert.equal(screen.queryByRole("status"), null, "the sending row goes once omp answered")); - await waitFor(() => assert.deepEqual(getDraft(KEY)?.images, [{ data: PNG, mimeType: "image/png" }])); - assert.equal(getDraft(KEY)?.value, `${calls[0].message}\n\ntyped meanwhile`, "the text, file contents included, comes back too"); - assert.equal(screen.getByRole("textbox").value, `${calls[0].message}\n\ntyped meanwhile`); -}); - test("a queued message is not cleared once stored if the composer changed meanwhile", async () => { let store; const calls = await renderRunningWithAttachments({ queued: new Promise((resolve) => { store = () => resolve(true); }) }); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 88463c536..4439baf52 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -430,6 +430,21 @@ export const ChatInput = memo(forwardRef(function ChatIn () => new Set((slashCommands ?? []).flatMap((command) => [command.name, ...(command.aliases ?? [])])), [slashCommands], ); + // The catalog decides who owns a slash command. A pasted or dictated command + // can reach dispatch before the palette ever opened, so fetch it once before + // routing instead of deciding on an empty roster. Concurrent sends share the + // request; the gate stops a second Enter from dispatching while it waits. + const catalogRequestRef = useRef> | null>(null); + const catalogGateRef = useRef(false); + const resolveCommandCatalog = useCallback((): Promise> => { + if (ompCommandNames.size > 0 || !onLoadSlashCommands) return Promise.resolve(ompCommandNames); + if (!catalogRequestRef.current) { + catalogRequestRef.current = Promise.resolve(onLoadSlashCommands()) + .then((commands) => new Set((commands ?? []).flatMap((command) => [command.name, ...(command.aliases ?? [])]))) + .catch(() => ompCommandNames); + } + return catalogRequestRef.current; + }, [ompCommandNames, onLoadSlashCommands]); const usageLimitLabel = usageLimit ? formatUsageLimitLabel(usageLimit, t) : undefined; @@ -1251,9 +1266,9 @@ export const ChatInput = memo(forwardRef(function ChatIn /** `/btw` asks a side question beside any run: never a prompt, never * queued. Attachments cannot ride along, so refuse and keep the draft * rather than drop them. False when `msg` is not `/btw`. */ - const sendSideQuestion = useCallback((msg: string, overrideText?: string): boolean => { + const sendSideQuestion = useCallback((msg: string, overrideText?: string, catalog: Set = ompCommandNames): boolean => { // A catalog command named `btw` wins over the client side-question panel. - if (!/^\/btw(\s|$)/.test(msg) || !onBuiltinCommand || ompCommandNames.has("btw")) return false; + if (!/^\/btw(\s|$)/.test(msg) || !onBuiltinCommand || catalog.has("btw")) return false; if (attachedImagesRef.current.length || attachedTextFilesRef.current.length || attachedUploadsRef.current.length) { toast.error(t("btw.attachmentsUnsupported")); return true; @@ -1270,11 +1285,21 @@ export const ChatInput = memo(forwardRef(function ChatIn const shellCommand = msg.startsWith("!") && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length; if (submissionBlockedRef.current || holdingRef.current || (isStreaming && !shellCommand)) return; onAudioUnlock?.(); - if (sendSideQuestion(msg, overrideText)) return; + let catalog = ompCommandNames; + if (msg.startsWith("/") && ompCommandNames.size === 0 && onLoadSlashCommands) { + if (catalogGateRef.current) return; + catalogGateRef.current = true; + try { + catalog = await resolveCommandCatalog(); + } finally { + catalogGateRef.current = false; + } + } + if (sendSideQuestion(msg, overrideText, catalog)) return; if (rejectsPendingUploads()) return; if (msg.startsWith("/") && (attachedImagesRef.current.length || attachedTextFilesRef.current.length || attachedUploadsRef.current.length)) { const commandName = msg.slice(1).split(/\s+/)[0]; - if (CLIENT_ONLY_COMMAND_NAMES[commandName] === true && !ompCommandNames.has(commandName)) { + if (CLIENT_ONLY_COMMAND_NAMES[commandName] === true && !catalog.has(commandName)) { toast.error(t("chatInput.commandAttachmentsUnsupported")); return; } @@ -1282,7 +1307,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const composedMessage = composeMessageWithTextAttachments(msg, attachedTextFilesRef.current); if (!attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length && msg.startsWith("/") && onBuiltinCommand) { const commandName = msg.slice(1).split(/\s+/)[0]; - const expansion = ompCommandNames.has(commandName) + const expansion = catalog.has(commandName) ? { kind: "not-web" as const } : expandWebSlashCommand(msg); if (expansion.kind === "expand" && rejectsOversizedPrompt(expansion.prompt, attachedImagesRef.current)) return; @@ -1324,7 +1349,7 @@ export const ChatInput = memo(forwardRef(function ChatIn if (key) recoverDraft(key, recovery); throw error; } - }, [value, isStreaming, onBuiltinCommand, onSend, outbox, clearInput, clearOnceStored, onAudioUnlock, ompCommandNames, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion, t]); + }, [value, isStreaming, onBuiltinCommand, onSend, outbox, clearInput, clearOnceStored, onAudioUnlock, ompCommandNames, resolveCommandCatalog, onLoadSlashCommands, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion, t]); const { isRecording, isPaused, @@ -1762,12 +1787,22 @@ export const ChatInput = memo(forwardRef(function ChatIn }); }, [slashMatch, value, setValue]); - const sendQueued = useCallback((mode: "steer" | "followup", overrideText?: string) => { + const sendQueued = useCallback(async (mode: "steer" | "followup", overrideText?: string) => { if (submissionBlockedRef.current || holdingRef.current) return; const raw = overrideText ?? value; const msg = raw.trim(); if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) return; - if (sendSideQuestion(msg, overrideText)) return; + let catalog = ompCommandNames; + if (msg.startsWith("/") && ompCommandNames.size === 0 && onLoadSlashCommands) { + if (catalogGateRef.current) return; + catalogGateRef.current = true; + try { + catalog = await resolveCommandCatalog(); + } finally { + catalogGateRef.current = false; + } + } + if (sendSideQuestion(msg, overrideText, catalog)) return; if (rejectsPendingUploads()) return; if (msg.startsWith("!") && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) { void handleSend(overrideText); @@ -1807,7 +1842,7 @@ export const ChatInput = memo(forwardRef(function ChatIn // Client-dispatched commands (/goal uses the native goal RPC, /btw is a // side question) must not enter the prompt queue: omp would treat the // text as an ordinary message. Run them now, mid-run included. - if (CLIENT_ONLY_COMMAND_NAMES[commandName] === true && !ompCommandNames.has(commandName)) { + if (CLIENT_ONLY_COMMAND_NAMES[commandName] === true && !catalog.has(commandName)) { if (attachedImagesRef.current.length || attachedTextFilesRef.current.length || attachedUploadsRef.current.length) { toast.error(t("chatInput.commandAttachmentsUnsupported")); return; @@ -1819,7 +1854,7 @@ export const ChatInput = memo(forwardRef(function ChatIn // when queued. A name omp's catalog owns is never expanded: omp runs // the original command line (extension/custom/skill/builtin) on // delivery. - const expansion = ompCommandNames.has(commandName) + const expansion = catalog.has(commandName) ? { kind: "not-web" as const } : expandWebSlashCommand(msg); if (expansion.kind === "expand") { @@ -1839,7 +1874,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const composedMessage = composeMessageWithTextAttachments(msg, files); if (rejectsOversizedPrompt(composedMessage, attachedImagesRef.current)) return; hold(composedMessage); - }, [value, handleSend, onSteer, onFollowUp, clearOnceStored, onAudioUnlock, t, ompCommandNames, onBuiltinCommand, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); + }, [value, handleSend, onSteer, onFollowUp, clearOnceStored, onAudioUnlock, t, ompCommandNames, resolveCommandCatalog, onLoadSlashCommands, onBuiltinCommand, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); // A typed message or attachment during a run is a queued follow-up — and so // is a dictation in progress: the primary button must take the same state it // would have if the composer already held text. Keep Stop as the action diff --git a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md index 42bef7df8..096c4069d 100644 --- a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md +++ b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md @@ -124,6 +124,14 @@ current turn continues, and omp decides continuation at the next terminal `agent_end`. A client-owned command with attachments is refused before any of these steps, so a queued `/goal` cannot clear an attached file. +The catalog is authoritative for the dispatcher too, not only for the palette: +`handleBuiltinSlashCommand` loads the roster once before the switch when a +session exists, so a pasted or dictated command cannot reach a client handler +whose name an extension, skill or custom command also owns. A brand-new chat has +no roster before omp starts; starting it there would attach an observer stream +beside the command's own, so its first command creates the runtime and later +dispatches see the roster (typing `/` loads it through the palette as well). + An asynchronous client command clears only its unchanged originating draft on success. Dictation's explicit text override does not bypass that check: newer typing, changed attachments and pending attachment reads are retained. Text @@ -225,6 +233,12 @@ A present-but-malformed goal is rejected rather than treated as "no goal". published only if no newer goal event/response arrived; its automatic first prompt requires that the same goal is still active. The normal active create echo does not prevent the initial prompt. +- A `dropped` goal is never visible: omp keeps the record in its state and + answers the `drop` command with `{goal: null, state: null}`, but either the + event or that reply may arrive first and no later event repeats the clear. + `withoutDroppedGoal` maps it to "no goal" in `publishGoalState` and + `applyGoalSnapshot` (the raw record stays in `goalStateRef`, so staleness and + the create fence still compare real timestamps). Both orderings are tested. Session switching: diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 22cc5418e..83d4ca8fe 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1273,7 +1273,8 @@ for (const status of ["active", "paused", "dropped", "cleared", "replaced"]) { lastEs()?.open(); await command; }); - assert.deepEqual(w.latest.goalState, nextState); + // A dropped goal has nothing left to show, so the banner is already gone. + assert.deepEqual(w.latest.goalState, status === "dropped" ? null : nextState); assert.deepEqual( world.calls.filter((call) => call.body?.type === "prompt").map((call) => call.body.message), status === "active" ? ["ship the export"] : [], @@ -1297,6 +1298,43 @@ test("GOAL get_state and goal_updated both feed the banner", async () => { assert.equal(w.latest.goalState, null, "a cleared goal hides the banner"); }); +for (const order of ["event then reply", "reply then event"]) { + test(`GOAL a dropped goal hides the banner when the ${order}`, async () => { + resetWorld(); + const sid = `goal-drop-${order.replaceAll(" ", "-")}`; + primeSession(sid, [userMsg("u0", "loaded question")]); + world.agents.set(sid, { running: false, state: { goal: goalState() } }); + const w = await mountSession(sid); + assert.equal(w.latest.goalState?.goal?.status, "active"); + + const dropped = { ...GOAL, status: "dropped", updatedAt: 2000 }; + const emitDrop = () => w.latest.handleAgentEventRef.current({ type: "goal_updated", goal: dropped, state: goalState(dropped) }); + let release; + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "goal", + produce: () => new Promise((resolve) => { + release = () => resolve({ value: { success: true, data: { goal: null, state: null } } }); + }), + }); + let action; + await act(async () => { + action = w.latest.handleGoalAction("drop"); + await sleep(20); + }); + + if (order === "event then reply") { + await act(async () => emitDrop()); + assert.equal(w.latest.goalState, null, "the drop event alone hides the banner"); + await act(async () => { release(); await action; }); + } else { + await act(async () => { release(); await action; }); + assert.equal(w.latest.goalState, null, "the null reply alone hides the banner"); + await act(async () => emitDrop()); + } + assert.equal(w.latest.goalState, null, "no later event brings the dropped goal back"); + }); +} + test("GOAL a failed create reports omp's error and keeps the existing goal", async () => { resetWorld(); primeSession("goal-conflict", [userMsg("u0", "loaded question")]); @@ -2548,7 +2586,7 @@ test("a refused compact command cannot unlock compaction attached from another t }); await act(async () => { const result = await w.latest.handleBuiltinSlashCommand("/compact"); - assert.ok(result.error, "a second compaction is refused"); + assert.equal(result.handled, false, "omp owns /compact; the web forwards it instead of compacting locally"); }); assert.equal(w.latest.isCompacting, true, "the rejected command does not own the attached compaction"); await act(async () => { await w.latest.handleCompact(); }); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 0309c9bd9..eab62ac6e 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -39,7 +39,7 @@ import { toast } from "@/components/ui/toast"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import { validateOutgoingPrompt } from "@/lib/image-attachments"; import { type ActivePlan } from "@/lib/web-mode-state"; -import { isStaleGoalState, readGoalCommandResponse, readGoalUpdatedEvent } from "@/lib/goal-state"; +import { isStaleGoalState, readGoalCommandResponse, readGoalUpdatedEvent, withoutDroppedGoal } from "@/lib/goal-state"; import type { GoalCommandResponse, GoalModeState, HostToolDefinition, HostUriSchemeDefinition, RpcAskDialogAnswer, RpcAvailableSlashCommand, SessionStatsInfo, SlowModeScope, TodoPhase, UsageLimitState } from "@/lib/pi-types"; import { isRecord } from "@/lib/type-guards"; import { subscribeSessionsChanged } from "@/lib/session-change-bus"; @@ -426,6 +426,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // but the unknown-command warning must not flag them (#167). Ref-only: it is // consulted at send time and must never re-render the composer. const knownSlashCommandNamesRef = useRef([]); + /** True once a `get_commands` reply actually arrived: until then an empty + * roster means "not asked yet", not "omp owns nothing". */ + const slashRosterLoadedRef = useRef(false); + const slashCommandsInFlightRef = useRef | null>(null); const warnedSlashCommandsRef = useRef(new Set()); const [noticeState, dispatchNotice] = useReducer(noticeReducer, { visible: [], pending: [] }); const [sessionStatsOverride, setSessionStatsOverride] = useState(null); @@ -517,13 +521,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const applyGoalSnapshot = useCallback((seq: number, value: GoalModeState | null) => { if (seq !== goalSeqRef.current || isStaleGoalState(goalStateRef.current, value)) return; goalStateRef.current = value; - setGoalState(value); + setGoalState(withoutDroppedGoal(value)); }, []); const publishGoalState = useCallback((value: GoalModeState | null) => { goalSeqRef.current += 1; if (isStaleGoalState(goalStateRef.current, value)) return; goalStateRef.current = value; - setGoalState(value); + setGoalState(withoutDroppedGoal(value)); }, []); const [subagents, setSubagents] = useState([]); const [subagentEvents, setSubagentEvents] = useState>({}); @@ -591,6 +595,20 @@ export function useAgentSession(opts: UseAgentSessionOptions) { compactionGenRef.current += 1; setCompacting(localCompactionsRef.current > 0 || autoCompactingRef.current); }, [setCompacting]); + // A compaction omp started and this tab does not own (auto-compaction, or a + // manual one from another tab, the TUI, or a forwarded `/compact`). It holds + // the control across a local compaction settling, and its end is the only + // thing that releases it. + const beginNativeCompaction = useCallback(() => { + compactionGenRef.current += 1; + autoCompactingRef.current = true; + setCompacting(true); + }, [setCompacting]); + const endNativeCompaction = useCallback(() => { + compactionGenRef.current += 1; + autoCompactingRef.current = false; + if (localCompactionsRef.current === 0) setCompacting(false); + }, [setCompacting]); // Set while an interrupt-and-reply (abort_and_prompt) is in flight: the // aborted turn's terminal agent_end must not tear down the new run that is // starting. Cleared on the new run's agent_start (or the intercept itself). @@ -1333,31 +1351,41 @@ export function useAgentSession(opts: UseAgentSessionOptions) { }, [ensureNewSession]); const loadSlashCommands = useCallback(async () => { - const sid = sessionIdRef.current ?? await ensureNewSession(); - if (!sid) { - setSlashCommands([]); - knownSlashCommandNamesRef.current = []; - return [] as SlashCommandInfo[]; - } - setSlashCommandsLoading(true); + if (slashCommandsInFlightRef.current) return slashCommandsInFlightRef.current; + const request = (async () => { + const sid = sessionIdRef.current ?? await ensureNewSession(); + if (!sid) { + setSlashCommands([]); + knownSlashCommandNamesRef.current = []; + return [] as SlashCommandInfo[]; + } + setSlashCommandsLoading(true); + try { + const data = await sendAgentCommand(sid, { type: "get_commands" }); + const available = Array.isArray(data?.commands) ? data.commands : []; + // Keep every source, builtins included: omp runs them through the prompt + // path and they must not be reported as unknown (#167). + // A reply carrying no list is not evidence that nothing is known, so it + // must not erase a roster an earlier reply did supply. + if (available.length > 0) knownSlashCommandNamesRef.current = slashCommandRosterNames(available); + slashRosterLoadedRef.current = true; + const commands = available.map(toSlashCommandInfo); + setSlashCommands(commands); + return commands; + } catch (e) { + console.error("Failed to load slash commands:", e); + setSlashCommands([]); + knownSlashCommandNamesRef.current = []; + return [] as SlashCommandInfo[]; + } finally { + setSlashCommandsLoading(false); + } + })(); + slashCommandsInFlightRef.current = request; try { - const data = await sendAgentCommand(sid, { type: "get_commands" }); - const available = Array.isArray(data?.commands) ? data.commands : []; - // Keep every source, builtins included: omp runs them through the prompt - // path and they must not be reported as unknown (#167). - // A reply carrying no list is not evidence that nothing is known, so it - // must not erase a roster an earlier reply did supply. - if (available.length > 0) knownSlashCommandNamesRef.current = slashCommandRosterNames(available); - const commands = available.map(toSlashCommandInfo); - setSlashCommands(commands); - return commands; - } catch (e) { - console.error("Failed to load slash commands:", e); - setSlashCommands([]); - knownSlashCommandNamesRef.current = []; - return [] as SlashCommandInfo[]; + return await request; } finally { - setSlashCommandsLoading(false); + slashCommandsInFlightRef.current = null; } }, [ensureNewSession]); @@ -2165,7 +2193,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { void reconcileAgentState(sid); } } - }, [applyNativeCompacting, applyQueueStateSnapshot, applySkillDiagnosticsSnapshot, finishPromptWithoutStream, refreshSubagentRoster]); + }, [applyGoalSnapshot, applyNativeCompacting, applyQueueStateSnapshot, applySkillDiagnosticsSnapshot, finishPromptWithoutStream, refreshSubagentRoster]); // Recovery net for missed SSE events: while a prompt or compaction runs, verify // against the server periodically and whenever the tab returns to the @@ -2678,17 +2706,15 @@ export function useAgentSession(opts: UseAgentSessionOptions) { break; } case "manual_compaction_start": { - // `/compact` now runs through omp's own builtin; the RPC `compact` - // response only covers the web button. Keep both paths visible. - isCompactingRef.current = true; - setIsCompacting(true); + // `/compact` runs through omp's builtin; this event also covers a + // compaction another tab, the TUI or a forwarded command started. + beginNativeCompaction(); setCompactError(null); setCompactResult(null); break; } case "manual_compaction_end": { - isCompactingRef.current = false; - setIsCompacting(false); + endNativeCompaction(); const compacted = readCompactResult(event.result, typeof event.mode === "string" ? event.mode : "manual"); if (compacted) setCompactResult(compacted); else if (typeof event.errorMessage === "string" && event.errorMessage) setCompactError(event.errorMessage); @@ -2879,16 +2905,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setRetryInfo(null); break; case "auto_compaction_start": - compactionGenRef.current += 1; - autoCompactingRef.current = true; - setCompacting(true); + beginNativeCompaction(); setCompactError(null); setCompactResult(null); break; case "auto_compaction_end": - compactionGenRef.current += 1; - autoCompactingRef.current = false; - if (localCompactionsRef.current === 0) setCompacting(false); + endNativeCompaction(); if (event.errorMessage) { setCompactError(event.errorMessage as string); setCompactResult(null); @@ -3054,7 +3076,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { handleExtensionUiRequest(event as unknown as IncomingExtensionUiRequest); break; } - }, [addNotice, addUnconfirmedRunErrorNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, refreshSubagentRoster, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, publishGoalState, beginAuthoritativeModelSync, setCompacting, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot]); + }, [addNotice, addUnconfirmedRunErrorNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, refreshSubagentRoster, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, publishGoalState, beginAuthoritativeModelSync, beginNativeCompaction, endNativeCompaction, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot]); handleAgentEventRef.current = handleAgentEvent; syncActionsRef.current = { metadata: (context, version, hasLive = liveModelMeta !== null || currentModelOverride !== null) => { @@ -4140,7 +4162,15 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const ensureRuntime = async () => sessionIdRef.current ?? await ensureNewSession(); // The catalog wins over every client handler, including the client-only // names: an extension/skill command called `goal`, `btw`, `reload`, - // `name`, or `copy` must not be shadowed. + // `name`, or `copy` must not be shadowed. A pasted or dictated command can + // reach dispatch before autocomplete ever fetched the roster, so ask once + // here rather than deciding on an empty list. + // A fresh chat has no roster until omp starts, and starting it here would + // attach an observer stream beside the command's own; its first command + // creates the runtime, and the roster is known from the next dispatch on + // (typing "/" already loads it through the palette). + if (!slashRosterLoadedRef.current && sessionIdRef.current) await loadSlashCommands(); + if (!hookAliveRef.current) return { handled: true }; if (knownSlashCommandNamesRef.current.includes(commandName)) return { handled: false }; switch (commandName) { diff --git a/lib/goal-state.test.mjs b/lib/goal-state.test.mjs index 2f883625c..fb10018fd 100644 --- a/lib/goal-state.test.mjs +++ b/lib/goal-state.test.mjs @@ -9,6 +9,7 @@ const { readGoalCommandResponse, readGoalModeState, readGoalUpdatedEvent, + withoutDroppedGoal, } = await import("./goal-state.ts"); const GOAL = { @@ -94,3 +95,11 @@ test("only active and paused goals are controllable; older snapshots lose", () = { enabled: true, mode: "active", goal: { ...GOAL, updatedAt: 3000 } }, ), false); }); + +test("a dropped goal is never visible, and a null clear stays null", () => { + const dropped = { enabled: false, mode: "active", goal: { ...GOAL, status: "dropped", updatedAt: 2000 } }; + assert.equal(withoutDroppedGoal(dropped), null, "omp keeps the dropped record; the banner must not"); + assert.equal(withoutDroppedGoal(null), null); + assert.equal(withoutDroppedGoal({ enabled: true, mode: "active", goal: GOAL })?.goal?.id, "g1"); + assert.equal(withoutDroppedGoal({ enabled: false, mode: "active", goal: { ...GOAL, status: "completed" } })?.goal?.status, "completed"); +}); diff --git a/lib/goal-state.ts b/lib/goal-state.ts index 24d9fe14f..839b9b4f3 100644 --- a/lib/goal-state.ts +++ b/lib/goal-state.ts @@ -87,6 +87,17 @@ export function isGoalControllable(state: GoalModeState | null | undefined): boo return state?.goal?.status === "active" || state?.goal?.status === "paused"; } +/** + * omp keeps a dropped goal in the state it reports, but nothing is left to show + * or do with it. Hide it the moment the drop arrives: omp then answers the + * `drop` command with `{ goal: null, state: null }`, and no later event repeats + * that clear, so waiting for the reply (or for the event, when the order is + * reversed) would leave a "Dropped" banner until the next state snapshot. + */ +export function withoutDroppedGoal(state: GoalModeState | null | undefined): GoalModeState | null { + return state?.goal?.status === "dropped" ? null : (state ?? null); +} + /** omp reports `timeUsedSeconds`; while active, extrapolate from `updatedAt` for a live display. */ export function goalElapsedSeconds(state: GoalModeState | null | undefined, now = Date.now()): number { const goal = state?.goal; From dc9c71deb5cb23c079e521e82dff6e28988ebe29 Mon Sep 17 00:00:00 2001 From: killcerr Date: Mon, 9 Nov 2026 12:17:23 +0800 Subject: [PATCH 8/9] fix(chat): harden native command dispatch and compaction --- CHANGELOG.md | 2 + .../ChatInput.queue-attachments.test.mjs | 94 +++++++++ components/ChatInput.tsx | 51 +++-- ...-29-native-slash-commands-and-goal-mode.md | 14 +- hooks/useAgentSession.rpc.test.mjs | 193 ++++++++++++++++++ hooks/useAgentSession.ts | 47 +++-- lib/goal-state.test.mjs | 3 + lib/goal-state.ts | 3 +- lib/hosts/daemon-channels.test.mjs | 8 + lib/hosts/daemon-channels.ts | 4 +- lib/hosts/link-protocol.ts | 6 + lib/i18n/locales/en.json | 1 + lib/i18n/locales/ja.json | 1 + lib/i18n/locales/zh-CN.json | 1 + lib/rpc-manager.test.mjs | 17 ++ lib/rpc-manager.ts | 12 +- 16 files changed, 410 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39c109526..de9ebb2d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,8 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements - **Anthropic stays visible when usage limits are unavailable.** The Provider Usage panel keeps accounts that omp reports without usage data and marks them as unavailable rather than unlimited. +- **Slash-command dispatch keeps the command catalog authoritative without losing drafts or attachments.** A late catalog snapshot can no longer overwrite a newer command update, failed discovery leaves the current roster and draft intact for retry, and typing while the first lookup is pending is never cleared by the older command. Web prompt commands expand before text, image and uploaded-file attachments are sent, and remain visible in the palette while a run is active. +- **Goal and manual-compaction state stay fenced and synchronized across clients.** Goal mutations now respect a history edit held through a shared host daemon, malformed goal snapshots cannot hide a valid banner, and native `/compact` events update the server's live snapshot and session-list caches as well as the initiating tab. - **A delayed archive restore cannot overwrite newer archived work.** Restore now pins the compressed source generation it staged and verifies an atomically captured archive entry before moving artifacts. If another server restored, updated and re-archived that session meanwhile, the stale restore is refused and the newer transcript and artifacts remain available. Captured archives remain discoverable by session ID before publication and after an interrupted restore, so held messages are not falsely failed as belonging to a missing session; orphaned restore claims report their manual-recovery path. - **In-progress archive captures are evidence, not restore targets.** Captures have unique keys and disabled Restore controls, so a capture and a newer archive cannot select the wrong session. Archive discovery rechecks names and source generations after reading to avoid missing a capture during concurrent replacement; a capture encountered while pinning still reports its restore-claim recovery path. - **Unreadable archive directories no longer look empty.** Access and disk I/O errors retain affected outbox messages instead of proving their session absent. A corrupt or unreadable local archive is reported as one unavailable host in the archive browser, without hiding healthy linked hosts. diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 0cc50c9b0..5a25b7f9d 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -39,6 +39,7 @@ function override(target, key, replacement) { beforeEach(() => { window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} }); + window.HTMLElement.prototype.scrollIntoView = () => {}; globalThis.FileReader = TestFileReader; URL.createObjectURL ??= () => "blob:test"; URL.revokeObjectURL ??= () => {}; @@ -50,6 +51,7 @@ afterEach(() => { clearDraft(KEY); localStorage.clear(); delete window.matchMedia; + delete window.HTMLElement.prototype.scrollIntoView; globalThis.FileReader = previousFileReader; while (overrides.length) { const { target, key, original } = overrides.pop(); @@ -191,6 +193,88 @@ test("a catalog-owned goal with attachments is forwarded once the catalog answer assert.deepEqual(builtins, [], "with attachments the command goes straight to the prompt"); }); +test("a delayed catalog dispatch never clears text typed after the original command", async () => { + const user = userEvent.setup(); + let release; + const catalog = new Promise((resolve) => { release = resolve; }); + const builtins = []; + await renderWithAttachments({ + attachments: false, + isStreaming: false, + slashCommands: [], + onLoadSlashCommands: () => catalog, + onBuiltinCommand: async (message) => { + builtins.push(message); + return { handled: true }; + }, + }); + const textbox = screen.getByRole("textbox"); + await user.type(textbox, "/goal first"); + await user.keyboard("{Enter}"); + await user.clear(textbox); + await user.type(textbox, "newer draft"); + await act(async () => release([])); + await waitFor(() => assert.deepEqual(builtins, ["/goal first"])); + assert.equal(textbox.value, "newer draft"); + assert.equal(getDraft(KEY)?.value, "newer draft"); +}); + +test("a failed catalog lookup retains the command and retries instead of guessing ownership", async () => { + const user = userEvent.setup(); + let attempts = 0; + let failed = false; + let rejectFirst; + const first = new Promise((_, reject) => { rejectFirst = reject; }); + const builtins = []; + await renderWithAttachments({ + attachments: false, + isStreaming: false, + slashCommands: [], + onLoadSlashCommands: () => { + attempts += 1; + return failed ? [] : first; + }, + onBuiltinCommand: async (message) => { + builtins.push(message); + return { handled: true }; + }, + }); + const textbox = screen.getByRole("textbox"); + await user.type(textbox, "/goal retry"); + await user.keyboard("{Enter}"); + await waitFor(() => assert.ok(attempts >= 1)); + await act(async () => { + failed = true; + rejectFirst(new Error("catalog offline")); + await Promise.resolve(); + }); + assert.equal(textbox.value, "/goal retry"); + assert.deepEqual(builtins, []); + + await user.keyboard("{Enter}"); + await waitFor(() => assert.deepEqual(builtins, ["/goal retry"])); + assert.ok(attempts >= 2); +}); + +test("an idle web slash command expands before its attachments are composed", async () => { + const { expandWebSlashCommand } = await import("@/lib/web-slash-commands"); + const user = userEvent.setup(); + const { calls } = await renderWithAttachments({ + isStreaming: false, + onBuiltinCommand: async (message, sendPrompt) => { + const expansion = expandWebSlashCommand(message); + assert.equal(expansion.kind, "expand"); + const result = await sendPrompt(expansion.prompt); + return { handled: true, retainInput: result.status !== "accepted" }; + }, + }); + await user.type(screen.getByRole("textbox"), "/plan ship it"); + await user.keyboard("{Enter}"); + await waitFor(() => assert.equal(calls.length, 1)); + assert.equal(calls[0].name, "onSend"); + assertQueuedWithAttachments(calls[0], expandWebSlashCommand("/plan ship it").prompt); +}); + test("a queued web slash command is expanded and keeps the attachments", async () => { const { expandWebSlashCommand } = await import("@/lib/web-slash-commands"); window.HTMLElement.prototype.scrollIntoView = () => {}; @@ -204,6 +288,16 @@ test("a queued web slash command is expanded and keeps the attachments", async ( assertQueuedWithAttachments(calls[0], expandWebSlashCommand("/plan ship it").prompt); }); +test("streaming hides client-only commands but keeps queueable web commands in the palette", async () => { + window.HTMLElement.prototype.scrollIntoView = () => {}; + const user = userEvent.setup(); + await renderWithAttachments({ attachments: false, isStreaming: true, slashCommands: [] }); + await user.type(screen.getByRole("textbox"), "/"); + await waitFor(() => assert.ok(screen.getByRole("option", { name: /\/plan\b/i }))); + assert.equal(screen.queryByRole("option", { name: /\/goal\b/i }), null); + delete window.HTMLElement.prototype.scrollIntoView; +}); + test("a queued /goal runs the native goal RPC instead of entering the prompt queue", async () => { window.HTMLElement.prototype.scrollIntoView = () => {}; const user = userEvent.setup(); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 4439baf52..0d1add050 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -248,7 +248,10 @@ interface Props { slashCommands?: SlashCommandInfo[]; slashCommandsLoading?: boolean; onLoadSlashCommands?: () => Promise | SlashCommandInfo[]; - onBuiltinCommand?: (message: string) => Promise; + onBuiltinCommand?: ( + message: string, + sendPrompt?: (message: string) => Promise, + ) => Promise; onAudioUnlock?: () => void; draftKey?: string; /** Owning host for file uploads and the @ file index (this machine when absent). */ @@ -439,9 +442,13 @@ export const ChatInput = memo(forwardRef(function ChatIn const resolveCommandCatalog = useCallback((): Promise> => { if (ompCommandNames.size > 0 || !onLoadSlashCommands) return Promise.resolve(ompCommandNames); if (!catalogRequestRef.current) { - catalogRequestRef.current = Promise.resolve(onLoadSlashCommands()) - .then((commands) => new Set((commands ?? []).flatMap((command) => [command.name, ...(command.aliases ?? [])]))) - .catch(() => ompCommandNames); + const request = Promise.resolve() + .then(() => onLoadSlashCommands()) + .then((commands) => new Set((commands ?? []).flatMap((command) => [command.name, ...(command.aliases ?? [])]))); + catalogRequestRef.current = request; + void request.finally(() => { + if (catalogRequestRef.current === request) catalogRequestRef.current = null; + }).catch(() => {}); } return catalogRequestRef.current; }, [ompCommandNames, onLoadSlashCommands]); @@ -1242,12 +1249,18 @@ export const ChatInput = memo(forwardRef(function ChatIn const revision = attachmentRevisionRef.current; const images = attachedImagesRef.current; const files = attachedTextFilesRef.current; + const uploads = attachedUploadsRef.current; + const sendPrompt = (prompt: string) => onSend( + composeMessageWithTextAttachments(prompt, files), + images.length ? images : undefined, + ...uploadArgs(uploads), + ); // Dictation inserts overrideText in the same batch as dispatch. It still // must match on completion; an override does not own subsequent typing. const stored = clearOnceStored(sentValue); holdingRef.current = true; try { - const result = await onBuiltinCommand(msg); + const result = await onBuiltinCommand(msg, sendPrompt); if (!result.handled) return false; const unchanged = valueRef.current === sentValue && attachmentRevisionRef.current === revision @@ -1261,7 +1274,7 @@ export const ChatInput = memo(forwardRef(function ChatIn stored.release(); holdingRef.current = false; } - }, [onBuiltinCommand, clearOnceStored]); + }, [onBuiltinCommand, onSend, clearOnceStored]); /** `/btw` asks a side question beside any run: never a prompt, never * queued. Attachments cannot ride along, so refuse and keep the draft @@ -1291,11 +1304,14 @@ export const ChatInput = memo(forwardRef(function ChatIn catalogGateRef.current = true; try { catalog = await resolveCommandCatalog(); + } catch { + toast.error(t("chatInput.commandCatalogUnavailable")); + return; } finally { catalogGateRef.current = false; } } - if (sendSideQuestion(msg, overrideText, catalog)) return; + if (sendSideQuestion(msg, raw, catalog)) return; if (rejectsPendingUploads()) return; if (msg.startsWith("/") && (attachedImagesRef.current.length || attachedTextFilesRef.current.length || attachedUploadsRef.current.length)) { const commandName = msg.slice(1).split(/\s+/)[0]; @@ -1305,13 +1321,16 @@ export const ChatInput = memo(forwardRef(function ChatIn } } const composedMessage = composeMessageWithTextAttachments(msg, attachedTextFilesRef.current); - if (!attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length && msg.startsWith("/") && onBuiltinCommand) { + if (msg.startsWith("/") && onBuiltinCommand) { const commandName = msg.slice(1).split(/\s+/)[0]; const expansion = catalog.has(commandName) ? { kind: "not-web" as const } : expandWebSlashCommand(msg); - if (expansion.kind === "expand" && rejectsOversizedPrompt(expansion.prompt, attachedImagesRef.current)) return; - if (await runBuiltinCommand(msg, overrideText)) return; + if (expansion.kind === "expand") { + const expandedMessage = composeMessageWithTextAttachments(expansion.prompt, attachedTextFilesRef.current); + if (rejectsOversizedPrompt(expandedMessage, attachedImagesRef.current)) return; + } + if (!catalog.has(commandName) && await runBuiltinCommand(msg, raw)) return; } if (submissionBlockedRef.current) return; if (rejectsOversizedPrompt(composedMessage, attachedImagesRef.current)) return; @@ -1516,7 +1535,10 @@ export const ChatInput = memo(forwardRef(function ChatIn return modelCollator.compare(a.name, b.name); }); } - const commands = [...(isStreaming ? [] : builtinSlashCommands), ...externalSlashCommands]; + const commands = [ + ...builtinSlashCommands.filter((command) => !isStreaming || CLIENT_ONLY_COMMAND_NAMES[command.name] !== true), + ...externalSlashCommands, + ]; return [...commands] .filter((command) => { const name = command.name.toLowerCase(); @@ -1798,11 +1820,14 @@ export const ChatInput = memo(forwardRef(function ChatIn catalogGateRef.current = true; try { catalog = await resolveCommandCatalog(); + } catch { + toast.error(t("chatInput.commandCatalogUnavailable")); + return; } finally { catalogGateRef.current = false; } } - if (sendSideQuestion(msg, overrideText, catalog)) return; + if (sendSideQuestion(msg, raw, catalog)) return; if (rejectsPendingUploads()) return; if (msg.startsWith("!") && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) { void handleSend(overrideText); @@ -1847,7 +1872,7 @@ export const ChatInput = memo(forwardRef(function ChatIn toast.error(t("chatInput.commandAttachmentsUnsupported")); return; } - if (onBuiltinCommand) void runBuiltinCommand(msg, overrideText); + if (onBuiltinCommand) void runBuiltinCommand(msg, raw); return; } // Web-only prompt expansions (/plan, /fix, ...) must be expanded even diff --git a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md index 096c4069d..9c96f18a5 100644 --- a/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md +++ b/docs/specs/2026-10-29-native-slash-commands-and-goal-mode.md @@ -124,13 +124,13 @@ current turn continues, and omp decides continuation at the next terminal `agent_end`. A client-owned command with attachments is refused before any of these steps, so a queued `/goal` cannot clear an attached file. -The catalog is authoritative for the dispatcher too, not only for the palette: -`handleBuiltinSlashCommand` loads the roster once before the switch when a -session exists, so a pasted or dictated command cannot reach a client handler -whose name an extension, skill or custom command also owns. A brand-new chat has -no roster before omp starts; starting it there would attach an observer stream -beside the command's own, so its first command creates the runtime and later -dispatches see the roster (typing `/` loads it through the palette as well). +The catalog is authoritative for the dispatcher too, not only for the palette. +`ChatInput` resolves it before routing any slash command, including a pasted or +dictated command and the first command in a brand-new chat. In the latter case +the lookup creates the runtime and its observer before dispatch. This prevents a +client handler from shadowing an extension, skill or custom command with the +same name. `handleBuiltinSlashCommand` also loads a missing roster when a +session already exists, covering direct callers that bypass the composer. An asynchronous client command clears only its unchanged originating draft on success. Dictation's explicit text override does not bypass that check: newer diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 83d4ca8fe..c785b6e69 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1405,6 +1405,67 @@ test("GOAL an omp command named goal wins over the client dispatch", async () => assert.equal(world.calls.some((call) => call.body?.type === "goal"), false, "no native goal RPC"); }); +test("GOAL a late catalog snapshot cannot overwrite a newer ownership event", async () => { + resetWorld(); + primeSession("goal-catalog-race", [userMsg("u0", "loaded question")]); + const w = await mountSession("goal-catalog-race"); + let release; + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "get_commands", + produce: () => new Promise((resolve) => { + release = () => resolve({ + value: { success: true, data: { commands: [{ name: "todo", source: "builtin" }] } }, + }); + }), + }); + + let loading; + await act(async () => { + loading = w.latest.loadSlashCommands(); + await sleep(20); + }); + await act(async () => w.latest.handleAgentEventRef.current({ + type: "available_commands_update", + commands: [{ name: "goal", source: "extension", description: "new owner" }], + })); + await act(async () => { + release(); + await loading; + }); + + assert.deepEqual(w.latest.slashCommands.map((command) => command.name), ["goal"]); + assert.deepEqual(await act(async () => w.latest.handleBuiltinSlashCommand("/goal ship it")), { handled: false }); + assert.equal(world.calls.some((call) => call.body?.type === "goal"), false); +}); + +test("GOAL a failed catalog refresh preserves a newer ownership event", async (t) => { + resetWorld(); + primeSession("goal-catalog-failure", [userMsg("u0", "loaded question")]); + const w = await mountSession("goal-catalog-failure"); + t.mock.method(console, "error", () => {}); + await act(async () => w.latest.handleAgentEventRef.current({ + type: "available_commands_update", + commands: [{ name: "goal", source: "extension", description: "new owner" }], + })); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "get_commands", + produce: async () => ({ status: 503, value: { error: "offline" } }), + }); + + let failure; + await act(async () => { + try { + await w.latest.loadSlashCommands(); + } catch (error) { + failure = error; + } + }); + assert.match(String(failure), /offline/); + assert.deepEqual(w.latest.slashCommands.map((command) => command.name), ["goal"]); + assert.deepEqual(await act(async () => w.latest.handleBuiltinSlashCommand("/goal ship it")), { handled: false }); + assert.equal(world.calls.some((call) => call.body?.type === "goal"), false); +}); + test("GOAL pause, resume and drop send the matching RPC and update the banner", async () => { resetWorld(); primeSession("goal-actions", [userMsg("u0", "loaded question")]); @@ -2850,6 +2911,103 @@ function holdNext(match) { return held; } +async function mountCompactionObserver(sid) { + primeSession(sid, [userMsg("u0", "q")]); + const w = await mountSession(sid); + world.agents.set(sid, { running: true, state: {} }); + await deliverRunning([sid]); + await settle(); + const es = lastEs(); + await act(async () => { + es.open(); + await sleep(30); + }); + return { w, es }; +} + +test("manual compaction events preserve overlapping local compaction ownership in either settlement order", async () => { + resetWorld(); + const sid = "manual-local-overlap"; + const { w, es } = await mountCompactionObserver(sid); + + const first = holdNext((method, url, body) => method === "POST" && url === `/api/agent/${sid}` && body?.type === "compact"); + let firstCompaction; + await act(async () => { + firstCompaction = w.latest.handleCompact(); + await sleep(30); + }); + await act(async () => { + es.emit({ type: "manual_compaction_start" }); + es.emit({ type: "manual_compaction_end" }); + }); + assert.equal(w.latest.isCompacting, true, "a native end cannot release the local command"); + await act(async () => { + first.release({ success: true, data: {} }); + await firstCompaction; + }); + assert.equal(w.latest.isCompacting, false); + + const second = holdNext((method, url, body) => method === "POST" && url === `/api/agent/${sid}` && body?.type === "compact"); + let secondCompaction; + await act(async () => { + secondCompaction = w.latest.handleCompact(); + await sleep(30); + es.emit({ type: "manual_compaction_start" }); + }); + await act(async () => { + second.release({ success: true, data: {} }); + await secondCompaction; + }); + assert.equal(w.latest.isCompacting, true, "the native compaction keeps ownership after the local command settles"); + await act(async () => { + es.emit({ type: "manual_compaction_end" }); + }); + assert.equal(w.latest.isCompacting, false); +}); + +test("a remote manual compaction blocks a local compact command until its end event", async () => { + resetWorld(); + const sid = "remote-manual-compact"; + const { w, es } = await mountCompactionObserver(sid); + const compactCalls = () => callsTo("POST", `/api/agent/${sid}`).filter((call) => call.body?.type === "compact").length; + + await act(async () => { + es.emit({ type: "manual_compaction_start" }); + }); + assert.equal(w.latest.isCompacting, true); + await act(async () => { + await w.latest.handleCompact(); + }); + assert.equal(compactCalls(), 0, "the remote owner prevents a competing compact command"); + + await act(async () => { + es.emit({ type: "manual_compaction_end" }); + }); + assert.equal(w.latest.isCompacting, false); +}); + +test("an auto-compaction end event cannot release an overlapping local compaction", async () => { + resetWorld(); + const sid = "auto-local-overlap"; + const { w, es } = await mountCompactionObserver(sid); + const compact = holdNext((method, url, body) => method === "POST" && url === `/api/agent/${sid}` && body?.type === "compact"); + let compacting; + await act(async () => { + compacting = w.latest.handleCompact(); + await sleep(30); + }); + await act(async () => { + es.emit({ type: "auto_compaction_start" }); + es.emit({ type: "auto_compaction_end" }); + }); + assert.equal(w.latest.isCompacting, true, "the local command still owns compaction"); + await act(async () => { + compact.release({ success: true, data: {} }); + await compacting; + }); + assert.equal(w.latest.isCompacting, false); +}); + test("an idle snapshot cannot release a manual compaction this tab is still sending", async () => { resetWorld(); const sid = "cold-compact"; @@ -6552,6 +6710,41 @@ test("a fresh chat's /btw question attaches one event stream instead of an obser assert.equal(world.esInstances.length, 1); }); +test("a fresh chat dispatches /btw against the catalog loaded by the composer", async () => { + resetWorld(); + const sid = "fresh-catalog-btw"; + world.holds.push({ + match: (method, url) => method === "POST" && url === "/api/agent/new", + produce: async () => ({ value: { sessionId: sid } }), + }); + world.holds.push({ + match: (method, url, body) => method === "POST" && url === `/api/agent/${sid}` && body?.type === "get_commands", + produce: async () => ({ value: { success: true, data: { commands: [] } } }), + }); + holdBtwCommand("btw", async () => ({ value: { success: true, data: { record: btwRecord() } } })); + const w = await mountSession(null, undefined, { newSessionCwd: "/workspace", onSessionCreated: () => {} }); + + await act(async () => { + await w.latest.loadSlashCommands(); + }); + let asked; + await act(async () => { + asked = w.latest.handleBuiltinSlashCommand("/btw what is 2+2"); + await sleep(30); + }); + let result; + await act(async () => { + lastEs().open(); + result = await asked; + }); + w.unmount(); + + assert.deepEqual(result, { handled: true }); + assert.equal(callsTo("POST", "/api/agent/new").length, 1, "catalog discovery and dispatch share one runtime"); + const commands = callsTo("POST", `/api/agent/${sid}`).map((call) => call.body?.type); + assert.ok(commands.indexOf("get_commands") < commands.indexOf("btw"), "the authoritative catalog is loaded before client dispatch"); +}); + test("a first prompt rejected after promotion identifies the real-session recovery draft", async () => { resetWorld(); const sid = "promoted-rejected-send"; diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index eab62ac6e..1cf7f1994 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -426,6 +426,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // but the unknown-command warning must not flag them (#167). Ref-only: it is // consulted at send time and must never re-render the composer. const knownSlashCommandNamesRef = useRef([]); + const slashCommandsRef = useRef([]); + /** Invalidates an older `get_commands` snapshot when a live catalog event wins. */ + const slashCatalogVersionRef = useRef(0); /** True once a `get_commands` reply actually arrived: until then an empty * roster means "not asked yet", not "omp owns nothing". */ const slashRosterLoadedRef = useRef(false); @@ -1352,31 +1355,31 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const loadSlashCommands = useCallback(async () => { if (slashCommandsInFlightRef.current) return slashCommandsInFlightRef.current; + const requestedVersion = slashCatalogVersionRef.current; const request = (async () => { const sid = sessionIdRef.current ?? await ensureNewSession(); if (!sid) { - setSlashCommands([]); - knownSlashCommandNamesRef.current = []; - return [] as SlashCommandInfo[]; + throw new Error("No session is available for slash-command discovery"); } setSlashCommandsLoading(true); try { const data = await sendAgentCommand(sid, { type: "get_commands" }); const available = Array.isArray(data?.commands) ? data.commands : []; + if (slashCatalogVersionRef.current !== requestedVersion) return slashCommandsRef.current; // Keep every source, builtins included: omp runs them through the prompt // path and they must not be reported as unknown (#167). - // A reply carrying no list is not evidence that nothing is known, so it - // must not erase a roster an earlier reply did supply. - if (available.length > 0) knownSlashCommandNamesRef.current = slashCommandRosterNames(available); + // A reply carrying no list is not evidence that nothing is known. An + // explicit empty list is authoritative once no newer event superseded it. + if (Array.isArray(data?.commands)) { + knownSlashCommandNamesRef.current = slashCommandRosterNames(available); + slashCommandsRef.current = available.map(toSlashCommandInfo); + setSlashCommands(slashCommandsRef.current); + } slashRosterLoadedRef.current = true; - const commands = available.map(toSlashCommandInfo); - setSlashCommands(commands); - return commands; + return slashCommandsRef.current; } catch (e) { console.error("Failed to load slash commands:", e); - setSlashCommands([]); - knownSlashCommandNamesRef.current = []; - return [] as SlashCommandInfo[]; + throw e; } finally { setSlashCommandsLoading(false); } @@ -2696,8 +2699,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } case "available_commands_update": { const commands = (event.commands as RpcAvailableSlashCommand[] | undefined) ?? []; + slashCatalogVersionRef.current += 1; + slashRosterLoadedRef.current = true; knownSlashCommandNamesRef.current = slashCommandRosterNames(commands); - setSlashCommands(commands.map(toSlashCommandInfo)); + slashCommandsRef.current = commands.map(toSlashCommandInfo); + setSlashCommands(slashCommandsRef.current); break; } case "goal_updated": { @@ -4137,7 +4143,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [ensureEventsConnected, ensureNewSession, promoteNewSession, sendBtw]); - const handleBuiltinSlashCommand = useCallback(async (text: string): Promise => { + const handleBuiltinSlashCommand = useCallback(async ( + text: string, + sendPrompt?: (message: string) => Promise, + ): Promise => { if (editInFlightRef.current) return { handled: true, retainInput: true }; if (!text.startsWith("/")) return { handled: false }; const match = text.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/); @@ -4165,10 +4174,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // `name`, or `copy` must not be shadowed. A pasted or dictated command can // reach dispatch before autocomplete ever fetched the roster, so ask once // here rather than deciding on an empty list. - // A fresh chat has no roster until omp starts, and starting it here would - // attach an observer stream beside the command's own; its first command - // creates the runtime, and the roster is known from the next dispatch on - // (typing "/" already loads it through the palette). + // ChatInput resolves the catalog before invoking this handler, including + // for a fresh chat (that lookup creates its runtime). Direct callers can + // still arrive here without a runtime; they create it in the selected + // command path, and later dispatches load its roster here. if (!slashRosterLoadedRef.current && sessionIdRef.current) await loadSlashCommands(); if (!hookAliveRef.current) return { handled: true }; if (knownSlashCommandNamesRef.current.includes(commandName)) return { handled: false }; @@ -4273,7 +4282,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { }); } if (commandName === "plan") setActivePlan({ objective: args }); - const sent = await handleSend(expansion.prompt); + const sent = await (sendPrompt ? sendPrompt(expansion.prompt) : handleSend(expansion.prompt)); if (sent.status !== "accepted") { if (commandName === "plan") setActivePlan(null); return { handled: true, retainInput: true }; diff --git a/lib/goal-state.test.mjs b/lib/goal-state.test.mjs index fb10018fd..37e3a810f 100644 --- a/lib/goal-state.test.mjs +++ b/lib/goal-state.test.mjs @@ -34,6 +34,7 @@ test("reads omp's goal shapes defensively", () => { goal: null, }); // A present-but-malformed goal must not be mistaken for "no goal". + assert.equal(readGoalModeState({ enabled: true, mode: "active" }), null); assert.equal(readGoalModeState({ enabled: true, mode: "active", goal: { objective: "" } }), null); assert.equal(readGoalModeState("nope"), null); }); @@ -59,8 +60,10 @@ test("malformed goal payloads never look like a valid clear", () => { // A broken state alongside a null goal must be skipped, not published as a // clear that hides the banner. assert.equal(readGoalUpdatedEvent({ goal: null, state: { enabled: true } }), undefined); + assert.equal(readGoalUpdatedEvent({ state: { enabled: true, mode: "active" } }), undefined); assert.equal(readGoalUpdatedEvent({ goal: { objective: "" }, state: null }), undefined); assert.equal(readGoalUpdatedEvent({}), undefined); + assert.equal(readGoalCommandResponse({ state: { enabled: true, mode: "active" } }), null); assert.equal(readGoalCommandResponse({ goal: null, state: { enabled: true } }), null); assert.equal(readGoalCommandResponse({ goal: GOAL, diff --git a/lib/goal-state.ts b/lib/goal-state.ts index 839b9b4f3..5f32d61b5 100644 --- a/lib/goal-state.ts +++ b/lib/goal-state.ts @@ -34,9 +34,10 @@ function stateFromGoal(goal: Goal | null): GoalModeState | null { export function readGoalModeState(value: unknown): GoalModeState | null { if (!isRecord(value)) return null; + if (!("goal" in value)) return null; const goal = readGoal(value.goal); // A present-but-malformed goal is not "no goal": refuse the snapshot. - if (value.goal != null && !goal) return null; + if (value.goal !== null && !goal) return null; const enabled = value.enabled; const mode = asString(value.mode); if (typeof enabled !== "boolean" || mode === undefined) return stateFromGoal(goal); diff --git a/lib/hosts/daemon-channels.test.mjs b/lib/hosts/daemon-channels.test.mjs index f41636ae4..171427b81 100644 --- a/lib/hosts/daemon-channels.test.mjs +++ b/lib/hosts/daemon-channels.test.mjs @@ -403,15 +403,23 @@ test("a history-edit lease refuses a competing editor and other links' mutations assert.throws(() => h.table.editLease(h.b, a.ch, true), { status: 409, code: "session_busy" }, "a competing editor fails before its preflight"); h.table.editLease(h.b, a.ch, false); // Releasing a lease it does not hold changes nothing. h.table.stdin(h.b, a.ch, JSON.stringify({ type: "prompt", id: "peer", message: "x" })); + h.table.stdin(h.b, a.ch, JSON.stringify({ type: "goal", op: "create", id: "peer-goal", objective: "ship" })); + h.table.stdin(h.b, a.ch, JSON.stringify({ type: "goal", op: "get", id: "goal-read" })); h.table.stdin(h.b, a.ch, JSON.stringify({ type: "get_state", id: "read" })); h.table.stdin(h.a, a.ch, JSON.stringify({ type: "prompt", id: "edit", message: "/edit" })); assert.deepEqual(prompts(), ["edit"]); assert.ok(h.children[0].writes.some(frame => frame.id === "read"), "reads are never fenced"); + assert.ok(h.children[0].writes.some(frame => frame.id === "goal-read"), "goal reads are never fenced"); + assert.equal(h.children[0].writes.some(frame => frame.id === "peer-goal"), false, "a peer goal mutation cannot cross the edit lease"); const refused = h.output.filter(item => item.id === "l2" && item.body.type === "stdout").map(item => JSON.parse(item.body.line)).find(frame => frame.id === "peer"); assert.equal(refused?.code, "session_busy"); + const refusedGoal = h.output.filter(item => item.id === "l2" && item.body.type === "stdout").map(item => JSON.parse(item.body.line)).find(frame => frame.id === "peer-goal"); + assert.equal(refusedGoal?.code, "session_busy"); h.table.editLease(h.a, a.ch, false); h.table.editLease(h.b, a.ch, true); h.table.editLease(h.b, a.ch, false); // Free again: B may take it. h.table.stdin(h.b, a.ch, JSON.stringify({ type: "prompt", id: "after", message: "x" })); + h.table.stdin(h.b, a.ch, JSON.stringify({ type: "goal", op: "create", id: "goal-after", objective: "ship" })); + assert.ok(h.children[0].writes.some(frame => frame.id === "goal-after"), "the mutation proceeds after the lease is released"); h.table.editLease(h.a, a.ch, true); h.table.linkDown(h.a); // A restarted server forgets its edit. h.table.stdin(h.b, a.ch, JSON.stringify({ type: "prompt", id: "dropped", message: "x" })); h.table.editLease(h.a, a.ch, true); h.table.close(h.a, a.ch); diff --git a/lib/hosts/daemon-channels.ts b/lib/hosts/daemon-channels.ts index 404eb61e9..9ab829759 100644 --- a/lib/hosts/daemon-channels.ts +++ b/lib/hosts/daemon-channels.ts @@ -6,7 +6,7 @@ import { readSessionHeaderSync } from "../omp/session-files"; import { isValidSessionId } from "../session-file-references-core"; import { isRecord } from "../type-guards"; import type { DaemonLink } from "./daemon-link"; -import { HISTORY_MUTATING_COMMANDS, HostOpError, LINK_LIMITS, MESSAGE_COMMANDS, PEER_MESSAGE_FRAME, type HelloChannel, type HostUriScheme, type OpenChannelRequest, type OpenChannelResult, type Unsequenced, type UpMessage } from "./link-protocol"; +import { HostOpError, isHistoryMutatingCommand, LINK_LIMITS, MESSAGE_COMMANDS, PEER_MESSAGE_FRAME, type HelloChannel, type HostUriScheme, type OpenChannelRequest, type OpenChannelResult, type Unsequenced, type UpMessage } from "./link-protocol"; import { PendingRequests } from "./pending-requests"; import { StreamSnapshot } from "./stream-snapshot"; import { ChannelLifecycle } from "./channel-lifecycle"; @@ -441,7 +441,7 @@ export class ChannelTable { } return; } - if (channel.editor !== undefined && channel.editor !== link.id && HISTORY_MUTATING_COMMANDS.has(frame.type)) { + if (channel.editor !== undefined && channel.editor !== link.id && isHistoryMutatingCommand(frame)) { if (typeof frame.id === "string") { this.deliver(channel, channel.members.get(link.id)!, { type: "stdout", ch, line: JSON.stringify({ type: "response", id: frame.id, command: frame.type, success: false, code: "session_busy", error: "Another web app is editing this session's history; retry once it finishes" }) }, true); diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index 589252b99..c0ab10531 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -64,6 +64,12 @@ export const HISTORY_MUTATING_COMMANDS = new Set([ "set_model", "cycle_model", "set_thinking_level", "cycle_thinking_level", "set_fast_mode", "set_slow_mode", "set_auto_compaction", "set_auto_retry", "abort_retry", ]); +/** One history-edit fence shared by web wrappers and a daemon's peer links. */ +export function isHistoryMutatingCommand(command: { type?: unknown; op?: unknown }): boolean { + return typeof command.type === "string" + && (HISTORY_MUTATING_COMMANDS.has(command.type) + || (command.type === "goal" && command.op !== "get")); +} /** Commands whose user message a peer's identical echo could be mistaken for. */ export const MESSAGE_COMMANDS = new Set(["prompt", "steer", "follow_up", "followUp", "abort_and_prompt"]); /** Shared-channel marker a daemon puts in the other members' output when one link writes a message command. */ diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 08f583329..8c3514adc 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -519,6 +519,7 @@ "chatInput.inputHistory": "Input history", "chatInput.kindFollowUp": "follow-up", "chatInput.kindSteer": "steer", + "chatInput.commandCatalogUnavailable": "Couldn’t load slash commands. Try again.", "chatInput.loadingCommands": "Loading commands...", "chatInput.loadingFiles": "Loading files...", "chatInput.loadingModels": "Loading models...", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 4833ed93a..5c4f0e325 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -502,6 +502,7 @@ "chatInput.inputHistory": "入力履歴", "chatInput.kindFollowUp": "フォローアップ", "chatInput.kindSteer": "ステア", + "chatInput.commandCatalogUnavailable": "スラッシュコマンドを読み込めませんでした。もう一度お試しください。", "chatInput.loadingCommands": "コマンドを読み込み中...", "chatInput.loadingFiles": "ファイルを読み込み中...", "chatInput.loadingModels": "モデルを読み込み中...", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index e78d24597..6090497aa 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -502,6 +502,7 @@ "chatInput.inputHistory": "输入历史", "chatInput.kindFollowUp": "追加消息", "chatInput.kindSteer": "引导", + "chatInput.commandCatalogUnavailable": "无法加载斜杠命令,请重试。", "chatInput.loadingCommands": "正在加载命令...", "chatInput.loadingFiles": "正在加载文件...", "chatInput.loadingModels": "正在加载模型...", diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index c58bac61b..af7518bf0 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -199,6 +199,23 @@ test("terminal completion retains response evidence without retaining the unpers assert.equal(state.responseObserved, true, "an idle state read cannot erase native response evidence"); }); +test("manual compaction frames own the live snapshot and invalidate session metadata", async (t) => { + const invalidated = []; + const host = { + ...localHost, + invalidateSessionLists(sessionFile) { invalidated.push(sessionFile); }, + }; + const { wrapper, emit } = snapshotSession(t, undefined, SnapshotWrapper, "manual-compact", undefined, host); + const before = invalidated.length; + + emit({ type: "manual_compaction_start" }); + assert.equal(wrapper.getStreamSnapshot().isCompacting, true); + + emit({ type: "manual_compaction_end", result: { estimatedTokensAfter: 42 } }); + assert.equal(wrapper.getStreamSnapshot().isCompacting, false); + assert.equal(invalidated.length, before + 1); +}); + diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index b4fdde03b..e6ce48fd5 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -38,7 +38,7 @@ import type { import type { AgentMessage, CrossSessionHostToolCall, CrossSessionHostToolEvent, ExitedRpcSession, ExtensionWidgetItem } from "./types"; import { isLinkUp, type Host, type HostStatus, type SpawnRequest, type SpawnResult } from "./hosts/host"; import { freezeHostLinks, getHost, hostOwnsLifecycle, isNotifier, lastUplinkAt, listHosts, orphanExit } from "./hosts/hub"; -import { HISTORY_MUTATING_COMMANDS, HostOpError, PEER_MESSAGE_FRAME } from "./hosts/link-protocol"; +import { HostOpError, isHistoryMutatingCommand, PEER_MESSAGE_FRAME } from "./hosts/link-protocol"; import { LOCAL_HOST_ID } from "./hosts/registry"; import type { OpResult } from "./hosts/session-ops"; import { hostForSessionId, invalidateHostSessionList, listSessionsAllHosts, sessionSpawnTarget } from "./hosts/session-index"; @@ -1265,10 +1265,15 @@ export class AgentSessionWrapper { patchEstimatedTokensAfter(event.result); this.invalidateSessionLists(); break; + case "manual_compaction_start": + this.compacting = true; + break; case "manual_compaction_end": // `/compact` runs through omp's builtin; the client reads this event // result for the banner, so patch it like the RPC response path. + this.compacting = false; patchEstimatedTokensAfter(event.result); + this.invalidateSessionLists(); break; case "notice": if (event.source === "session-persistence") void this.followSessionMove(); @@ -2527,12 +2532,9 @@ export class AgentSessionWrapper { if (typeof command.type === "string" && command.type.startsWith("abort")) { console.info("[omp-web] cancellation-command", JSON.stringify({ sessionId: this._sessionId, type: command.type, at: new Date().toISOString() })); } - const commandType = command.type as string; // Goal mutations change session state and the active tool set, so they // must not race a history edit. The read-only `get` op stays available. - const mutatesHistory = - HISTORY_MUTATING_COMMANDS.has(commandType) - || (commandType === "goal" && command.op !== "get"); + const mutatesHistory = isHistoryMutatingCommand(command); if (mutatesHistory && this.historyEditInFlight) { throw new WebRpcError("Wait for the history edit to finish", "session_busy"); } From 50a0957f78b47bbc0c407d1ccba3cf9cce37398f Mon Sep 17 00:00:00 2001 From: killcerr Date: Mon, 9 Nov 2026 21:37:54 +0800 Subject: [PATCH 9/9] fix(chat): harden slash command and goal handling --- CHANGELOG.md | 2 +- .../ChatInput.queue-attachments.test.mjs | 36 +++++++++++++++++- components/ChatInput.tsx | 37 +++++++++---------- lib/goal-state.test.mjs | 3 ++ lib/goal-state.ts | 14 ++++--- lib/hosts/daemon-channels.test.mjs | 4 ++ 6 files changed, 69 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index de9ebb2d9..00f3baf37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements - **Anthropic stays visible when usage limits are unavailable.** The Provider Usage panel keeps accounts that omp reports without usage data and marks them as unavailable rather than unlimited. -- **Slash-command dispatch keeps the command catalog authoritative without losing drafts or attachments.** A late catalog snapshot can no longer overwrite a newer command update, failed discovery leaves the current roster and draft intact for retry, and typing while the first lookup is pending is never cleared by the older command. Web prompt commands expand before text, image and uploaded-file attachments are sent, and remain visible in the palette while a run is active. +- **Slash-command dispatch keeps the command catalog authoritative without losing drafts or attachments.** Dispatch refreshes even a non-empty roster before choosing between omp and a web command, so a missed catalog update cannot route a pasted, dictated or queued command to the wrong owner. A late catalog snapshot cannot overwrite a newer command update, failed discovery leaves the current roster and draft intact for retry, and typing while the lookup is pending is never cleared by the older command. Web prompt commands are expanded and size-checked once before text, image and uploaded-file attachments are sent, and remain visible in the palette while a run is active. - **Goal and manual-compaction state stay fenced and synchronized across clients.** Goal mutations now respect a history edit held through a shared host daemon, malformed goal snapshots cannot hide a valid banner, and native `/compact` events update the server's live snapshot and session-list caches as well as the initiating tab. - **A delayed archive restore cannot overwrite newer archived work.** Restore now pins the compressed source generation it staged and verifies an atomically captured archive entry before moving artifacts. If another server restored, updated and re-archived that session meanwhile, the stale restore is refused and the newer transcript and artifacts remain available. Captured archives remain discoverable by session ID before publication and after an interrupted restore, so held messages are not falsely failed as belonging to a missing session; orphaned restore claims report their manual-recovery path. - **In-progress archive captures are evidence, not restore targets.** Captures have unique keys and disabled Restore controls, so a capture and a newer archive cannot select the wrong session. Archive discovery rechecks names and source generations after reading to avoid missing a capture during concurrent replacement; a capture encountered while pinning still reports its restore-claim recovery path. diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 5a25b7f9d..9d27f16f8 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -159,7 +159,7 @@ test("a stored Steer preference turns the primary button into Steer, which steer assertQueuedWithAttachments(calls[0], "look at this"); }); -test("a catalog-owned goal with attachments is forwarded once the catalog answers", async () => { +test("a refreshed catalog can replace a non-empty stale roster before an idle command dispatches", async () => { window.HTMLElement.prototype.scrollIntoView = () => {}; const user = userEvent.setup(); let release; @@ -170,7 +170,7 @@ test("a catalog-owned goal with attachments is forwarded once the catalog answer const builtins = []; const { calls } = await renderWithAttachments({ isStreaming: false, - slashCommands: [], + slashCommands: [{ name: "old-command", source: "builtin", description: "stale command" }], onBuiltinCommand: async (message) => { builtins.push(message); return { handled: false }; @@ -193,6 +193,38 @@ test("a catalog-owned goal with attachments is forwarded once the catalog answer assert.deepEqual(builtins, [], "with attachments the command goes straight to the prompt"); }); +test("a queued command waits for a refreshed non-empty catalog before choosing its owner", async () => { + const user = userEvent.setup(); + let release; + let loads = 0; + const catalog = new Promise((resolve) => { + release = () => resolve([{ name: "goal", source: "extension", description: "extension goal" }]); + }); + const builtins = []; + const { calls } = await renderWithAttachments({ + attachments: false, + slashCommands: [{ name: "old-command", source: "builtin", description: "stale command" }], + onBuiltinCommand: async (message) => { + builtins.push(message); + return { handled: true }; + }, + onLoadSlashCommands: () => { + loads += 1; + return catalog; + }, + }); + await user.type(screen.getByRole("textbox"), "/goal ship it"); + await user.keyboard("{Enter}"); + await waitFor(() => assert.ok(loads >= 1), { timeout: 2000 }); + assert.deepEqual(calls, [], "the old roster must not route the command"); + assert.deepEqual(builtins, [], "the old roster must not invoke the client goal handler"); + await act(async () => release()); + await waitFor(() => assert.equal(calls.length, 1)); + assert.equal(calls[0].name, "onFollowUp"); + assert.equal(calls[0].message, "/goal ship it"); + assert.deepEqual(builtins, []); +}); + test("a delayed catalog dispatch never clears text typed after the original command", async () => { const user = userEvent.setup(); let release; diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 0d1add050..517f783c4 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -434,13 +434,13 @@ export const ChatInput = memo(forwardRef(function ChatIn [slashCommands], ); // The catalog decides who owns a slash command. A pasted or dictated command - // can reach dispatch before the palette ever opened, so fetch it once before - // routing instead of deciding on an empty roster. Concurrent sends share the - // request; the gate stops a second Enter from dispatching while it waits. + // can reach dispatch before the palette's refresh finishes, so dispatch + // always asks for the latest roster. Concurrent sends share the request; the + // gate stops a second Enter from dispatching while it waits. const catalogRequestRef = useRef> | null>(null); const catalogGateRef = useRef(false); const resolveCommandCatalog = useCallback((): Promise> => { - if (ompCommandNames.size > 0 || !onLoadSlashCommands) return Promise.resolve(ompCommandNames); + if (!onLoadSlashCommands) return Promise.resolve(ompCommandNames); if (!catalogRequestRef.current) { const request = Promise.resolve() .then(() => onLoadSlashCommands()) @@ -1250,11 +1250,17 @@ export const ChatInput = memo(forwardRef(function ChatIn const images = attachedImagesRef.current; const files = attachedTextFilesRef.current; const uploads = attachedUploadsRef.current; - const sendPrompt = (prompt: string) => onSend( - composeMessageWithTextAttachments(prompt, files), - images.length ? images : undefined, - ...uploadArgs(uploads), - ); + const sendPrompt = (prompt: string): Promise => { + const composed = composeMessageWithTextAttachments(prompt, files); + if (rejectsOversizedPrompt(composed, images)) { + return Promise.resolve({ status: "rejected" }); + } + return onSend( + composed, + images.length ? images : undefined, + ...uploadArgs(uploads), + ); + }; // Dictation inserts overrideText in the same batch as dispatch. It still // must match on completion; an override does not own subsequent typing. const stored = clearOnceStored(sentValue); @@ -1274,7 +1280,7 @@ export const ChatInput = memo(forwardRef(function ChatIn stored.release(); holdingRef.current = false; } - }, [onBuiltinCommand, onSend, clearOnceStored]); + }, [onBuiltinCommand, onSend, clearOnceStored, rejectsOversizedPrompt]); /** `/btw` asks a side question beside any run: never a prompt, never * queued. Attachments cannot ride along, so refuse and keep the draft @@ -1299,7 +1305,7 @@ export const ChatInput = memo(forwardRef(function ChatIn if (submissionBlockedRef.current || holdingRef.current || (isStreaming && !shellCommand)) return; onAudioUnlock?.(); let catalog = ompCommandNames; - if (msg.startsWith("/") && ompCommandNames.size === 0 && onLoadSlashCommands) { + if (msg.startsWith("/") && onLoadSlashCommands) { if (catalogGateRef.current) return; catalogGateRef.current = true; try { @@ -1323,13 +1329,6 @@ export const ChatInput = memo(forwardRef(function ChatIn const composedMessage = composeMessageWithTextAttachments(msg, attachedTextFilesRef.current); if (msg.startsWith("/") && onBuiltinCommand) { const commandName = msg.slice(1).split(/\s+/)[0]; - const expansion = catalog.has(commandName) - ? { kind: "not-web" as const } - : expandWebSlashCommand(msg); - if (expansion.kind === "expand") { - const expandedMessage = composeMessageWithTextAttachments(expansion.prompt, attachedTextFilesRef.current); - if (rejectsOversizedPrompt(expandedMessage, attachedImagesRef.current)) return; - } if (!catalog.has(commandName) && await runBuiltinCommand(msg, raw)) return; } if (submissionBlockedRef.current) return; @@ -1815,7 +1814,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const msg = raw.trim(); if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) return; let catalog = ompCommandNames; - if (msg.startsWith("/") && ompCommandNames.size === 0 && onLoadSlashCommands) { + if (msg.startsWith("/") && onLoadSlashCommands) { if (catalogGateRef.current) return; catalogGateRef.current = true; try { diff --git a/lib/goal-state.test.mjs b/lib/goal-state.test.mjs index 37e3a810f..90f794733 100644 --- a/lib/goal-state.test.mjs +++ b/lib/goal-state.test.mjs @@ -35,6 +35,7 @@ test("reads omp's goal shapes defensively", () => { }); // A present-but-malformed goal must not be mistaken for "no goal". assert.equal(readGoalModeState({ enabled: true, mode: "active" }), null); + assert.equal(readGoalModeState({ enabled: true, mode: "active", goal: undefined }), null); assert.equal(readGoalModeState({ enabled: true, mode: "active", goal: { objective: "" } }), null); assert.equal(readGoalModeState("nope"), null); }); @@ -65,6 +66,8 @@ test("malformed goal payloads never look like a valid clear", () => { assert.equal(readGoalUpdatedEvent({}), undefined); assert.equal(readGoalCommandResponse({ state: { enabled: true, mode: "active" } }), null); assert.equal(readGoalCommandResponse({ goal: null, state: { enabled: true } }), null); + assert.equal(readGoalCommandResponse({ goal: undefined, state: null }), null); + assert.equal(readGoalCommandResponse({ goal: null, state: undefined }), null); assert.equal(readGoalCommandResponse({ goal: GOAL, state: { enabled: true, mode: "active", goal: { ...GOAL, id: "g2" } }, diff --git a/lib/goal-state.ts b/lib/goal-state.ts index 5f32d61b5..8526e3144 100644 --- a/lib/goal-state.ts +++ b/lib/goal-state.ts @@ -34,9 +34,9 @@ function stateFromGoal(goal: Goal | null): GoalModeState | null { export function readGoalModeState(value: unknown): GoalModeState | null { if (!isRecord(value)) return null; - if (!("goal" in value)) return null; const goal = readGoal(value.goal); - // A present-but-malformed goal is not "no goal": refuse the snapshot. + // Only explicit null is "no goal"; missing, undefined or malformed values + // must not clear a valid displayed goal. if (value.goal !== null && !goal) return null; const enabled = value.enabled; const mode = asString(value.mode); @@ -68,11 +68,15 @@ export function readGoalUpdatedEvent(value: unknown): GoalModeState | null | und export function readGoalCommandResponse(value: unknown): GoalCommandResponse | null { if (!isRecord(value)) return null; - if (!("goal" in value) && !("state" in value)) return null; + const hasGoal = "goal" in value; + const hasState = "state" in value; + if (!hasGoal && !hasState) return null; const state = readGoalModeState(value.state); const goal = readGoal(value.goal); - if (value.goal != null && !goal) return null; - if (value.state != null && !state) return null; + // Only explicit null is a clear. A present undefined or malformed value + // must not be normalized into a successful "no goal" response. + if (hasGoal && value.goal !== null && !goal) return null; + if (hasState && value.state !== null && !state) return null; if (goal && state && state.goal?.id !== goal.id) return null; if (state || goal) return { goal: goal ?? state?.goal ?? null, state: state ?? stateFromGoal(goal) }; // Both null is a valid "no goal" answer (drop/get). diff --git a/lib/hosts/daemon-channels.test.mjs b/lib/hosts/daemon-channels.test.mjs index 171427b81..31b97babd 100644 --- a/lib/hosts/daemon-channels.test.mjs +++ b/lib/hosts/daemon-channels.test.mjs @@ -404,6 +404,7 @@ test("a history-edit lease refuses a competing editor and other links' mutations h.table.editLease(h.b, a.ch, false); // Releasing a lease it does not hold changes nothing. h.table.stdin(h.b, a.ch, JSON.stringify({ type: "prompt", id: "peer", message: "x" })); h.table.stdin(h.b, a.ch, JSON.stringify({ type: "goal", op: "create", id: "peer-goal", objective: "ship" })); + h.table.stdin(h.b, a.ch, JSON.stringify({ type: "goal", op: "pause", id: "peer-goal-pause" })); h.table.stdin(h.b, a.ch, JSON.stringify({ type: "goal", op: "get", id: "goal-read" })); h.table.stdin(h.b, a.ch, JSON.stringify({ type: "get_state", id: "read" })); h.table.stdin(h.a, a.ch, JSON.stringify({ type: "prompt", id: "edit", message: "/edit" })); @@ -411,10 +412,13 @@ test("a history-edit lease refuses a competing editor and other links' mutations assert.ok(h.children[0].writes.some(frame => frame.id === "read"), "reads are never fenced"); assert.ok(h.children[0].writes.some(frame => frame.id === "goal-read"), "goal reads are never fenced"); assert.equal(h.children[0].writes.some(frame => frame.id === "peer-goal"), false, "a peer goal mutation cannot cross the edit lease"); + assert.equal(h.children[0].writes.some(frame => frame.id === "peer-goal-pause"), false, "non-create goal mutations cannot cross the edit lease"); const refused = h.output.filter(item => item.id === "l2" && item.body.type === "stdout").map(item => JSON.parse(item.body.line)).find(frame => frame.id === "peer"); assert.equal(refused?.code, "session_busy"); const refusedGoal = h.output.filter(item => item.id === "l2" && item.body.type === "stdout").map(item => JSON.parse(item.body.line)).find(frame => frame.id === "peer-goal"); assert.equal(refusedGoal?.code, "session_busy"); + const refusedPause = h.output.filter(item => item.id === "l2" && item.body.type === "stdout").map(item => JSON.parse(item.body.line)).find(frame => frame.id === "peer-goal-pause"); + assert.equal(refusedPause?.code, "session_busy"); h.table.editLease(h.a, a.ch, false); h.table.editLease(h.b, a.ch, true); h.table.editLease(h.b, a.ch, false); // Free again: B may take it. h.table.stdin(h.b, a.ch, JSON.stringify({ type: "prompt", id: "after", message: "x" }));