Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f
- Keep composer controls on one line, with equally sized Send, Stop, and Queue buttons and model names truncating before short effort labels.
- Align the + button and primary action with matching composer insets.
- Clearly dim Attach files while the agent is running; queued messages remain text-only.
- Recover saved responses before reporting an empty agent reply after returning to a backgrounded page or PWA. Preserve provider errors and distinguish new runs from older answers.

---

Expand Down
156 changes: 156 additions & 0 deletions hooks/useAgentSession.rpc.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,162 @@ test("a silent idle transition shows a fallback error instead of disappearing",
assert.ok(w.latest.notices.some((notice) => /stopped without returning a response/i.test(notice.message)));
});

for (const completion of ["visibilitychange", "agent_end"]) {
test(`a saved response missed by SSE is recovered on ${completion} without a failure notice`, async (t) => {
t.after(unmountAll);
resetWorld();
primeSession("s1", [userMsg("u0", "old question")]);
const { w, es } = await startRun(t, "s1", "new question");
primeSession("s1", [
userMsg("u0", "old question"),
userMsg("u1", "new question"),
assistantMsg("a1", "Completed while away"),
]);
await act(async () => {
if (completion === "agent_end") es.emit({ type: "agent_end", isTerminal: true });
else docTarget.fire("visibilitychange");
await sleep(60);
});
await settle();

assert.equal(w.latest.agentRunning, false);
assert.ok(w.latest.messages.some((m) => m.role === "assistant" && m.content[0]?.text === "Completed while away"));
assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), []);
});
}

test("an older answer does not hide a current run with only tool activity", async (t) => {
t.after(unmountAll);
resetWorld();
const history = [userMsg("u0", "question"), assistantMsg("a0", "Old answer")];
primeSession("s1", history);
const { w } = await startRun(t, "s1", "question");
primeSession("s1", [...history, userMsg("u1", "question"), {
...assistantMsg("a1", ""),
content: [{ type: "toolCall", toolCallId: "tc1", toolName: "read", input: {} }],
}]);
await act(async () => {
docTarget.fire("visibilitychange");
await sleep(60);
});
await settle();
assert.equal(w.latest.agentRunning, false);
assert.equal(w.latest.notices.filter((n) => n.type === "error").length, 1);
});

test("a repeated prompt cannot reuse an old saved answer when the new prompt was not persisted", async (t) => {
t.after(unmountAll);
resetWorld();
primeSession("s1", [userMsg("u0", "question"), assistantMsg("a0", "Old answer")]);
const { w } = await startRun(t, "s1", "question");
await act(async () => {
docTarget.fire("visibilitychange");
await sleep(60);
});
await settle();
assert.equal(w.latest.agentRunning, false);
assert.equal(w.latest.notices.filter((n) => n.type === "error").length, 1);
});

test("recovery preserves a saved provider failure even after partial response content", async (t) => {
t.after(unmountAll);
resetWorld();
primeSession("s1", [userMsg("u0", "old question")]);
const { w } = await startRun(t, "s1", "new question");
const providerError = "Provider disconnected during generation";
primeSession("s1", [
userMsg("u0", "old question"),
userMsg("u1", "new question"),
{ ...assistantMsg("a1", "Partial answer"), stopReason: "error", errorMessage: providerError },
]);
await act(async () => {
docTarget.fire("visibilitychange");
await sleep(60);
});
await settle();
assert.equal(w.latest.agentRunning, false);
assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [providerError]);
});

test("a failed transcript reload is retried instead of being classified as an empty response", async (t) => {
t.after(unmountAll);
resetWorld();
primeSession("s1", [userMsg("u0", "old question")]);
const { w } = await startRun(t, "s1", "new question");
primeSession("s1", [userMsg("u0", "old question"), userMsg("u1", "new question"), assistantMsg("a1", "Saved answer")]);
world.holds.push({
match: (method, url) => method === "GET" && url.startsWith("/api/sessions/s1?"),
produce: async () => ({ status: 503, value: {} }),
});
await act(async () => {
docTarget.fire("visibilitychange");
await sleep(60);
});
await settle();
assert.equal(w.latest.agentRunning, true, "unknown completion must remain recoverable");
assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), []);

await act(async () => {
winTarget.fire("online");
await sleep(60);
});
await settle();
assert.equal(w.latest.agentRunning, false);
assert.ok(w.latest.messages.some((m) => m.role === "assistant" && m.content[0]?.text === "Saved answer"));
assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), []);
});

for (const nextRun of ["send", "interrupt"]) {
test(`${nextRun} captures saved entries newer than the last rendered transcript`, async (t) => {
t.after(unmountAll);
resetWorld();
primeSession("s1", [userMsg("u0", "old question")]);
const { w, es } = await startRun(t, "s1", "question");
primeSession("s1", [userMsg("u0", "old question"), userMsg("u1", "question"), assistantMsg("a1", "Previous answer")]);
let releaseTerminalReload;
if (nextRun === "send") {
world.holds.push({
match: (method, url) => method === "GET" && url.startsWith("/api/sessions/s1?"),
produce: () => new Promise((resolve) => {
releaseTerminalReload = () => resolve({ value: {
sessionId: "s1",
leafId: "3",
context: { ...world.sessions.get("s1"), todoPhases: [] },
} });
}),
});
await act(async () => {
es.emit({ type: "message_update", message: assistantMsg("a1", "Previous answer") });
es.emit({ type: "agent_end", isTerminal: true });
await Promise.resolve();
});
assert.equal(w.latest.agentRunning, false);
}
let submission;
await act(async () => {
submission = nextRun === "send" ? w.latest.handleSend("question") : w.latest.handleInterruptAndReply("question");
await sleep(30);
});
const replacement = lastEs();
await act(async () => {
replacement.open();
await submission;
releaseTerminalReload?.();
if (nextRun === "interrupt") replacement.emit({ type: "agent_end", isTerminal: true });
replacement.emit({ type: "agent_start" });
await Promise.resolve();
});
// The replacement never persisted a new user entry or answer.
await act(async () => {
docTarget.fire("visibilitychange");
await sleep(60);
});
await settle();
assert.equal(w.latest.agentRunning, false);
assert.equal(w.latest.notices.filter((n) => n.type === "error").length, 1, "previous answer must not count as replacement success");
});
}

test("tool activity and turn_end errors do not count as a successful answer", async (t) => {
t.after(unmountAll);
resetWorld();
Expand Down
88 changes: 72 additions & 16 deletions hooks/useAgentSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
// until the terminal path can surface it exactly once.
const lastRunErrorRef = useRef<string | null>(null);
const runHadContentRef = useRef(false);
// Persisted entries preceding a locally submitted run cannot supply its answer.
// Empty on mount; null while a submitted run's boundary is still being read.
const runPreviousEntryIdsRef = useRef<string[] | null>([]);
const slashCommandRunRef = useRef(false);
// Bumped on every roster clear (run end): in-flight get_subagents/history
// responses from the finished run must not merge into the cleared (or next
Expand Down Expand Up @@ -715,7 +718,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
messagesLoaded = true;
if (showLoading) setLoading(false);
if (!includeState) {
return null;
return { context: d.context, agentState: null };
}

// Track initial hydration so prompt submission waits for the live state.
Expand Down Expand Up @@ -760,11 +763,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
setQueuedMessages(EMPTY_QUEUE);
}
if (showLoading) setLoading(false);
return agentState;
return { context: d.context, agentState };
} catch (e) {
console.error("Failed to load agent state:", e);
if (showLoading) setLoading(false);
return null;
return { context: d.context, agentState: null };
} finally {
if (isInitialHydration) initialHydrationPendingRef.current = false;
}
Expand Down Expand Up @@ -1339,22 +1342,47 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
}
}, [addNotice, opts.chatInputRef]);

const finishPromptWithoutStream = useCallback(async (sid: string | null = sessionIdRef.current, runId?: number) => {
const finishPromptWithoutStream = useCallback(async (sid: string | null = sessionIdRef.current, runId = promptRunIdRef.current) => {
clearTerminalReconcileTimer();
// Bail out before loadSession too: a stale finish for a previous run
// must not overwrite the messages of the run currently streaming.
if (runId !== undefined && promptRunIdRef.current !== runId) return;
const hadContent = runHadContentRef.current;
let hadContent = runHadContentRef.current;
const quotaMessage = lastQuotaErrorRef.current;
const runError = lastRunErrorRef.current;
let runError = lastRunErrorRef.current;
const allowEmptyResponse = slashCommandRunRef.current;
const previousEntryIds = runPreviousEntryIdsRef.current;
if (previousEntryIds === null) return;
let transcriptLoaded = false;
try {
// Pass the fence into loadSession: the pre-check above only guards the
// start — a next prompt that begins while the reload is in flight must
// not be overwritten by the finished run's snapshot.
if (sid) await loadSession(sid, false, true, runId);
const loaded = sid ? await loadSession(sid, false, true, runId) : null;
if (loaded) {
transcriptLoaded = true;
const { messages, entryIds = [] } = loaded.context;
// Only the latest user turn can answer the current prompt. Entry ids
// distinguish repeated same-text prompts from the previous saved turn.
const userIndex = messages.findLastIndex((message) => message.role === "user");
const userEntryId = entryIds[userIndex];
if (userIndex >= 0 && userEntryId && !previousEntryIds.includes(userEntryId)) {
for (let i = userIndex + 1; i < messages.length; i += 1) {
const message = messages[i];
if (message.role !== "assistant") continue;
hadContent ||= hasVisibleAssistantContent(message);
runError = readAgentError(message) ?? runError;
}
}
}
} finally {
if (runId !== undefined && promptRunIdRef.current !== runId) return;
if (promptRunIdRef.current !== runId || sessionIdRef.current !== sid) return;
// Live frames can arrive while the snapshot is loading.
hadContent ||= runHadContentRef.current;
runError = lastRunErrorRef.current ?? runError;
// A failed read is not proof of an empty answer. Keep recovery active
// so the next visibility/online/poll trigger can load the transcript.
if (!transcriptLoaded && !hadContent && !runError && !allowEmptyResponse) return;
optimisticUserMessageKeyRef.current = null;
if (!agentRunningRef.current) return;
if (runError) {
Expand Down Expand Up @@ -1671,6 +1699,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
const quotaMessage = lastQuotaErrorRef.current;
const terminalError = readTerminalAgentError(event) ?? lastRunErrorRef.current;
const wasSlashCommand = slashCommandRunRef.current;
if (!hadContent && !terminalError && !wasSlashCommand) {
// On resume, even agent_end can arrive without the answer frames.
// Reload before classifying an apparently empty completion.
void finishPromptWithoutStream(sessionIdRef.current, promptRunIdRef.current);
break;
}
if (terminalError && isQuotaLikeError(terminalError)) {
lastQuotaErrorRef.current = terminalError;
}
Expand All @@ -1690,10 +1724,6 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
} else {
toast.error("Request failed", errorMessage, { timeout: 12000 });
}
} else if (!hadContent && !wasSlashCommand) {
const message = translate("agentSession.responseFailed");
addNotice({ type: "error", message });
toast.error("Request failed", message, { timeout: 10000 });
}
// async, and a next prompt (or session switch) that starts while it is
// in flight must not be overwritten by this finished run's snapshot.
Expand Down Expand Up @@ -2203,6 +2233,17 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
}, [addNotice, clearLiveToolResults, clearTerminalReconcileTimer, consumeQueuedMessage, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, mergeSubagents, onAgentEnd, reconcileAgentState, resetSubagentActivityState, applyAuthoritativeModel, beginAuthoritativeModelSync, setLiveToolResult, surfaceQuotaOnStream]);
handleAgentEventRef.current = handleAgentEvent;

const snapshotRunEntries = useCallback(async (sid: string) => {
// Read immediately before dispatch, not from React's last rendered state:
// the previous terminal reload or interrupted turn can still be in flight.
// Unlike loadSession, this must not replace the optimistic user bubble.
const params = new URLSearchParams({ deferThinking: "1", deferMedia: "1" });
const res = await fetch(`/api/sessions/${encodeURIComponent(sid)}?${params}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const snapshot = await res.json() as SessionData;
return snapshot.context.entryIds ?? [];
}, []);

const handleSend = useCallback(async (message: string, images?: AttachedImage[]): Promise<boolean> => {
const trimmedMessage = message.trim();
if (!trimmedMessage && !images?.length) return false;
Expand Down Expand Up @@ -2235,6 +2276,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
setMessages((prev) => [...prev, userMsg]);
optimisticUserMessageKeyRef.current = userMessageKey(userMsg);
promptRunIdRef.current = promptRunId;
runPreviousEntryIdsRef.current = isNew ? [] : null;
agentRunningRef.current = true;
slashCommandRunRef.current = isSlashCommandPrompt;
// A new run starts fresh: drop any rescued in-flight reconcile state from
Expand Down Expand Up @@ -2296,6 +2338,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
void refreshSubagentRoster(session.id);
void registerHostTools(session.id);
void registerHostUriSchemes(session.id);
const previousEntryIds = await snapshotRunEntries(session.id);
if (promptRunIdRef.current === promptRunId && sessionIdRef.current === session.id) {
runPreviousEntryIdsRef.current = previousEntryIds;
}
await sendAgentCommand(session.id, {
type: "prompt",
message,
Expand Down Expand Up @@ -2340,7 +2386,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
dispatch({ type: "end" });
return false;
}
}, [isNew, newSessionCwd, newSessionModel, session, ensureNewSession, ensureEventsConnected, promoteNewSession, waitForPromptSettlement, addNotice, opts.chatInputRef, refreshSubagentRoster, registerHostTools, registerHostUriSchemes, clearLiveToolResults, clearTerminalReconcileTimer]);
}, [isNew, newSessionCwd, newSessionModel, session, ensureNewSession, ensureEventsConnected, promoteNewSession, waitForPromptSettlement, addNotice, opts.chatInputRef, refreshSubagentRoster, registerHostTools, registerHostUriSchemes, clearLiveToolResults, clearTerminalReconcileTimer, snapshotRunEntries]);

/** Abort the running agent and send the message as a fresh prompt
* (abort_and_prompt). Only valid mid-run; the old turn's agent_end is
Expand All @@ -2362,7 +2408,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
clearTerminalReconcileTimer();
// Advance the run generation so late agent_end / prompt_error / stale
// loadSession from the aborted turn cannot stop or clobber the replacement.
promptRunIdRef.current += 1;
const promptRunId = ++promptRunIdRef.current;
const previousRunEntryIds = runPreviousEntryIdsRef.current;
runPreviousEntryIdsRef.current = null;

const { userMsg, piImages: interruptPiImages } = buildOutgoingPrompt(message, images);
setMessages((prev) => [...prev, userMsg]);
Expand All @@ -2374,6 +2422,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
try {
await ensureEventsConnected(sid);
void refreshSubagentRoster(sid);
const previousEntryIds = await snapshotRunEntries(sid);
if (promptRunIdRef.current === promptRunId && sessionIdRef.current === sid) {
runPreviousEntryIdsRef.current = previousEntryIds;
}
await sendAgentCommand(sid, {
type: "abort_and_prompt",
message: trimmedMessage,
Expand All @@ -2382,6 +2434,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
return true;
} catch (e) {
console.error("Failed to interrupt and reply:", e);
if (promptRunIdRef.current === promptRunId && sessionIdRef.current === sid) {
runPreviousEntryIdsRef.current = previousRunEntryIds;
}
interruptReplyPendingRef.current = false;
const optimisticKey = optimisticUserMessageKeyRef.current;
if (optimisticKey) {
Expand All @@ -2399,7 +2454,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
if (trimmedMessage) opts.chatInputRef?.current?.insertIfEmpty(trimmedMessage);
return false;
}
}, [addNotice, ensureEventsConnected, refreshSubagentRoster, clearTerminalReconcileTimer, opts.chatInputRef]);
}, [addNotice, ensureEventsConnected, refreshSubagentRoster, clearTerminalReconcileTimer, opts.chatInputRef, snapshotRunEntries]);

const executeBash = useCallback(async (command: string, excludeFromContext: boolean) => {
if (agentRunningRef.current || bashRunningRef.current) return;
Expand Down Expand Up @@ -2999,7 +3054,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) {
if (mountedSessionLoadRef.current === session.id) return;
mountedSessionLoadRef.current = session.id;
sessionIdRef.current = session.id;
loadSession(session.id, true, true).then((agentState) => {
loadSession(session.id, true, true).then((loaded) => {
const agentState = loaded?.agentState;
if (agentState?.running) {
if (agentState.state?.isStreaming || agentState.state?.isPromptRunning) {
agentRunningRef.current = true;
Expand Down
Loading