diff --git a/AGENTS.md b/AGENTS.md index 197270781..52b608836 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -123,6 +123,7 @@ lib/ notification-store.ts server: SQLite store for VAPID keys, devices and the notification history notification-history.ts browser: mirror of the server's notification history (Notifications tab) notification-client.ts browser: device id, prefs store, service worker + push subscription + queue-progress.ts pure ledger of queued prompts (queued/running/done/failed/cancelled) fed by omp frames rpc-manager.ts session registry + startRpcSession over RpcProcess session-reader.ts session .jsonl parsing + path cache + buildSessionContext session-search.ts shared fuzzy/phrase query scorer for sidebar search (title weights ≫ transcript) @@ -146,6 +147,7 @@ components/ ChatWindow.tsx chat composition + completion sound wrapper ChatInput.tsx input bar + model/thinking/tools/compact controls ComposerPanels.tsx composer-attached /btw + todo + subagent panels (collapsible, live states) + QueueProgressPanel.tsx composer queue panel: ledger batch, "N of M done", per-item status/actions, dismissible summary BtwPanel.tsx /btw side-question panel (stream, cancel, copy, follow-up) + history dialog TodoList.tsx todo phase grid with preview/show-all (used by ComposerPanels) SubagentTranscriptDialog.tsx task + final output summary dialog (wide, screen-adaptive) @@ -366,6 +368,45 @@ during the wait. reason:"shellRunning"}`), which the hook surfaces as a notice while rolling the phantom optimistic turn back. The chip still comes from omp's snapshot. +### Queued-prompt progress (`lib/queue-progress.ts`, `components/QueueProgressPanel.tsx`) +- omp's snapshots only list what is still waiting, so `AgentSessionWrapper` + keeps a per-process ledger (`queueProgress`) and feeds it frames omp already + sends: `queue_update` (and `get_state.queuedMessages`) → queued; an item that + leaves the snapshot and then arrives as a user `message_start` → running; + a later follow-up delivery in a new `turn_start` finishes earlier items + (follow-ups start only when the agent would stop; a steer joins the running + turn and finishes nothing); a terminal `agent_end` → done, or failed when its + last assistant message stopped with `error`/`aborted` (a failed prompt + `response` too); `remove_queued_message` `removed: true` and + `abort_and_restore_queue` → cancelled. A confirmed removal also overrides a + status the ledger only inferred (started alongside a later delivery, or + settled by the run's end) when the reply is handled after those frames. An + abort settles only entries that existed when it was sent (`boundary()`). + Verified frame order (omp 18.12.6): every follow-up of one prompt runs in + ONE agent run (no `agent_end` between them), and the `queue_update` that + drops an item precedes its user message. +- Items are matched by text and order. Snapshot diffs use an LCS that marks + the EARLIEST duplicate as the one that left (omp delivers from the front and + removes the first match); a departed item whose text never shows up (slash + command or template rewrite) takes the run's outcome at the end of the run, + or cancelled when the run was aborted. A plain `abort` keeps omp's pending + queue, so those items stay queued. +- Exposure: `get_state.queueProgress` (`{ epoch, revision, items }`) and a + `queue_progress` frame after every change, so every tab shows the same list. + The hook applies a snapshot only when its revision is newer within the same + epoch; an HTTP snapshot with another epoch (or none, which clears it when the + session has no live process) is dropped if a `queue_progress` frame arrived + while it was in flight. The panel merges the ledger with omp's snapshot + (`buildQueuePanelItems`): only items omp still holds get Edit/Delete/Steer, + and of identical ones only the first (omp acts on the first match); a + departed item (`departed: true`, taken but not yet in the transcript) claims + no chip. A new batch starts once nothing is pending; + Dismiss sends omp-web's own `dismiss_queue_progress` (never reaches omp, + never spawns it). The ledger is in memory only: it starts empty when omp is + respawned (`reload`, crash) or omp-web restarts, and resets when the wrapper + switches to another conversation. There is no scroll-to-message helper, so + rows do not jump to the transcript. + ### Live event stream: one socket per browser (`/api/events`) - Browsers cap HTTP/1.1 at **6 connections per host across all tabs**, and an SSE response pins one for its lifetime. Per-stream SSE (sidebar + host diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..61d69c9cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Added + +- **Queued prompts show their progress.** The composer's queue panel now keeps every prompt of the current batch after omp takes it: a "1 of 3 done" header, a check and duration for finished prompts, a spinner for the one running now, pending prompts (still editable), and failed or cancelled ones. Of several identical pending prompts only the first offers Edit, Delete and Steer, because omp acts on the first match. Once all have finished it folds into a summary you can dismiss; queueing a new batch clears it too. omp-web derives the status from omp's queue snapshots and transcript events, so every tab and device on the session sees the same list. The record lives in omp-web's memory and starts empty after omp or omp-web restarts. + ### Fixes & Improvements - **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. diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index 892d71293..cdb0aec37 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -7,15 +7,17 @@ import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-fo import { MAX_AGENT_COMMAND_REQUEST_BYTES } from "@/lib/image-attachments"; // Commands that ride whatever child is alive and never spawn or replace one: -// keystroke predictions, and the side-question reads/cancel omp-web sends in -// the background (SSE connect, reconcile). Without a live process there is no -// ghost text, no running side question and nothing to cancel, so the reply is -// known without omp. Asking (`btw`) and opening the history start omp first. +// keystroke predictions, the side-question reads/cancel omp-web sends in +// the background (SSE connect, reconcile), and dismissing the queue-progress +// summary. Without a live process there is no ghost text, no running side +// question, nothing to cancel and no queue ledger, so the reply is known +// without omp. Asking (`btw`) and opening the history start omp first. const NO_SPAWN_REPLIES: Record = { predict_word: { suffix: null }, predict_word_feedback: null, get_btw_history: { records: [] }, btw_cancel: { cancelled: false }, + dismiss_queue_progress: null, }; // Live diagnostics of a skill-resolving omp. A saved or exited session has none, diff --git a/components/ChatInput.test.mjs b/components/ChatInput.test.mjs index 26c8b1367..7b3bc0e29 100644 --- a/components/ChatInput.test.mjs +++ b/components/ChatInput.test.mjs @@ -279,7 +279,7 @@ test("keeps editing and deletion but hides Steer for a single queued steer", () assert.doesNotMatch(html, />(Steer|chatInput\.queuedSteerAction) { +test("renders multiple queued prompts with progress count and expand action", () => { const html = renderToStaticMarkup( React.createElement(ChatInput, { async onSend() { return { status: "accepted" }; }, @@ -292,9 +292,34 @@ test("renders multiple queued prompts with count and expand action", () => { }), ); - assert.match(html, /\(3\)/); + assert.match(html, />(0 of 3 done|chatInput\.queueProgress)(Show all queued prompts|Show all|chatInput\.expandQueued) { + const html = renderToStaticMarkup( + React.createElement(ChatInput, { + async onSend() { return { status: "accepted" }; }, + onAbort() {}, + isStreaming: true, + queuedMessages: { followUp: ["reply four"], steering: [] }, + queueProgress: { + epoch: "e", + revision: 3, + items: [ + { id: "1", text: "reply two", queue: "followUp", status: "done", queuedAt: 1, startedAt: 2, finishedAt: 3 }, + { id: "2", text: "reply three", queue: "followUp", status: "running", queuedAt: 1, startedAt: 3 }, + { id: "3", text: "reply four", queue: "followUp", status: "queued", queuedAt: 1 }, + ], + }, + }), + ); + + assert.match(html, />(1 of 3 done|chatInput\.queueProgress) void; queuedMessages?: QueuedMessages | null; + /** Server ledger of the current queued batch (done/running/pending/failed/cancelled). */ + queueProgress?: QueueProgressSnapshot | null; + /** Clear the finished items of the queue-progress summary for every tab. */ + onDismissQueueProgress?: () => void; inputHistory?: string[]; /** True while the advisor model is actively reviewing the running turn. */ advisorActive?: boolean; @@ -334,7 +340,7 @@ export const ChatInput = memo(forwardRef(function ChatIn onAbortCompaction, isCompacting, compactResult, thinkingLevel, onThinkingLevelChange, availableThinkingLevels, thinkingLevelMap, modelNameOverride, toolPreset, onToolPresetChange, - retryInfo, queuedMessages, inputHistory = [], onAbortRetry, + retryInfo, queuedMessages, queueProgress, onDismissQueueProgress, inputHistory = [], onAbortRetry, slashCommands, slashCommandsLoading, onLoadSlashCommands, onBuiltinCommand, onAudioUnlock, @@ -1502,16 +1508,11 @@ export const ChatInput = memo(forwardRef(function ChatIn // Enter to submit with, so this button is how touch devices steer. const primaryActionMode = primaryActionQueuesMessage && onSteer && getSubmitDuringRunBehavior() === "steer" ? "steer" : "followup"; - // ── Queued follow-up bar ──────────────────────────────────────────────── - // Texts are mirrored locally; mutations wait for native acknowledgement. - const queuedEntries = [ - ...(queuedMessages?.followUp ?? []).map((text) => ({ kind: "follow-up" as const, text })), - ...(queuedMessages?.steering ?? []).map((text) => ({ kind: "steer" as const, text })), - ]; - const firstQueued = queuedEntries[0] ?? null; - const queuedCount = queuedEntries.length; + // ── Queue panel ───────────────────────────────────────────────────────── + // The server ledger's batch, with omp's snapshot deciding what is editable; + // mutations wait for native acknowledgement. + const queuePanelItems = useMemo(() => buildQueuePanelItems(queueProgress ?? null, queuedMessages ?? null), [queueProgress, queuedMessages]); - const [queueExpanded, setQueueExpanded] = useState(false); const [queueActionPending, setQueueActionPending] = useState(false); const queueActionPendingRef = useRef(false); // Invalidate confirmation if delivery or navigation changes the queue. @@ -1519,7 +1520,7 @@ export const ChatInput = memo(forwardRef(function ChatIn && queuedDeleteTarget?.queue === queuedMessages ? queuedDeleteTarget : null; const handleQueueAction = useCallback(async ( - entry: { kind: "follow-up" | "steer"; text: string }, + entry: QueuedEntry, action: "edit" | "delete" | "steer", ) => { if (queueActionPendingRef.current || (action === "steer" && submissionBlockedRef.current)) return; @@ -1548,25 +1549,10 @@ export const ChatInput = memo(forwardRef(function ChatIn } }, [onRemoveQueuedMessage, onPromoteQueuedToSteer]); - const handleItemDelete = useCallback((entry: { kind: "follow-up" | "steer"; text: string }) => { + const handleItemDelete = useCallback((entry: QueuedEntry) => { setQueuedDeleteTarget({ ...entry, draftKey, queue: queuedMessages }); }, [draftKey, queuedMessages]); - const handleQueuedEdit = useCallback(() => { - if (!firstQueued) return; - void handleQueueAction(firstQueued, "edit"); - }, [firstQueued, handleQueueAction]); - - const handleQueuedDelete = useCallback(() => { - if (!firstQueued) return; - handleItemDelete(firstQueued); - }, [firstQueued, handleItemDelete]); - - const handleQueuedSteer = useCallback(() => { - if (!firstQueued) return; - void handleQueueAction(firstQueued, "steer"); - }, [firstQueued, handleQueueAction]); - const getNextSlashIndex = useCallback((direction: "up" | "down" | "left" | "right") => { const lastIndex = filteredSlashCommands.length - 1; if (lastIndex < 0) return 0; @@ -2581,211 +2567,18 @@ export const ChatInput = memo(forwardRef(function ChatIn ); })()} - {/* Queued prompts panel / bar — attached to composer's top edge. - When 1 item: compact single row. When multiple items: compact row with expand toggle, or full list when expanded. */} - {queuedCount > 0 && ( -
- {queuedCount === 1 ? ( -
- - {firstQueued?.kind === "steer" ? t("chatInput.queuedSteer") : t("chatInput.queuedFollowUp")} - - - {firstQueued?.text} - - - {t("chatInput.queuedEdit")} - - - {t("chatInput.queuedDelete")} - - {firstQueued?.kind === "follow-up" && ( - - {t("chatInput.queuedSteerAction")} - - )} -
- ) : ( -
-
- -
- -
-
- {queueExpanded && ( -
- {queuedEntries.map((entry, idx) => ( -
- - {entry.kind === "steer" ? t("chatInput.queuedSteer") : t("chatInput.queuedFollowUp")} - - - {entry.text} - - void handleQueueAction(entry, "edit")} title={t("chatInput.queuedEditTitle")}> - {t("chatInput.queuedEdit")} - - handleItemDelete(entry)} title={t("chatInput.queuedDeleteTitle")}> - {t("chatInput.queuedDelete")} - - {entry.kind === "follow-up" && ( - void handleQueueAction(entry, "steer")} title={t("chatInput.queuedSteerTitle")} accent> - {t("chatInput.queuedSteerAction")} - - )} -
- ))} -
- )} -
- )} -
+ {/* Queue panel — attached to composer's top edge. */} + {queuePanelItems.length > 0 && ( + )} {/* Live agent status bar — attached to composer's top edge */} {statusText && ( @@ -2795,7 +2588,7 @@ export const ChatInput = memo(forwardRef(function ChatIn style={{ border: `1px solid ${bashMode ? "var(--tool-bg)" : "color-mix(in srgb, var(--border) 70%, transparent)"}`, borderBottom: "none", - borderRadius: queuedCount > 0 ? 0 : "var(--radius-card) var(--radius-card) 0 0", + borderRadius: queuePanelItems.length > 0 ? 0 : "var(--radius-card) var(--radius-card) 0 0", background: "var(--bg-panel)", padding: "6px 14px", display: "flex", @@ -2819,7 +2612,7 @@ export const ChatInput = memo(forwardRef(function ChatIn flexDirection: "column", background: "var(--bg)", border: `1px solid ${bashMode ? "var(--tool-bg)" : "color-mix(in srgb, var(--border) 70%, transparent)"}`, - borderRadius: (queuedCount > 0 || Boolean(statusText)) ? "0 0 var(--radius-card) var(--radius-card)" : "var(--radius-card)", + borderRadius: (queuePanelItems.length > 0 || Boolean(statusText)) ? "0 0 var(--radius-card) var(--radius-card)" : "var(--radius-card)", padding: "12px 12px 10px", boxShadow: "var(--shadow-card)", } as React.CSSProperties} diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 52a5354aa..d140e70f2 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -519,7 +519,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa liveModelMeta, retryInfo, contextUsage, forkingEntryId, editingEntryId, isCompacting, compactResult, tokensPerSecond, displayModel: displayModelValue, sessionStats, - slashCommands, slashCommandsLoading, queuedMessages, advisorActive, advisorEnabled, handleAdvisorChange, + slashCommands, slashCommandsLoading, queuedMessages, queueProgress, advisorActive, advisorEnabled, handleAdvisorChange, notices, dismissNotice, extensionDialog, extensionCustomUi, extensionStatuses, extensionWidgets, respondToExtensionUi, sendExtensionCustomInput, skillDiagnostics, setSkillStartupDiagnostics, isAutoModelSelection, @@ -530,7 +530,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa sessionIdRef, messagesEndRef, scrollContainerRef, handleSend, handleAbort, handleFork, handleEdit, handleModelChange, retrySession, handleSteer, handleFollowUp, handlePromptWithStreamingBehavior, handleAbortCompaction, handleCompact, - removeQueuedMessage, promoteQueuedToSteer, + removeQueuedMessage, promoteQueuedToSteer, dismissQueueProgress, handleBuiltinSlashCommand, togglePreCompactionHistory, handleThinkingLevelChange, handleFastModeChange, handleSlowModeChange, handleCycleModel, handleCycleThinkingLevel, handleAbortRetry, loadSlashCommands, handleToolPresetChange, @@ -1103,6 +1103,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa onAdvisorChange={handleAdvisorChange} advisorModel={advisorModelMeta} queuedMessages={queuedMessages} + queueProgress={queueProgress} inputHistory={inputHistory} advisorActive={advisorActive} onCompact={handleCompact} @@ -1112,6 +1113,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa generationSpeed={generationSpeed} onRemoveQueuedMessage={removeQueuedMessage} onPromoteQueuedToSteer={promoteQueuedToSteer} + onDismissQueueProgress={dismissQueueProgress} slashCommands={slashCommands} slashCommandsLoading={slashCommandsLoading} onLoadSlashCommands={loadSlashCommands} diff --git a/components/QueueProgressPanel.test.mjs b/components/QueueProgressPanel.test.mjs new file mode 100644 index 000000000..7ea344985 --- /dev/null +++ b/components/QueueProgressPanel.test.mjs @@ -0,0 +1,103 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test, { afterEach } from "node:test"; +import React from "react"; +import { cleanup, render, screen } from "@testing-library/react/pure.js"; +import userEvent from "@testing-library/user-event"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tsconfigPaths: true }); +const { QueueProgressPanel } = await jiti.import("./QueueProgressPanel.tsx"); + +afterEach(cleanup); + +const item = (text, status, extra = {}) => ({ + id: `id-${text}`, text, queue: "followUp", status, queuedAt: 0, actionable: status === "queued", ...extra, +}); + +function panel(items, props = {}) { + const calls = []; + const view = render(React.createElement(QueueProgressPanel, { + items, + actionPending: false, + canRemove: true, + canPromote: true, + promoteBlocked: false, + onAction: (entry, action) => calls.push([action, entry.text]), + onDelete: (entry) => calls.push(["delete", entry.text]), + onDismiss: () => calls.push(["dismiss"]), + ...props, + })); + return { ...view, calls }; +} + +const statusOf = (container) => [...container.querySelectorAll("[data-queue-item]")].map((row) => `${row.textContent.match(/(two|three|four)/)?.[0]}:${row.dataset.queueItem}`); + +test("header counts done items; the list shows each status with durations and actions only for pending items", async () => { + const user = userEvent.setup(); + const items = [ + item("two", "done", { startedAt: 1_000, finishedAt: 13_000 }), + item("three", "running", { startedAt: 13_000 }), + item("four", "queued"), + ]; + const { container, calls } = panel(items); + assert.match(container.querySelector("[data-queue-progress]").textContent, /^1 of 3 done$/); + // Collapsed, the header previews the running item. + assert.equal(container.querySelectorAll("[data-queue-item]").length, 0); + assert.match(container.textContent, /three/); + assert.ok(container.querySelector('[data-queue-status="running"] .animate-spin'), "the running item spins"); + + await user.click(screen.getByRole("button", { name: /Show all queued prompts/ })); + assert.deepEqual(statusOf(container), ["two:done", "three:running", "four:queued"]); + assert.ok(screen.getByRole("img", { name: "Done" })); + assert.ok(screen.getByRole("img", { name: "Pending" })); + assert.equal(screen.getByTitle("Took 12s").textContent, "12s"); + // Edit/Delete/Steer exist for the pending item only. + assert.equal(screen.getAllByRole("button", { name: "Edit", exact: true }).length, 1); + await user.click(screen.getByRole("button", { name: "Delete", exact: true })); + await user.click(screen.getByRole("button", { name: "Steer", exact: true })); + assert.deepEqual(calls, [["delete", "four"], ["steer", "four"]]); + assert.equal(screen.queryByRole("button", { name: /Dismiss/ }), null, "no dismiss while the batch runs"); +}); + +test("failed and cancelled items are counted; a finished batch collapses to a dismissible summary", async () => { + const user = userEvent.setup(); + const running = [item("two", "done", { startedAt: 0, finishedAt: 5_000 }), item("three", "running"), item("four", "queued")]; + const { container, calls, rerender } = panel(running); + await user.click(screen.getByRole("button", { name: /Show all queued prompts/ })); + assert.equal(container.querySelectorAll("[data-queue-item]").length, 3); + + const finished = [item("two", "done", { startedAt: 0, finishedAt: 5_000 }), item("three", "failed"), item("four", "cancelled")]; + rerender(React.createElement(QueueProgressPanel, { + items: finished, actionPending: false, canRemove: true, canPromote: true, promoteBlocked: false, + onAction() {}, onDelete() {}, onDismiss: () => calls.push(["dismiss"]), + })); + assert.equal(container.querySelectorAll("[data-queue-item]").length, 0, "the summary replaces the open list"); + assert.equal(container.querySelector("[data-queue-progress]").textContent, "1 of 3 done · 1 failed · 1 cancelled"); + await user.click(screen.getByRole("button", { name: /Dismiss/ })); + assert.deepEqual(calls, [["dismiss"]]); + + // The header itself still opens the list (Dismiss replaced the Show-all text button). + await user.click(container.querySelector("button[aria-expanded]")); + assert.deepEqual(statusOf(container), ["two:done", "three:failed", "four:cancelled"]); + assert.ok(screen.getByRole("img", { name: "Failed" })); + assert.ok(screen.getByRole("img", { name: "Cancelled" })); +}); + +test("a single item shows inline: pending with its actions, finished with dismiss", () => { + const { container, rerender } = panel([item("two", "queued")]); + assert.deepEqual(statusOf(container), ["two:queued"]); + assert.ok(screen.getByRole("button", { name: "Edit", exact: true })); + rerender(React.createElement(QueueProgressPanel, { + items: [item("two", "done", { startedAt: 0, finishedAt: 2_000 })], actionPending: false, canRemove: true, canPromote: true, + promoteBlocked: false, onAction() {}, onDelete() {}, onDismiss() {}, + })); + assert.deepEqual(statusOf(container), ["two:done"]); + assert.equal(screen.queryByRole("button", { name: "Edit", exact: true }), null); + assert.ok(screen.getByRole("button", { name: /Dismiss/ })); +}); + +test("a pending item omp no longer holds cannot be edited", () => { + panel([item("two", "queued", { actionable: false })]); + assert.equal(screen.queryByRole("button", { name: "Edit", exact: true }), null); +}); diff --git a/components/QueueProgressPanel.tsx b/components/QueueProgressPanel.tsx new file mode 100644 index 000000000..198e3d8ec --- /dev/null +++ b/components/QueueProgressPanel.tsx @@ -0,0 +1,303 @@ +"use client"; + +// Composer-attached queue panel: omp's queued prompts plus the progress the +// server's ledger tracks for the current batch (lib/queue-progress.ts) — +// done items with their duration, the running item, pending items (still +// editable while omp holds them), failed and cancelled ones. + +import React, { useState } from "react"; +import { Ban, Check, ChevronDown, Circle, CircleAlert, Loader2, X } from "lucide-react"; +import { useI18n } from "@/lib/i18n"; +import type { QueuePanelItem, QueueProgressStatus } from "@/lib/queue-progress"; +import { formatDuration } from "@/lib/subagent-format"; +import { QueuedActionButton } from "./ChatInput-banners"; + +export interface QueuedEntry { + kind: "follow-up" | "steer"; + text: string; +} + +interface QueueProgressPanelProps { + items: QueuePanelItem[]; + /** A queue mutation is awaiting omp's answer. */ + actionPending: boolean; + canRemove: boolean; + canPromote: boolean; + /** Steering is refused right now (e.g. a dictation is still submitting). */ + promoteBlocked: boolean; + onAction: (entry: QueuedEntry, action: "edit" | "steer") => void; + onDelete: (entry: QueuedEntry) => void; + onDismiss?: () => void; +} + +const STATUS_COLORS: Record = { + queued: "var(--text-dim)", + running: "var(--accent)", + done: "var(--status-success)", + failed: "var(--status-error)", + cancelled: "var(--text-dim)", +}; + +function StatusIcon({ status, label }: { status: QueueProgressStatus; label: string }) { + const props = { size: 12, strokeWidth: 2, "aria-hidden": true as const }; + return ( + + {status === "running" ? + : status === "done" ? + : status === "failed" ? + : status === "cancelled" ? + : } + + ); +} + +export function QueueProgressPanel({ + items, actionPending, canRemove, canPromote, promoteBlocked, onAction, onDelete, onDismiss, +}: QueueProgressPanelProps) { + const { t } = useI18n(); + const finished = items.every((item) => item.status !== "queued" && item.status !== "running"); + // The list starts collapsed and folds back into the summary once every item + // has finished (state derived from the previous render, not an effect). + const [view, setView] = useState({ expanded: false, finished }); + if (view.finished !== finished) setView({ expanded: finished ? false : view.expanded, finished }); + const expanded = view.expanded; + const toggle = () => setView((current) => ({ ...current, expanded: !current.expanded })); + + const count = (status: QueueProgressStatus) => items.filter((item) => item.status === status).length; + const failed = count("failed"); + const cancelled = count("cancelled"); + const statusLabel = (status: QueueProgressStatus) => t(`chatInput.queueStatus.${status}`); + const current = items.find((item) => item.status === "running") ?? items.find((item) => item.status === "queued"); + + const renderItem = (item: QueuePanelItem) => { + const entry: QueuedEntry = { kind: item.queue === "steering" ? "steer" : "follow-up", text: item.text }; + const duration = item.status === "done" && item.startedAt !== undefined && item.finishedAt !== undefined + ? formatDuration(item.finishedAt - item.startedAt) + : null; + const steer = entry.kind === "steer"; + return ( +
+ + + {steer ? t("chatInput.queuedSteer") : t("chatInput.queuedFollowUp")} + + + {item.text} + + {duration && ( + + {duration} + + )} + {item.status === "queued" && item.actionable && ( + <> + onAction(entry, "edit")} title={t("chatInput.queuedEditTitle")}> + {t("chatInput.queuedEdit")} + + onDelete(entry)} title={t("chatInput.queuedDeleteTitle")}> + {t("chatInput.queuedDelete")} + + {!steer && ( + onAction(entry, "steer")} title={t("chatInput.queuedSteerTitle")} accent> + {t("chatInput.queuedSteerAction")} + + )} + + )} +
+ ); + }; + + const dismissButton = finished && onDismiss && ( + + ); + + return ( +
+ {items.length === 1 ? ( +
+
{renderItem(items[0])}
+ {dismissButton} +
+ ) : ( + <> +
+ + {dismissButton || ( + + )} +
+ {expanded && ( +
+ {items.map(renderItem)} +
+ )} + + )} +
+ ); +} diff --git a/hooks/useAgentSession-queue.ts b/hooks/useAgentSession-queue.ts index 2207d2a2c..5e31bff6a 100644 --- a/hooks/useAgentSession-queue.ts +++ b/hooks/useAgentSession-queue.ts @@ -7,14 +7,6 @@ export type { QueuedMessages }; export const EMPTY_QUEUE: QueuedMessages = { steering: [], followUp: [] }; -/** Parse a queue snapshot from an RPC frame or state; null when absent. */ -export function readQueueSnapshot(value: unknown): QueuedMessages | null { - if (!value || typeof value !== "object" || !("steering" in value) || !("followUp" in value)) return null; - const [steering, followUp] = [value.steering, value.followUp].map((list) => - Array.isArray(list) ? list.filter((item): item is string => typeof item === "string") : []); - return { steering, followUp }; -} - /** * `lib/rpc-manager.ts` answers a prompt/steer with this when a `!!` shell * command owned the session: it forwarded the message into omp's follow-up diff --git a/hooks/useAgentSession-stream.ts b/hooks/useAgentSession-stream.ts index 3ede5b416..817ee518e 100644 --- a/hooks/useAgentSession-stream.ts +++ b/hooks/useAgentSession-stream.ts @@ -200,6 +200,8 @@ export type AgentStateResponse = { extensionStatuses?: ExtensionStatusItem[]; extensionWidgets?: ExtensionWidgetItem[]; queuedMessages?: QueuedMessages; + /** Untrusted until parsed by readQueueProgressSnapshot. */ + queueProgress?: unknown; /** Untrusted until parsed by parseSkillDiagnosticsSnapshot. */ skillDiagnostics?: unknown; todoPhases?: TodoPhase[]; diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index d6ab9f8e8..09fa28d69 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -4747,6 +4747,48 @@ test("a state snapshot requested before a newer skill update cannot overwrite it assert.deepEqual(w.latest.skillDiagnostics, newer, "the late older snapshot is dropped"); }); +test("a state snapshot requested before a newer queue_progress frame cannot replace it with another ledger or none", async () => { + const ledger = (epoch, revision, text) => ({ epoch, revision, items: [{ id: `${epoch}-${revision}`, text, queue: "followUp", status: "queued", queuedAt: 1 }] }); + for (const stale of [{ running: true, state: { queueProgress: ledger("old-process", 9, "stale") } }, { running: false }]) { + resetWorld(); + primeSession("queue-order", [userMsg("u0", "q")]); + world.agents.set("queue-order", { running: true, state: { queueProgress: ledger("old-process", 1, "startup") } }); + const w = await mountSession("queue-order"); + assert.equal(w.latest.queueProgress?.epoch, "old-process"); + + let release; + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/agent/queue-order", + produce: () => new Promise((resolve) => { release = () => resolve({ value: stale }); }), + }); + const newer = ledger("new-process", 1, "fresh"); + try { + await act(async () => { + lastEs().open(); // stream attachment requests an authoritative state snapshot + await sleep(20); + }); + assert.ok(release, "precondition: the snapshot request is still in flight"); + await act(() => lastEs().emit({ type: "queue_progress", ...newer })); + assert.deepEqual(w.latest.queueProgress, newer); + } finally { + release?.(); + } + await act(async () => { + await sleep(30); + }); + assert.deepEqual(w.latest.queueProgress, newer, "the late older snapshot is dropped"); + + // A same-ledger snapshot still orders by revision, whenever it was requested. + world.agents.set("queue-order", { running: true, state: { queueProgress: ledger("new-process", 2, "next") } }); + await act(async () => { + await w.latest.retrySession(); + await sleep(30); + }); + assert.equal(w.latest.queueProgress?.revision, 2); + w.unmount(); + } +}); + test("a fresh chat hydrates and follows skill diagnostics after slash discovery creates its runtime", async () => { resetWorld(); const startup = skillDiagnosticsSnapshot(true, "fresh-startup"); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index a2f8aa6f6..0514f7d3e 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -36,6 +36,7 @@ import { subscribeSessionsChanged } from "@/lib/session-change-bus"; import { EVENT_STREAM_CLOSED, EVENT_STREAM_OPEN, openEventStream, type EventStream } from "@/lib/event-stream"; import { createSessionCatchUp, type SessionCatchUp, type SessionLiveFields } from "./useAgentSession-sync"; import type { SessionLiveSnapshot } from "@/lib/session-sync"; +import { readQueueProgressSnapshot, readQueueSnapshot, type QueueProgressSnapshot } from "@/lib/queue-progress"; import { mergeSubagentRoster, parseSubagentActivityEvent, @@ -53,7 +54,7 @@ import { export type { SubagentInfo } from "@/lib/subagent-types"; // Pure helpers extracted to sibling modules (extraction only — no logic changes). -import { EMPTY_QUEUE, isQueuedWhileShellRunning, readQueueSnapshot } from "./useAgentSession-queue"; +import { EMPTY_QUEUE, isQueuedWhileShellRunning } from "./useAgentSession-queue"; import type { QueuedMessages } from "./useAgentSession-queue"; import { NOTICE_ERROR_VISIBLE_MS, @@ -354,6 +355,27 @@ export function useAgentSession(opts: UseAgentSessionOptions) { queueAppliedSeqRef.current = seq; updateQueuedMessages(readQueueSnapshot(value) ?? EMPTY_QUEUE); }, [updateQueuedMessages]); + // The server's ledger of the current queued batch. Ordered by its own + // revision within one ledger (epoch): HTTP snapshots and SSE frames can + // arrive in any order. Absent (no live process) clears it. + const [queueProgress, setQueueProgress] = useState(null); + const queueProgressRef = useRef(null); + // `queue_progress` frames received so far. An HTTP snapshot carries the + // count read before its request: revisions cannot order a different ledger + // (a replaced process) or none against a frame that arrived meanwhile. + const queueProgressFramesRef = useRef(0); + const applyQueueProgress = useCallback((value: unknown, framesBeforeRequest?: number) => { + const next = readQueueProgressSnapshot(value); + const current = queueProgressRef.current; + if (next && current && next.epoch === current.epoch) { + if (next.revision <= current.revision) return; + } else if (framesBeforeRequest !== undefined && framesBeforeRequest !== queueProgressFramesRef.current) { + return; + } + if (!next && !current) return; + queueProgressRef.current = next; + setQueueProgress(next); + }, []); // Orders get_state responses, the setter reply, and SSE updates so a response // started before a newer frame cannot overwrite it. const skillDiagnosticsSeqRef = useRef(0); @@ -879,6 +901,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // sync that started while this request was in flight. const token = beginAuthoritativeModelSync(); const queueRevision = ++queueSeqRef.current; + const queueProgressFrames = queueProgressFramesRef.current; const skillDiagnosticsRevision = ++skillDiagnosticsSeqRef.current; const stateRes = await fetch(`/api/sessions/${encodeURIComponent(sid)}/state`); if (!stateRes.ok) throw new Error(`HTTP ${stateRes.status}`); @@ -918,9 +941,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (liveState.extensionWidgets !== undefined) setExtensionWidgets(liveState.extensionWidgets ?? []); if (liveState.todoPhases !== undefined) setTodoPhases(liveState.todoPhases ?? []); applyQueueStateSnapshot(queueRevision, liveState.queuedMessages); + applyQueueProgress(liveState.queueProgress, queueProgressFrames); } else if (!agentState.running) { setSlowModeSupported(undefined); applyQueueStateSnapshot(queueRevision, null); + applyQueueProgress(null, queueProgressFrames); } if (showLoading) setLoading(false); return { context: d.context, agentState }; @@ -945,7 +970,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, applyQueueStateSnapshot, applyQueueProgress, applySkillDiagnosticsSnapshot]); const loadContext = useCallback(async (sid: string, leafId: string | null, includePreCompaction = false): Promise => { const seq = ++contextRequestSeqRef.current; @@ -1127,17 +1152,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const refreshAgentSnapshots = useCallback(async (sid: string) => { const queueRevision = ++queueSeqRef.current; + const queueProgressFrames = queueProgressFramesRef.current; const skillDiagnosticsRevision = ++skillDiagnosticsSeqRef.current; try { const res = await fetch(`/api/agent/${encodeURIComponent(sid)}`); if (!res.ok || !hookAliveRef.current || sessionIdRef.current !== sid) return; const data = await res.json() as { state?: AgentStateResponse }; applyQueueStateSnapshot(queueRevision, data.state?.queuedMessages); + applyQueueProgress(data.state?.queueProgress, queueProgressFrames); applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, data.state?.skillDiagnostics); } catch { // The next live update or state snapshot heals these views. } - }, [applyQueueStateSnapshot, applySkillDiagnosticsSnapshot]); + }, [applyQueueStateSnapshot, applyQueueProgress, applySkillDiagnosticsSnapshot]); const connectEvents = useCallback((sid: string, restoreWrapper = false): Promise => { // An awaited RPC can finish after its chat unmounted. No continuation may @@ -1757,6 +1784,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (token === null) return; try { const queueRevision = ++queueSeqRef.current; + const queueProgressFrames = queueProgressFramesRef.current; const skillDiagnosticsRevision = ++skillDiagnosticsSeqRef.current; const res = await fetch(`/api/agent/${encodeURIComponent(sid)}`); if (!res.ok) return; @@ -1779,6 +1807,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // And the only reliable re-sync for a missed subagent lifecycle frame. void refreshSubagentRoster(sid); applyQueueStateSnapshot(queueRevision, state?.queuedMessages); + applyQueueProgress(state?.queueProgress, queueProgressFrames); const busy = data.running && state && (state.isStreaming || state.isPromptRunning || state.isCompacting); // Mid-run, not after it: context usage grows with every token and the @@ -1807,7 +1836,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { void reconcileAgentState(sid); } } - }, [applyQueueStateSnapshot, applySkillDiagnosticsSnapshot, finishPromptWithoutStream, refreshSubagentRoster]); + }, [applyQueueStateSnapshot, applyQueueProgress, applySkillDiagnosticsSnapshot, finishPromptWithoutStream, refreshSubagentRoster]); // Recovery net for missed SSE events: while the agent is running, verify // against the server periodically and whenever the tab returns to the @@ -1979,6 +2008,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [addNotice]); + /** Clear the finished queue-progress items for every tab on the session; + * the panel follows the server's next `queue_progress` frame. */ + const dismissQueueProgress = useCallback(async () => { + const sid = sessionIdRef.current; + if (!hookAliveRef.current || !sid) return; + try { + await sendAgentCommand(sid, { type: "dismiss_queue_progress" }); + } catch (error) { + if (!hookAliveRef.current || sessionIdRef.current !== sid) return; + addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); + } + }, [addNotice]); + const handleAgentEvent = useCallback((event: AgentEvent) => { switch (event.type) { case "session_history_changed": { @@ -2005,6 +2047,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { applySkillDiagnosticsSnapshot(revision, event.data); break; } + case "queue_progress": + queueProgressFramesRef.current += 1; + applyQueueProgress(event); + break; case "queue_update": { const snapshot = readQueueSnapshot(event); if (snapshot) { @@ -2101,6 +2147,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { void loadSession(endedSid, false, false, endedRunId); const endToken = beginAuthoritativeModelSync(); const queueRevision = ++queueSeqRef.current; + const queueProgressFrames = queueProgressFramesRef.current; const skillDiagnosticsRevision = ++skillDiagnosticsSeqRef.current; fetch(`/api/agent/${encodeURIComponent(endedSid)}`) .then((r) => (r.ok ? r.json() as Promise<{ state?: AgentStateResponse }> : null)) @@ -2111,6 +2158,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // The queue does not depend on a model: an exited wrapper still // means nothing is queued. applyQueueStateSnapshot(queueRevision, d.state?.queuedMessages); + applyQueueProgress(d.state?.queueProgress, queueProgressFrames); applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, d.state?.skillDiagnostics); if (!d.state?.model) return; const applied = applyAuthoritativeModel(toThinkingModelMeta(d.state.model), endToken); @@ -2587,7 +2635,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { handleExtensionUiRequest(event as unknown as IncomingExtensionUiRequest); break; } -}, [addNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot]); +}, [addNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot, applyQueueProgress]); handleAgentEventRef.current = handleAgentEvent; syncActionsRef.current = { metadata: (context, version, hasLive = liveModelMeta !== null || currentModelOverride !== null) => { @@ -4095,7 +4143,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { liveModelMeta, retryInfo, contextUsage, systemPrompt, skillDiagnostics, forkingEntryId, editingEntryId, isCompacting, compactError, compactResult, tokensPerSecond, currentModel, displayModel, isAutoModelSelection: !displayModel, sessionStats, agentPhase, - slashCommands, slashCommandsLoading, queuedMessages, + slashCommands, slashCommandsLoading, queuedMessages, queueProgress, notices: noticeState.visible, dismissNotice, extensionDialog, extensionCustomUi, extensionStatuses, extensionWidgets, respondToExtensionUi, sendExtensionCustomInput, advisorActive: advisorActiveAt > 0, advisorEnabled, handleAdvisorChange, subagents, subagentEvents, subagentTranscriptVersions, activeSubagentCount, currentTodoPhase, todoPhases, @@ -4109,7 +4157,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { retrySession: () => { const sid = sessionIdRef.current; if (sid) void loadSession(sid, true, true); }, handleCompact, handleHandoff, handleSteer, handleFollowUp, handlePromptWithStreamingBehavior, handleAbortCompaction, handleBuiltinSlashCommand, togglePreCompactionHistory, - handleToolPresetChange, handleThinkingLevelChange, loadSlashCommands, removeQueuedMessage, promoteQueuedToSteer, setActiveLeafId, setData, setMessages, + handleToolPresetChange, handleThinkingLevelChange, loadSlashCommands, removeQueuedMessage, promoteQueuedToSteer, dismissQueueProgress, setActiveLeafId, setData, setMessages, dispatch, setAgentRunning, setForkingEntryId, btw, askBtw, bashRunning, pendingBash, diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 1ad043f14..7cf8287eb 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -435,6 +435,17 @@ "chatInput.queuedPrompts": "Queued prompts", "chatInput.expandQueued": "Show all queued prompts", "chatInput.collapseQueued": "Collapse queued prompts", + "chatInput.queueProgress": "{done} of {total} done", + "chatInput.queueFailedCount": "{count} failed", + "chatInput.queueCancelledCount": "{count} cancelled", + "chatInput.queueStatus.queued": "Pending", + "chatInput.queueStatus.running": "Running", + "chatInput.queueStatus.done": "Done", + "chatInput.queueStatus.failed": "Failed", + "chatInput.queueStatus.cancelled": "Cancelled", + "chatInput.queueDurationTitle": "Took {duration}", + "chatInput.queueDismiss": "Dismiss", + "chatInput.queueDismissTitle": "Clear the finished queued prompts", "chatInput.settings": "Settings", "chatInput.changeModel": "Change model", "chatInput.modelsLabel": "Models", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index af23a236a..3b5ce1b2d 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -418,6 +418,17 @@ "chatInput.queuedPrompts": "キュー内のプロンプト", "chatInput.expandQueued": "すべてのキューを表示", "chatInput.collapseQueued": "キューを折りたたむ", + "chatInput.queueProgress": "{total} 件中 {done} 件完了", + "chatInput.queueFailedCount": "{count} 件失敗", + "chatInput.queueCancelledCount": "{count} 件キャンセル", + "chatInput.queueStatus.queued": "待機中", + "chatInput.queueStatus.running": "実行中", + "chatInput.queueStatus.done": "完了", + "chatInput.queueStatus.failed": "失敗", + "chatInput.queueStatus.cancelled": "キャンセル済み", + "chatInput.queueDurationTitle": "所要時間 {duration}", + "chatInput.queueDismiss": "閉じる", + "chatInput.queueDismissTitle": "完了したキューのプロンプトを消去", "chatInput.settings": "設定", "chatInput.changeModel": "モデルを変更", "chatInput.modelsLabel": "モデル", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 75878b912..b508a630d 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -418,6 +418,17 @@ "chatInput.queuedPrompts": "排队的提示词", "chatInput.expandQueued": "展开所有排队提示词", "chatInput.collapseQueued": "折叠排队提示词", + "chatInput.queueProgress": "已完成 {done}/{total}", + "chatInput.queueFailedCount": "{count} 条失败", + "chatInput.queueCancelledCount": "{count} 条已取消", + "chatInput.queueStatus.queued": "等待中", + "chatInput.queueStatus.running": "运行中", + "chatInput.queueStatus.done": "已完成", + "chatInput.queueStatus.failed": "失败", + "chatInput.queueStatus.cancelled": "已取消", + "chatInput.queueDurationTitle": "耗时 {duration}", + "chatInput.queueDismiss": "关闭", + "chatInput.queueDismissTitle": "清除已结束的排队提示词", "chatInput.settings": "设置", "chatInput.changeModel": "切换模型", "chatInput.modelsLabel": "模型", diff --git a/lib/pi-types.ts b/lib/pi-types.ts index f3a7dca25..4980e3373 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -1,4 +1,5 @@ import type { SkillDiagnosticsSnapshot } from "./skill-diagnostics"; +import type { QueueProgressSnapshot } from "./queue-progress"; // Local mirrors of the omp shapes used by omp-web. omp's SDK packages are // Bun-only, so these types are hand-maintained against @@ -126,6 +127,8 @@ export interface WebSessionState { messageCount: number; queuedMessageCount: number; queuedMessages: QueuedMessages; + /** omp-web's ledger of the current batch of queued prompts (lib/queue-progress.ts). */ + queueProgress: QueueProgressSnapshot; contextUsage: ContextUsage | null; systemPrompt: string; thinkingLevel: string; diff --git a/lib/queue-progress.test.mjs b/lib/queue-progress.test.mjs new file mode 100644 index 000000000..6910109df --- /dev/null +++ b/lib/queue-progress.test.mjs @@ -0,0 +1,334 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); +const { + QueueProgressLedger, + alignQueue, + buildQueuePanelItems, + queuedTextOfUserMessage, + readQueueProgressSnapshot, + runOutcomeOfAgentEnd, +} = await jiti.import("./queue-progress.ts"); + +function ledger() { + let next = 0; + return new QueueProgressLedger({ epoch: "epoch-1", createId: () => `q${++next}` }); +} +const queue = (followUp = [], steering = []) => ({ steering, followUp }); +const view = (l) => l.snapshot().items.map(({ id, text, queue: name, status }) => ({ id, text, queue: name, status })); +const statuses = (l) => l.snapshot().items.map((item) => `${item.text}:${item.status}`); + +test("one-at-a-time follow-ups run queued → running → done in order (omp's frame order)", () => { + const l = ledger(); + // While the first prompt runs, three follow-ups are queued. + l.observeQueue(queue(["two"]), 10); + l.observeQueue(queue(["two", "three"]), 11); + l.observeQueue(queue(["two", "three", "four"]), 12); + assert.deepEqual(statuses(l), ["two:queued", "three:queued", "four:queued"]); + + // omp drops the head from the snapshot, then starts a turn with it. + l.observeQueue(queue(["three", "four"]), 20); + l.observeTurnStart(); + l.observeUserMessage("two", 21); + assert.deepEqual(statuses(l), ["two:running", "three:queued", "four:queued"]); + + l.observeQueue(queue(["four"]), 30); + l.observeTurnStart(); + l.observeUserMessage("three", 31); + assert.deepEqual(statuses(l), ["two:done", "three:running", "four:queued"]); + const two = l.snapshot().items[0]; + assert.equal(two.startedAt, 21); + assert.equal(two.finishedAt, 31); + + l.observeQueue(queue([]), 40); + l.observeTurnStart(); + l.observeUserMessage("four", 41); + l.observeRunEnd("completed", 50); + assert.deepEqual(statuses(l), ["two:done", "three:done", "four:done"]); + assert.deepEqual(l.snapshot().items.map((item) => [item.startedAt, item.finishedAt]), [[21, 31], [31, 41], [41, 50]]); +}); + +test('"all" mode starts every delivered follow-up together and finishes them with the run', () => { + const l = ledger(); + l.observeQueue(queue(["a", "b"]), 1); + l.observeQueue(queue([]), 2); + l.observeTurnStart(); + l.observeUserMessage("a", 3); + l.observeUserMessage("b", 3); + assert.deepEqual(statuses(l), ["a:running", "b:running"], "a second delivery in the same turn does not finish the first"); + l.observeRunEnd("completed", 9); + assert.deepEqual(statuses(l), ["a:done", "b:done"]); +}); + +test("identical texts are told apart deterministically by order", () => { + const l = ledger(); + l.observeQueue(queue(["same"]), 1); + l.observeQueue(queue(["same", "same"]), 2); + const [first, second] = view(l); + assert.notEqual(first.id, second.id); + + // Delivery takes the head: the earlier item runs, the later stays queued. + l.observeQueue(queue(["same"]), 3); + l.observeTurnStart(); + l.observeUserMessage("same", 4); + assert.deepEqual(view(l), [{ ...first, status: "running" }, { ...second, status: "queued" }]); + + l.observeQueue(queue([]), 5); + l.observeTurnStart(); + l.observeUserMessage("same", 6); + assert.deepEqual(view(l), [{ ...first, status: "done" }, { ...second, status: "running" }]); + assert.deepEqual(alignQueue(["x", "x"], ["x"]), [-1, 0], "the earliest duplicate is the one that left"); +}); + +test("a steer joins the running turn; the next follow-up finishes both", () => { + const l = ledger(); + l.observeQueue(queue(["later"]), 1); + l.observeQueue(queue(["later"], ["steer now"]), 2); + l.observeQueue(queue(["later"]), 3); + l.observeTurnStart(); + l.observeUserMessage("steer now", 4); + assert.deepEqual(statuses(l), ["steer now:running", "later:queued"]); + + // Steering never completes earlier work: the agent is still on it. + l.observeQueue(queue(["later"], ["more"]), 5); + l.observeQueue(queue(["later"]), 6); + l.observeTurnStart(); + l.observeUserMessage("more", 7); + assert.deepEqual(statuses(l), ["steer now:running", "more:running", "later:queued"]); + + l.observeQueue(queue([]), 8); + l.observeTurnStart(); + l.observeUserMessage("later", 9); + assert.deepEqual(statuses(l), ["steer now:done", "more:done", "later:running"]); +}); + +test("live steering recorded before its snapshot still matches the queued item", () => { + const l = ledger(); + l.observeQueue(queue([], ["now"]), 1); + l.observeUserMessage("now", 2); + l.observeQueue(queue([]), 3); + assert.deepEqual(statuses(l), ["now:running"]); +}); + +test("an aborted or failed run marks its items failed and drops what it took unrecorded", () => { + const aborted = ledger(); + aborted.observeQueue(queue(["a", "b", "c"]), 1); + aborted.observeQueue(queue(["b", "c"]), 2); + aborted.observeTurnStart(); + aborted.observeUserMessage("a", 3); + aborted.observeQueue(queue(["c"]), 4); // taken for the next call, never recorded + aborted.observeRunEnd(runOutcomeOfAgentEnd({ messages: [{ role: "assistant", stopReason: "aborted" }] }), 5); + assert.deepEqual(statuses(aborted), ["a:failed", "c:queued", "b:cancelled"], "a plain abort keeps omp's pending queue"); + + const failed = ledger(); + failed.observeQueue(queue(["a"]), 1); + failed.observeQueue(queue([]), 2); + failed.observeTurnStart(); + failed.observeUserMessage("a", 3); + failed.observeRunEnd(runOutcomeOfAgentEnd({ messages: [{ role: "assistant", stopReason: "error" }, { role: "toolResult" }] }), 4); + assert.deepEqual(statuses(failed), ["a:failed"]); + assert.equal(runOutcomeOfAgentEnd({ messages: [{ role: "assistant", stopReason: "stop" }] }), "completed"); + assert.equal(runOutcomeOfAgentEnd({ messages: [] }), "completed"); +}); + +test("remove_queued_message marks the removed item cancelled, before or after its snapshot", () => { + // omp's order: the snapshot drops it, then the reply confirms. + const l = ledger(); + l.observeQueue(queue(["dup", "dup"]), 1); + const [first, second] = view(l); + l.observeQueue(queue(["dup"]), 2); + assert.equal(l.observeRemoval("dup", "followUp", 3), true); + assert.deepEqual(view(l), [{ ...second, status: "queued" }, { ...first, status: "cancelled" }], "omp removes the first match"); + + // A reply that overtakes the snapshot still cancels exactly one. + const early = ledger(); + early.observeQueue(queue(["x", "y"]), 1); + early.observeRemoval("y", "followUp", 2); + early.observeQueue(queue(["x"]), 3); + assert.deepEqual(statuses(early), ["x:queued", "y:cancelled"]); + assert.equal(early.observeRemoval("missing", "followUp", 4), false); +}); + +test("a removal confirmed after a later delivery or the run's end still cancels the removed item", () => { + // The later prompt's user message is handled before the removal reply + // (one stdout read): the removed item is first inferred to run with it. + const l = ledger(); + l.observeQueue(queue(["removed", "next"]), 1); + l.observeQueue(queue(["next"]), 2); // omp removed it + l.observeQueue(queue([]), 3); // omp took "next" + l.observeTurnStart(); + l.observeUserMessage("next", 4); + assert.deepEqual(statuses(l), ["removed:running", "next:running"]); + assert.equal(l.observeRemoval("removed", "followUp", 5), true); + assert.deepEqual(statuses(l), ["next:running", "removed:cancelled"]); + assert.equal(l.snapshot().items[1].startedAt, undefined, "it never started"); + l.observeRunEnd("completed", 6); + assert.deepEqual(statuses(l), ["next:done", "removed:cancelled"]); + + // The run ended before the reply: the run's outcome was only inferred. + const ended = ledger(); + ended.observeQueue(queue(["removed"]), 1); + ended.observeQueue(queue([]), 2); + ended.observeRunEnd("completed", 3); + assert.deepEqual(statuses(ended), ["removed:done"]); + assert.equal(ended.observeRemoval("removed", "followUp", 4), true); + assert.deepEqual(statuses(ended), ["removed:cancelled"]); + + // An item that ran under its own transcript message is never undone. + const ran = ledger(); + ran.observeQueue(queue(["x"]), 1); + ran.observeQueue(queue([]), 2); + ran.observeTurnStart(); + ran.observeUserMessage("x", 3); + assert.equal(ran.observeRemoval("x", "followUp", 4), false); + assert.deepEqual(statuses(ran), ["x:running"]); +}); + +test("abort_and_restore_queue cancels everything still queued", () => { + const l = ledger(); + l.observeQueue(queue(["a", "b"], ["s"]), 1); + l.observeQueue(queue(["b"], ["s"]), 2); + l.observeTurnStart(); + l.observeUserMessage("a", 3); + // omp withdraws the queue, the run ends aborted, then the command answers. + l.observeQueue(queue([]), 4); + l.observeRunEnd("aborted", 5); + l.observeAbort({ restoreQueue: true, boundary: l.boundary() }, 6); + assert.deepEqual(statuses(l), ["a:failed", "s:cancelled", "b:cancelled"]); + + // While idle there is no agent_end: the reply alone settles the queue. + const idle = ledger(); + idle.observeQueue(queue(["x"]), 1); + idle.observeAbort({ restoreQueue: true, boundary: idle.boundary() }, 2); + idle.observeQueue(queue([]), 3); + assert.deepEqual(statuses(idle), ["x:cancelled"]); +}); + +test("an abort settles only what was queued before it was sent", () => { + const l = ledger(); + l.observeQueue(queue(["old"]), 1); + const boundary = l.boundary(); + // omp withdraws "old"; a prompt queued after the abort reaches the ledger + // before omp-web handles the abort's reply. + l.observeQueue(queue([]), 2); + l.observeQueue(queue(["new"]), 3); + l.observeAbort({ restoreQueue: true, boundary }, 4); + assert.deepEqual(statuses(l), ["new:queued", "old:cancelled"]); +}); + +test("promotion moves a follow-up into steering without losing its identity", () => { + const l = ledger(); + l.observeQueue(queue(["a", "b"]), 1); + const [a, b] = view(l); + l.observeQueue(queue(["a"], ["b"]), 2); + assert.deepEqual(view(l), [{ ...b, queue: "steering" }, a], "steering drains first"); +}); + +test("a rewritten delivery (slash command) still completes, and earlier departures run with the next match", () => { + const l = ledger(); + l.observeQueue(queue(["/skill:x go", "plain"]), 1); + l.observeQueue(queue(["plain"]), 2); + l.observeTurnStart(); + l.observeUserMessage("expanded skill text", 3); // no match: stays pending + assert.deepEqual(statuses(l), ["/skill:x go:queued", "plain:queued"]); + l.observeRunEnd("completed", 4); + assert.deepEqual(statuses(l), ["/skill:x go:done", "plain:queued"]); +}); + +test("a matched later prompt starts earlier departed items alongside it", () => { + const l = ledger(); + l.observeQueue(queue(["/skill:x go", "plain"]), 1); + l.observeQueue(queue([]), 2); + l.observeTurnStart(); + l.observeUserMessage("plain", 3); + assert.deepEqual(statuses(l), ["/skill:x go:running", "plain:running"]); +}); + +test("a new batch clears finished items; dismiss clears them on demand", () => { + const l = ledger(); + l.observeQueue(queue(["a"]), 1); + l.observeQueue(queue([]), 2); + l.observeTurnStart(); + l.observeUserMessage("a", 3); + l.observeRunEnd("completed", 4); + assert.deepEqual(statuses(l), ["a:done"]); + l.observeQueue(queue(["b"]), 5); + assert.deepEqual(statuses(l), ["b:queued"], "the previous batch was finished"); + + const revision = l.snapshot().revision; + assert.equal(l.dismissFinished(), false, "nothing finished to dismiss"); + assert.equal(l.snapshot().revision, revision, "no-op changes keep the revision"); + l.observeQueue(queue([]), 6); + l.observeTurnStart(); + l.observeUserMessage("b", 7); + l.observeRunEnd("completed", 8); + assert.equal(l.dismissFinished(), true); + assert.deepEqual(l.snapshot().items, []); + assert.ok(l.snapshot().revision > revision); + assert.equal(l.reset(), false); +}); + +test("an unrelated user prompt never touches the ledger", () => { + const l = ledger(); + l.observeQueue(queue(["queued"]), 1); + assert.equal(l.observeUserMessage("something else", 2), false); + assert.deepEqual(statuses(l), ["queued:queued"]); +}); + +test("user message text mirrors omp's queue-chip text", () => { + assert.equal(queuedTextOfUserMessage({ role: "user", content: "hi" }), "hi"); + assert.equal(queuedTextOfUserMessage({ role: "user", content: [{ type: "text", text: "a" }, { type: "image" }, { type: "text", text: "b" }] }), "a\nb"); + assert.equal(queuedTextOfUserMessage({ role: "user", content: [{ type: "image" }] }), "[Image]"); + assert.equal(queuedTextOfUserMessage({ role: "user", attribution: "agent", content: "handoff" }), null); + assert.equal(queuedTextOfUserMessage({ role: "assistant", content: "x" }), null); + assert.equal(queuedTextOfUserMessage({ role: "custom", content: "notice" }), null); +}); + +test("panel items: omp's snapshot decides what is editable and fills in chips the ledger has not reported", () => { + const l = ledger(); + l.observeQueue(queue(["a", "b"]), 1); + l.observeQueue(queue(["b"]), 2); // a left the queue, not yet in the transcript + const items = buildQueuePanelItems(l.snapshot(), queue(["b", "c"])); + assert.deepEqual(items.map((item) => [item.text, item.status, item.actionable]), [ + ["a", "queued", false], + ["b", "queued", true], + ["c", "queued", true], + ]); + assert.deepEqual(buildQueuePanelItems(null, null), []); +}); + +test("panel items: only the first of identical pending items is actionable, and a departed one claims no chip", () => { + // omp acts on the first match: with [A, X, A] only the first A may be edited. + const l = ledger(); + l.observeQueue(queue(["A", "X", "A"]), 1); + assert.deepEqual(buildQueuePanelItems(l.snapshot(), queue(["A", "X", "A"])).map((item) => [item.text, item.actionable]), [ + ["A", true], + ["X", true], + ["A", false], + ]); + // Chips the ledger has not reported follow the same rule. + assert.deepEqual(buildQueuePanelItems(null, queue(["B", "B"])).map((item) => [item.text, item.actionable]), [["B", true], ["B", false]]); + + // omp took the first of two identical follow-ups; its transcript message has not arrived. + const taken = ledger(); + taken.observeQueue(queue(["dup", "dup"]), 1); + taken.observeQueue(queue(["dup"]), 2); + const snapshot = taken.snapshot(); + assert.deepEqual(snapshot.items.map((item) => item.departed), [true, undefined]); + assert.deepEqual(readQueueProgressSnapshot(snapshot), snapshot, "the departed flag survives the wire"); + assert.deepEqual(buildQueuePanelItems(snapshot, queue(["dup"])).map((item) => [item.id, item.actionable]), [ + [snapshot.items[0].id, false], + [snapshot.items[1].id, true], + ]); +}); + +test("snapshots parse defensively", () => { + const l = ledger(); + l.observeQueue(queue(["a"]), 1); + assert.deepEqual(readQueueProgressSnapshot({ type: "queue_progress", ...l.snapshot() }), l.snapshot()); + assert.equal(readQueueProgressSnapshot(null), null); + assert.equal(readQueueProgressSnapshot({ epoch: "e", revision: "1", items: [] }), null); + assert.deepEqual(readQueueProgressSnapshot({ epoch: "e", revision: 1, items: [{ id: "x", text: "t", queue: "nope", status: "done", queuedAt: 1 }] }).items, []); +}); diff --git a/lib/queue-progress.ts b/lib/queue-progress.ts new file mode 100644 index 000000000..13cdc8410 --- /dev/null +++ b/lib/queue-progress.ts @@ -0,0 +1,467 @@ +// Per-session ledger of queued prompts and how far omp got with each one. +// +// omp's queue snapshots (`queue_update`, `get_state.queuedMessages`) list only +// what is still waiting: an item silently vanishes once omp takes it. The +// ledger remembers every item of the current batch and derives its progress +// from the frames omp already sends: +// +// appears in a snapshot → queued +// leaves the snapshot, then its +// text arrives as a user message → running ("all" mode starts several at once) +// the run that consumed it ends → done, or failed when the run errored/aborted +// a later follow-up starts → done (follow-ups only start once the +// agent would otherwise stop) +// withdrawn without delivery → cancelled (remove_queued_message, abort) +// +// Items are plain strings without ids, so they are matched by text and order. +// Identical texts are resolved deterministically: omp delivers from the front +// and removes the first match, so when a snapshot shrinks the *earliest* +// matching item is the one that left. +// +// Pure and synchronous: the caller (lib/rpc-manager.ts) feeds frames and +// supplies the clock. The ledger lives in memory for one omp process, so it +// starts empty again whenever omp or omp-web restarts. + +import type { QueuedMessages } from "./pi-types"; + +export type QueueName = "steering" | "followUp"; +export type QueueProgressStatus = "queued" | "running" | "done" | "failed" | "cancelled"; +export type QueueRunOutcome = "completed" | "failed" | "aborted"; + +export interface QueueProgressItem { + id: string; + text: string; + queue: QueueName; + status: QueueProgressStatus; + queuedAt: number; + startedAt?: number; + finishedAt?: number; + /** Still `queued`, but omp's queue no longer holds it: it was taken and has + * not reached the transcript yet. Edit/Delete/Steer cannot act on it. */ + departed?: true; +} + +/** Wire shape (`get_state.queueProgress` and `queue_progress` frames). */ +export interface QueueProgressSnapshot { + /** Identifies one ledger (one omp process); revisions only compare within it. */ + epoch: string; + revision: number; + items: QueueProgressItem[]; +} + +const QUEUE_STATUSES: readonly QueueProgressStatus[] = ["queued", "running", "done", "failed", "cancelled"]; + +interface Entry extends Omit { + /** Creation order, the final tie-breaker everywhere. */ + seq: number; + /** Index in omp's queue while queued. */ + position: number; + /** Left omp's snapshot but has not been seen in the transcript yet. */ + departed: boolean; + departedSeq: number; + /** Turn in which it started (follow-ups complete earlier turns' items). */ + startedTurn: number; + /** Started or settled by inference (a later item's delivery, the run's end) + * rather than by its own transcript message; a confirmed removal overrides it. */ + inferred: boolean; +} + +const QUEUES: readonly QueueName[] = ["steering", "followUp"]; + +const isActive = (entry: Entry) => entry.status === "queued" || entry.status === "running"; + +/** + * Pair old queued texts with a new snapshot (longest common subsequence), + * leaving the EARLIEST old items unmatched when several alignments are equally + * long. Returns, for each old index, the new index it maps to or -1. + */ +export function alignQueue(oldTexts: readonly string[], newTexts: readonly string[]): number[] { + const n = oldTexts.length; + const m = newTexts.length; + const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0)); + for (let i = 1; i <= n; i += 1) { + for (let j = 1; j <= m; j += 1) { + dp[i][j] = oldTexts[i - 1] === newTexts[j - 1] + ? dp[i - 1][j - 1] + 1 + : Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + const mapping = new Array(n).fill(-1); + // Backtracking from the end matches the latest old item first, so the + // unmatched (departed) ones are the earliest. + let i = n; + let j = m; + while (i > 0 && j > 0) { + if (oldTexts[i - 1] === newTexts[j - 1]) { + mapping[i - 1] = j - 1; + i -= 1; + j -= 1; + } else if (dp[i - 1][j] >= dp[i][j - 1]) { + i -= 1; + } else { + j -= 1; + } + } + return mapping; +} + +/** + * The text omp's queue chip shows for a transcript user message, or null when + * the message cannot come from the user's queue (other roles, agent-authored + * input, hidden companions). + */ +export function queuedTextOfUserMessage(message: unknown): string | null { + if (!message || typeof message !== "object") return null; + const value = message as { role?: unknown; content?: unknown; attribution?: unknown }; + if (value.role !== "user" || value.attribution === "agent") return null; + if (typeof value.content === "string") return value.content; + if (!Array.isArray(value.content)) return null; + const texts: string[] = []; + let hasImage = false; + for (const block of value.content as Array<{ type?: unknown; text?: unknown }>) { + if (block?.type === "text" && typeof block.text === "string") texts.push(block.text); + else if (block?.type === "image") hasImage = true; + } + if (texts.length > 0) return texts.join("\n"); + // omp labels an image-only queued message "[Image]". + return hasImage ? "[Image]" : null; +} + +/** How a terminal `agent_end` ended, from its last assistant message. */ +export function runOutcomeOfAgentEnd(event: { [key: string]: unknown }): QueueRunOutcome { + const messages = Array.isArray(event.messages) ? event.messages : []; + for (let index = messages.length - 1; index >= 0; index -= 1) { + const message = messages[index] as { role?: unknown; stopReason?: unknown } | null; + if (message?.role !== "assistant") continue; + if (message.stopReason === "aborted") return "aborted"; + if (message.stopReason === "error") return "failed"; + return "completed"; + } + return "completed"; +} + +/** Parse omp's queue snapshot from a `queue_update` frame or `get_state`; null when absent. */ +export function readQueueSnapshot(value: unknown): QueuedMessages | null { + if (!value || typeof value !== "object" || !("steering" in value) || !("followUp" in value)) return null; + const [steering, followUp] = [value.steering, value.followUp].map((list) => + Array.isArray(list) ? list.filter((item): item is string => typeof item === "string") : []); + return { steering, followUp }; +} + +/** Parse a ledger snapshot from a `queue_progress` frame or `get_state.queueProgress`. */ +export function readQueueProgressSnapshot(value: unknown): QueueProgressSnapshot | null { + if (!value || typeof value !== "object") return null; + const { epoch, revision, items } = value as Record; + if (typeof epoch !== "string" || typeof revision !== "number" || !Array.isArray(items)) return null; + const parsed: QueueProgressItem[] = []; + for (const raw of items as Array | null>) { + if (!raw || typeof raw.id !== "string" || typeof raw.text !== "string" || typeof raw.queuedAt !== "number") continue; + if (raw.queue !== "steering" && raw.queue !== "followUp") continue; + if (!QUEUE_STATUSES.includes(raw.status as QueueProgressStatus)) continue; + parsed.push({ + id: raw.id, + text: raw.text, + queue: raw.queue, + status: raw.status as QueueProgressStatus, + queuedAt: raw.queuedAt, + ...(typeof raw.startedAt === "number" ? { startedAt: raw.startedAt } : {}), + ...(typeof raw.finishedAt === "number" ? { finishedAt: raw.finishedAt } : {}), + ...(raw.departed === true ? { departed: true as const } : {}), + }); + } + return { epoch, revision, items: parsed }; +} + +export interface QueueProgressLedgerOptions { + epoch: string; + createId: () => string; +} + +export class QueueProgressLedger { + private readonly epoch: string; + private readonly createId: () => string; + private entries: Entry[] = []; + private revision = 0; + private seq = 0; + private departureSeq = 0; + private turn = 0; + + constructor({ epoch, createId }: QueueProgressLedgerOptions) { + this.epoch = epoch; + this.createId = createId; + } + + snapshot(): QueueProgressSnapshot { + // Started items in start order, then pending items in delivery order + // (steering drains before follow-ups), then items withdrawn unstarted. + const started: Entry[] = []; + const queued: Entry[] = []; + const withdrawn: Entry[] = []; + for (const entry of this.entries) { + if (entry.status === "queued") queued.push(entry); + else if (entry.status === "cancelled" && entry.startedAt === undefined) withdrawn.push(entry); + else started.push(entry); + } + started.sort((a, b) => (a.startedAt ?? a.finishedAt ?? 0) - (b.startedAt ?? b.finishedAt ?? 0) || a.seq - b.seq); + queued.sort((a, b) => Number(b.departed) - Number(a.departed) + || QUEUES.indexOf(a.queue) - QUEUES.indexOf(b.queue) + || a.position - b.position + || a.seq - b.seq); + return { + epoch: this.epoch, + revision: this.revision, + items: [...started, ...queued, ...withdrawn].map(publicItem), + }; + } + + /** A `queue_update` frame or `get_state.queuedMessages`. Returns whether anything changed. */ + observeQueue(snapshot: QueuedMessages, now: number): boolean { + let changed = false; + const departedNow: Entry[] = []; + const unmatched: Record> = { steering: [], followUp: [] }; + for (const queue of QUEUES) { + const texts = snapshot[queue]; + const pending = this.entries + .filter((entry) => entry.status === "queued" && !entry.departed && entry.queue === queue) + .sort((a, b) => a.position - b.position || a.seq - b.seq); + const mapping = alignQueue(pending.map((entry) => entry.text), texts); + const taken = new Set(); + pending.forEach((entry, index) => { + const position = mapping[index]; + if (position >= 0) { + taken.add(position); + if (entry.position !== position) { + entry.position = position; + changed = true; + } + } else { + entry.departed = true; + entry.departedSeq = ++this.departureSeq; + departedNow.push(entry); + } + }); + texts.forEach((text, position) => { + if (!taken.has(position)) unmatched[queue].push({ text, position }); + }); + } + // promote_queued_message moves a follow-up to the end of the steering queue. + for (const added of [...unmatched.steering]) { + const promoted = departedNow.find((entry) => entry.queue === "followUp" && entry.departed && entry.text === added.text); + if (!promoted) continue; + promoted.queue = "steering"; + promoted.departed = false; + promoted.position = added.position; + unmatched.steering.splice(unmatched.steering.indexOf(added), 1); + changed = true; + } + if (departedNow.length > 0) changed = true; + + const additions = [...unmatched.steering.map((item) => ({ ...item, queue: "steering" as const })), + ...unmatched.followUp.map((item) => ({ ...item, queue: "followUp" as const }))]; + if (additions.length > 0) { + // A new batch starts once nothing of the previous one is still pending. + if (!this.entries.some(isActive)) this.entries = []; + for (const { text, position, queue } of additions) { + this.entries.push({ + id: this.createId(), + text, + queue, + status: "queued", + queuedAt: now, + seq: ++this.seq, + position, + departed: false, + departedSeq: 0, + startedTurn: 0, + inferred: false, + }); + } + changed = true; + } + return this.bump(changed); + } + + /** A `turn_start` frame: delivered follow-ups begin a new turn. */ + observeTurnStart(): void { + this.turn += 1; + } + + /** A user message entered the transcript (`message_start`). */ + observeUserMessage(text: string, now: number): boolean { + const entry = this.findDelivered(text); + if (!entry) return false; + // Items that left the queue before this one were delivered too, under a + // rewritten text (slash command, template); they run alongside it. + for (const earlier of this.entries) { + if (earlier.status === "queued" && earlier.departed && earlier.departedSeq < entry.departedSeq) { + this.start(earlier, now, true); + } + } + if (entry.queue === "followUp") { + // A follow-up starts only once the agent would otherwise stop, so the + // work of every item started in an earlier turn is finished. + for (const running of this.entries) { + if (running.status === "running" && running.startedTurn < this.turn) this.finish(running, "done", now); + } + } + this.start(entry, now); + return this.bump(true); + } + + /** A terminal `agent_end` (or a failed prompt) ended the run. */ + observeRunEnd(outcome: QueueRunOutcome, now: number): boolean { + let changed = false; + for (const entry of this.entries) { + if (entry.status === "running") { + this.finish(entry, outcome === "completed" ? "done" : "failed", now); + changed = true; + } else if (entry.status === "queued" && entry.departed) { + // Left the queue but never matched a transcript message: delivered + // under a rewritten text when the run completed or failed, dropped + // by the abort otherwise. + this.finish(entry, outcome === "completed" ? "done" : outcome === "failed" ? "failed" : "cancelled", now); + entry.inferred = true; + changed = true; + } + } + return this.bump(changed); + } + + /** `remove_queued_message` answered `removed: true`. */ + observeRemoval(text: string, queue: QueueName, now: number): boolean { + const matches = this.entries.filter((entry) => entry.queue === queue && entry.text === text); + // The snapshot that dropped it arrives first (departed). A later item's + // delivery or the run's end may have settled it by inference before this + // reply: the removal proves omp never ran it. Without either, omp removed + // the first pending match. + const entry = matches.filter((item) => item.status === "queued" && item.departed).sort((a, b) => a.departedSeq - b.departedSeq)[0] + ?? matches.filter((item) => item.inferred && item.status !== "cancelled").sort((a, b) => a.departedSeq - b.departedSeq)[0] + ?? matches.filter((item) => item.status === "queued").sort((a, b) => a.position - b.position || a.seq - b.seq)[0]; + if (!entry) return false; + entry.startedAt = undefined; + this.finish(entry, "cancelled", now); + return this.bump(true); + } + + /** The newest entry so far; {@link observeAbort} leaves later entries alone. */ + boundary(): number { + return this.seq; + } + + /** + * `abort` / `abort_and_restore_queue` answered. The run's own `agent_end` + * marks running items failed; this settles the queue: items omp took but + * never recorded were dropped, and `restoreQueue` withdraws everything. + * Only entries up to `boundary` (taken before the abort was sent) are + * settled: a prompt queued after it can reach the ledger before the reply. + */ + observeAbort({ restoreQueue, boundary }: { restoreQueue: boolean; boundary: number }, now: number): boolean { + let changed = false; + for (const entry of this.entries) { + if (entry.seq > boundary) continue; + if (entry.status === "running") { + this.finish(entry, "failed", now); + changed = true; + } else if (entry.status === "queued" && (entry.departed || restoreQueue)) { + this.finish(entry, "cancelled", now); + changed = true; + } + } + return this.bump(changed); + } + + /** Clear finished items (the user dismissed the summary). */ + dismissFinished(): boolean { + const before = this.entries.length; + this.entries = this.entries.filter(isActive); + return this.bump(this.entries.length !== before); + } + + /** Forget everything (the session switched to another conversation). */ + reset(): boolean { + const changed = this.entries.length > 0; + this.entries = []; + return this.bump(changed); + } + + private findDelivered(text: string): Entry | undefined { + const departed = this.entries + .filter((entry) => entry.status === "queued" && entry.departed && entry.text === text) + .sort((a, b) => a.departedSeq - b.departedSeq)[0]; + if (departed) return departed; + // Live steering can record a message before the snapshot drops it. + return this.entries + .filter((entry) => entry.status === "queued" && entry.text === text) + .sort((a, b) => QUEUES.indexOf(a.queue) - QUEUES.indexOf(b.queue) || a.position - b.position || a.seq - b.seq)[0]; + } + + private start(entry: Entry, now: number, inferred = false): void { + entry.status = "running"; + entry.departed = false; + entry.startedAt = now; + entry.startedTurn = this.turn; + entry.inferred = inferred; + } + + private finish(entry: Entry, status: "done" | "failed" | "cancelled", now: number): void { + entry.status = status; + entry.departed = false; + entry.finishedAt = now; + } + + private bump(changed: boolean): boolean { + if (changed) this.revision += 1; + return changed; + } +} + +function publicItem(entry: Entry): QueueProgressItem { + return { + id: entry.id, + text: entry.text, + queue: entry.queue, + status: entry.status, + queuedAt: entry.queuedAt, + ...(entry.startedAt !== undefined ? { startedAt: entry.startedAt } : {}), + ...(entry.finishedAt !== undefined ? { finishedAt: entry.finishedAt } : {}), + ...(entry.status === "queued" && entry.departed ? { departed: true as const } : {}), + }; +} + +export interface QueuePanelItem extends QueueProgressItem { + /** The first chip with its text in omp's queue, so Edit/Delete/Steer act on it. */ + actionable: boolean; +} + +/** + * What the composer's queue panel lists: the ledger's batch, with omp's own + * queue snapshot deciding which pending items can still be edited. A chip the + * ledger has not reported yet (HTTP and SSE can reorder) still shows, so the + * panel never hides something omp will run. + * + * omp's queue commands carry only the text and act on the first match, so of + * several identical pending items only the first offers them; a departed item + * left omp's queue and never claims a chip. + */ +export function buildQueuePanelItems(progress: QueueProgressSnapshot | null, queue: QueuedMessages | null): QueuePanelItem[] { + const chips: Record = { steering: queue?.steering ?? [], followUp: queue?.followUp ?? [] }; + const claimed: Record = { + steering: chips.steering.map(() => false), + followUp: chips.followUp.map(() => false), + }; + const firstOfText = (name: QueueName, index: number) => chips[name].indexOf(chips[name][index]) === index; + const items: QueuePanelItem[] = (progress?.items ?? []).map((item) => { + if (item.status !== "queued" || item.departed) return { ...item, actionable: false }; + const index = chips[item.queue].findIndex((text, position) => !claimed[item.queue][position] && text === item.text); + if (index < 0) return { ...item, actionable: false }; + claimed[item.queue][index] = true; + return { ...item, actionable: firstOfText(item.queue, index) }; + }); + for (const name of QUEUES) { + chips[name].forEach((text, index) => { + if (claimed[name][index]) return; + items.push({ id: `chip:${name}:${index}:${text}`, text, queue: name, status: "queued", queuedAt: 0, actionable: firstOfText(name, index) }); + }); + } + return items; +} diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index a153e829d..87ad5cf56 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -2659,3 +2659,76 @@ test("waitForTurnEnd resolves on terminal agent_end and rejects on timeout (#275 emit({ type: "prompt_result" }); await promptDone; }); + +test("the queue-progress ledger follows omp's frames and reaches every tab and the state payload", async (t) => { + const commands = []; + const { wrapper, emit } = snapshotSession(t, async (command) => { + commands.push(command.type); + if (command.type === "get_state") return { sessionId: "queue-progress", isStreaming: false, isCompacting: false, queuedMessages: { steering: [], followUp: [] } }; + if (command.type === "remove_queued_message") return { removed: true }; + return {}; + }, SnapshotWrapper, "queue-progress"); + const tabs = [[], []]; + for (const frames of tabs) wrapper.onEvent((event) => { if (event.type === "queue_progress") frames.push(event); }); + const latest = () => tabs[0].at(-1).items.map((item) => `${item.text}:${item.status}`); + + emit({ type: "agent_start" }); + emit({ type: "queue_update", steering: [], followUp: ["two"] }); + emit({ type: "queue_update", steering: [], followUp: ["two", "three"] }); + assert.deepEqual(latest(), ["two:queued", "three:queued"]); + emit({ type: "queue_update", steering: [], followUp: ["three"] }); + emit({ type: "turn_start" }); + emit({ type: "message_start", message: { role: "user", content: "two", attribution: "user" } }); + assert.deepEqual(latest(), ["two:running", "three:queued"]); + + emit({ type: "queue_update", steering: [], followUp: [] }); + await wrapper.send({ type: "remove_queued_message", message: "three", queue: "followUp" }); + assert.deepEqual(latest(), ["two:running", "three:cancelled"]); + emit({ type: "agent_end", isTerminal: false, messages: [] }); + assert.deepEqual(latest(), ["two:running", "three:cancelled"], "a continuation is not the end of the run"); + emit({ type: "agent_end", isTerminal: true, messages: [{ role: "assistant", stopReason: "stop" }] }); + assert.deepEqual(latest(), ["two:done", "three:cancelled"]); + assert.deepEqual(tabs[1], tabs[0], "every attached tab sees the same ledger"); + + const state = await wrapper.send({ type: "get_state" }); + const { epoch, revision, items } = tabs[0].at(-1); + assert.deepEqual(state.queueProgress, { epoch, revision, items }); + + await wrapper.send({ type: "dismiss_queue_progress" }); + assert.deepEqual(tabs[0].at(-1).items, []); + assert.ok(!commands.includes("dismiss_queue_progress"), "dismissing is omp-web's own and never reaches omp"); +}); + +test("a failed prompt fails the running queued item; aborts settle the rest", async (t) => { + const { wrapper, emit } = snapshotSession(t, async (command) => (command.type === "abort_and_restore_queue" ? { steering: [], followUp: [] } : {})); + const frames = []; + wrapper.onEvent((event) => { if (event.type === "queue_progress") frames.push(event); }); + const latest = () => frames.at(-1).items.map((item) => `${item.text}:${item.status}`); + emit({ type: "agent_start" }); + emit({ type: "queue_update", steering: [], followUp: ["a", "b"] }); + emit({ type: "queue_update", steering: [], followUp: ["b"] }); + emit({ type: "turn_start" }); + emit({ type: "message_start", message: { role: "user", content: [{ type: "text", text: "a" }] } }); + emit({ type: "response", command: "prompt", success: false, error: "provider down" }); + assert.deepEqual(latest(), ["a:failed", "b:queued"]); + await wrapper.send({ type: "abort_and_restore_queue" }); + assert.deepEqual(latest(), ["a:failed", "b:cancelled"]); +}); + +test("an abort's reply leaves a prompt queued after it alone", async (t) => { + let emitFrame; + const { wrapper, emit } = snapshotSession(t, async (command) => { + if (command.type !== "abort_and_restore_queue") return {}; + // omp withdrew "old"; another tab's prompt is queued before omp-web handles this reply. + emitFrame({ type: "queue_update", steering: [], followUp: [] }); + emitFrame({ type: "queue_update", steering: [], followUp: ["new"] }); + return { steering: [], followUp: ["old"] }; + }); + emitFrame = emit; + const frames = []; + wrapper.onEvent((event) => { if (event.type === "queue_progress") frames.push(event); }); + emit({ type: "agent_start" }); + emit({ type: "queue_update", steering: [], followUp: ["old"] }); + await wrapper.send({ type: "abort_and_restore_queue" }); + assert.deepEqual(frames.at(-1).items.map((item) => `${item.text}:${item.status}`), ["new:queued", "old:cancelled"]); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index f8e23cee8..f17bda5a0 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -37,6 +37,7 @@ import { publishNotification } from "./notification-hub"; import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "./skill-diagnostics"; import { isReservedLaunchArg, loadProjectRegistry } from "./project-registry"; import { eventWithToolResultImageUrls } from "./media-cache"; +import { QueueProgressLedger, queuedTextOfUserMessage, readQueueSnapshot, runOutcomeOfAgentEnd } from "./queue-progress"; import type { BashResultInfo, OmpModel, @@ -389,6 +390,9 @@ export class AgentSessionWrapper { private hostUriSchemes: Map = new Map(); /** host_uri_request ids awaiting a host_uri_result from the browser. */ private pendingHostUris: Map = new Map(); + /** Progress of the queued prompts in the current batch (lib/queue-progress.ts). + * In memory only: a new omp process or omp-web restart starts empty. */ + private readonly queueProgress = new QueueProgressLedger({ epoch: randomUUID(), createId: randomUUID }); /** Resolves once an in-flight destroyAndWait finishes; null when idle. Read * by startRpcSession so a replacement spawn awaits the old child's exit. */ destroyPromise: Promise | null = null; @@ -610,6 +614,7 @@ export class AgentSessionWrapper { this.continuationGraceUntil = 0; // A different conversation now: the old one's ids must not suppress its notifications. this.movedFromIds.length = 0; + this.publishQueueProgress(this.queueProgress.reset()); } this._sessionId = state.sessionId; this._sessionFile = state.sessionFile ?? ""; @@ -906,6 +911,7 @@ export class AgentSessionWrapper { const promptError = { type: "prompt_error", errorMessage: detail, error: event.error, command: event.command }; this.publishNotifications(promptError); this.emit(promptError); + this.publishQueueProgress(this.queueProgress.observeRunEnd("failed", Date.now())); notifyRunningChange(); return; } @@ -1017,6 +1023,7 @@ export class AgentSessionWrapper { this.publishNotifications(event); this.emit(event); + this.trackQueueProgress(event); notifyRunningChange({ refreshSessionList }); } @@ -1223,6 +1230,37 @@ export class AgentSessionWrapper { } } + /** + * Feed omp's frames to the queue-progress ledger. The ledger only reads + * frames omp already sends; it never changes what reaches the browser. + */ + private trackQueueProgress(event: UnsequencedAgentEvent): void { + const now = Date.now(); + switch (event.type) { + case "queue_update": { + const snapshot = readQueueSnapshot(event); + if (snapshot) this.publishQueueProgress(this.queueProgress.observeQueue(snapshot, now)); + break; + } + case "turn_start": + this.queueProgress.observeTurnStart(); + break; + case "message_start": { + const text = queuedTextOfUserMessage(event.message); + if (text !== null) this.publishQueueProgress(this.queueProgress.observeUserMessage(text, now)); + break; + } + case "agent_end": + if (event.isTerminal !== false) this.publishQueueProgress(this.queueProgress.observeRunEnd(runOutcomeOfAgentEnd(event), now)); + break; + } + } + + /** Broadcast the ledger to every attached tab after a change. */ + private publishQueueProgress(changed: boolean): void { + if (changed) this.emit({ type: "queue_progress", ...this.queueProgress.snapshot() }); + } + private sessionFileSignalTimer: NodeJS.Timeout | null = null; /** Invalidate session-list metadata plus ONLY this session's parse caches @@ -1508,6 +1546,8 @@ export class AgentSessionWrapper { // Reconcile process-side flags with authoritative child state. this.applyIdentity({ ...state, sessionFile: state.sessionFile ?? this._sessionFile }); this.streamSequence += 1; + // Same authoritative queue as `queue_update`, read in stdout order. + if (state.queuedMessages) this.publishQueueProgress(this.queueProgress.observeQueue(state.queuedMessages, Date.now())); const awaitingExpired = !this.awaitingAgentStart || Date.now() >= this.awaitingAgentStartDeadline; const hasPendingWork = @@ -1561,6 +1601,7 @@ export class AgentSessionWrapper { messageCount: state.messageCount, queuedMessageCount: state.queuedMessageCount, queuedMessages: state.queuedMessages ?? { steering: [], followUp: [] }, + queueProgress: this.queueProgress.snapshot(), tokensPerSecond: state.tokensPerSecond ?? null, contextUsage: state.contextUsage ?? null, systemPrompt: state.systemPrompt?.join("\n\n") ?? "", @@ -1723,6 +1764,8 @@ export class AgentSessionWrapper { this.extensionStatuses.clear(); this.extensionWidgets.clear(); this.clearPendingUiRequests(); + // The replacement process starts with an empty queue. + this.publishQueueProgress(this.queueProgress.reset()); this.promptRunning = false; this.promptDispatchPendingCount = 0; this.awaitingAgentStart = false; @@ -1898,15 +1941,28 @@ export class AgentSessionWrapper { // Queue mutations are synchronous control operations, like get_state. // Expiry must not abort unrelated work or replay a possibly applied mutation. const result = await this.proc.sendCommand(command as { type: string }, GET_STATE_TIMEOUT_MS); + if (type === "remove_queued_message" && isRecord(result) && result.removed === true + && typeof command.message === "string" && (command.queue === "steering" || command.queue === "followUp")) { + this.publishQueueProgress(this.queueProgress.observeRemoval(command.message, command.queue, Date.now())); + } return result ?? null; } + // omp-web's own: clear the finished items of the queue-progress summary + // for every tab viewing the session. + case "dismiss_queue_progress": + this.publishQueueProgress(this.queueProgress.dismissFinished()); + return null; + // abort_and_restore_queue is omp's Esc: it takes queued user input back // atomically, then aborts, and returns the withdrawn messages. case "abort": case "abort_and_restore_queue": { this.responseObserved = false; this.responseRunActive = false; + // The abort settles only what was queued before it was sent: a prompt + // queued afterwards can reach the ledger before the reply is handled. + const queueBoundary = this.queueProgress.boundary(); const result = await this.withFinalRunningNotification(async () => { const response: unknown = await this.proc.sendCommand({ type }); // If the prompt was aborted before the agent loop started, no @@ -1923,6 +1979,7 @@ export class AgentSessionWrapper { this.clearLiveSnapshots(); return response; }); + this.publishQueueProgress(this.queueProgress.observeAbort({ restoreQueue: type === "abort_and_restore_queue", boundary: queueBoundary }, Date.now())); return type === "abort" ? null : result ?? null; }