fix(session): prevent consumed follow-ups from replaying after restart (#6299)
* fix(session): atomically acknowledge consumed follow-ups * refactor(webui): drop legacy follow-up replay compatibility
This commit is contained in:
1 parent
743d40bbba
commit
53e0edf709
17 files changed
+645
-215
No files matched your search
@@ -3,6 +3,7 @@ import type { UIMessage } from "@/lib/types";
|
||||
export interface PromptAnchor {
|
||||
answerPreview: string;
|
||||
id: string;
|
||||
turnId?: string;
|
||||
label: string;
|
||||
preview: string;
|
||||
createdAt: number;
|
||||
@@ -17,6 +18,7 @@ export function userPromptAnchors(messages: UIMessage[]): PromptAnchor[] {
|
||||
const anchor: PromptAnchor = {
|
||||
answerPreview: nextAssistantPreview(messages, messageIndex),
|
||||
id: message.id,
|
||||
...(message.turnId ? { turnId: message.turnId } : {}),
|
||||
label: promptLabel(message.content, index),
|
||||
preview: promptPreview(message.content, index),
|
||||
createdAt: message.createdAt,
|
||||
|
||||
@@ -92,24 +92,38 @@ export function usePromptHistory(key: string | null, version: number, messages:
|
||||
return () => controller.abort();
|
||||
}, [client, enabled, getToken, key, version, refresh]);
|
||||
|
||||
const indexedIds = useMemo(() => new Set(index?.prompts.map((prompt) => prompt.id)), [index]);
|
||||
const indexed = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
const turns = new Map<string, PromptAnchor | null>();
|
||||
for (const prompt of index?.prompts ?? []) {
|
||||
ids.add(prompt.id);
|
||||
if (prompt.turnId) turns.set(prompt.turnId, turns.has(prompt.turnId) ? null : prompt);
|
||||
}
|
||||
return { ids, turns };
|
||||
}, [index]);
|
||||
const localCache = useRef<{ index: typeof index; users: UIMessage[]; prompts: PromptAnchor[] }>();
|
||||
const prompts = useMemo(() => {
|
||||
if (!enabled) return userPromptAnchors(messages);
|
||||
if (!currentScope || index?.key !== key) return [];
|
||||
// Keep live prompts and legacy prompts backfilled by the history reader
|
||||
// navigable, even when they have no persisted transcript cursor yet.
|
||||
const users = messages.filter((message) => message.role === "user" && !indexedIds.has(message.id));
|
||||
// Live rows can still have optimistic render ids after admission. Match the
|
||||
// host's unambiguous original transport id and content, not text alone.
|
||||
const users = messages.filter((message) => {
|
||||
if (message.role !== "user" || indexed.ids.has(message.id)) return false;
|
||||
const admitted = message.turnId ? indexed.turns.get(message.turnId) : null;
|
||||
return !admitted || admitted.preview !== message.content.trim().slice(0, 320);
|
||||
});
|
||||
if (!users.length) return index.prompts;
|
||||
const cached = localCache.current;
|
||||
if (cached?.index === index && users.length === cached.users.length
|
||||
&& users.every((user, position) => user === cached.users[position])) return cached.prompts;
|
||||
const local = userPromptAnchors(messages).filter((prompt) => !indexedIds.has(prompt.id));
|
||||
const merged = [...index.prompts, ...local].sort((a, b) => a.createdAt - b.createdAt)
|
||||
.map((prompt, position) => ({ ...prompt, index: position }));
|
||||
const localIds = new Set(users.map((message) => message.id));
|
||||
const local = userPromptAnchors(messages).filter((prompt) => localIds.has(prompt.id));
|
||||
// Directory order is logical admission order. Unknown legacy times are zero,
|
||||
// not a reason to move an old prompt ahead of its preceding inputs.
|
||||
const merged = [...index.prompts, ...local].map((prompt, position) => ({ ...prompt, index: position }));
|
||||
localCache.current = { index, users, prompts: merged };
|
||||
return merged;
|
||||
}, [currentScope, enabled, index, indexedIds, key, messages]);
|
||||
}, [currentScope, enabled, index, indexed, key, messages]);
|
||||
|
||||
const updateMessages = useCallback((update: (messages: UIMessage[]) => UIMessage[]) => {
|
||||
setPages((current) => current.map((page) => ({ ...page, messages: update(page.messages) })));
|
||||
|
||||
@@ -2,9 +2,9 @@ import i18n from "i18next";
|
||||
|
||||
import { normalizeLocale } from "@/i18n/config";
|
||||
|
||||
/** Loose ISO-or-epoch parser; returns ``null`` for missing/invalid input. */
|
||||
/** Loose ISO-or-epoch parser; zero denotes an unknown persisted message time. */
|
||||
function parseDate(value: string | number | null | undefined): Date | null {
|
||||
if (value === null || value === undefined || value === "") return null;
|
||||
if (value === null || value === undefined || value === "" || value === 0) return null;
|
||||
const d = new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
@@ -421,9 +421,9 @@ export function closeThreadProjectionAnswer(
|
||||
}
|
||||
|
||||
function projectionCreatedAt(event: ThreadProjectionEvent, options: ThreadProjectionOptions): number {
|
||||
return typeof event.created_at_ms === "number" && Number.isFinite(event.created_at_ms)
|
||||
return typeof event.created_at_ms === "number" && Number.isFinite(event.created_at_ms) && event.created_at_ms >= 0
|
||||
? event.created_at_ms
|
||||
: options.now;
|
||||
: options.persisted ? 0 : options.now;
|
||||
}
|
||||
|
||||
function projectionMessageId(
|
||||
@@ -785,7 +785,7 @@ export function projectThreadEvent(
|
||||
);
|
||||
Object.assign(state, resetThreadProjectionCursor(state, state.messages));
|
||||
const media = event.media_urls?.map((item) => toMediaAttachment(item));
|
||||
const turn = turnFieldsForProjection(state, event, "user");
|
||||
const turn = turnFieldsFromEvent(event, "user");
|
||||
const row: UIMessage = {
|
||||
id: projectionMessageId(event, options),
|
||||
role: "user",
|
||||
@@ -999,13 +999,10 @@ export function projectThreadEvent(
|
||||
|
||||
export function projectThreadEvents(events: ThreadProjectionEvent[]): UIMessage[] {
|
||||
let state = createThreadProjectionState();
|
||||
const fallbackNow = Date.now();
|
||||
events.forEach((event, index) => {
|
||||
state = projectThreadEvent(state, event, {
|
||||
createId: () => `history-${index}`,
|
||||
now: typeof event.created_at_ms === "number"
|
||||
? event.created_at_ms
|
||||
: fallbackNow + index,
|
||||
now: 0,
|
||||
persisted: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -50,3 +50,17 @@ it("lets users type into prompt search immediately after opening it", async () =
|
||||
expect(onJumpToPrompt).toHaveBeenCalledWith("two");
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
|
||||
it("keeps an unknown recovered time blank while the prompt remains navigable", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onJumpToPrompt = vi.fn();
|
||||
render(<PromptNavigator messages={[
|
||||
{ id: "undated", role: "user", content: "Undated recovered input", createdAt: 0 },
|
||||
]} onJumpToPrompt={onJumpToPrompt} />);
|
||||
await user.click(screen.getByRole("button", { name: "Message navigation" }));
|
||||
const prompt = screen.getByRole("button", { name: "Jump to message: Undated recovered input" });
|
||||
expect(prompt.textContent).toBe("Undated recovered input");
|
||||
await user.click(prompt);
|
||||
expect(onJumpToPrompt).toHaveBeenCalledWith("undated");
|
||||
});
|
||||
@@ -131,3 +131,16 @@ describe("canonical thread event projection", () => {
|
||||
expect(messages[0].activitySegmentId).toBe(messages[1].activitySegmentId);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
it("uses deterministic unknown replay time and preserves distinct same-text inputs", () => {
|
||||
const events: ThreadProjectionEvent[] = [
|
||||
{ event: "user_message", chat_id: "chat", text: "same", starts_turn: true, turn_id: "input-one", projection_id: "u1" },
|
||||
{ event: "turn_end", chat_id: "chat", turn_id: "input-one" },
|
||||
{ event: "user_message", chat_id: "chat", text: "same", starts_turn: true, turn_id: "input-two", projection_id: "u2" },
|
||||
];
|
||||
const messages = projectThreadEvents(events);
|
||||
expect(messages.map((message) => message.id)).toEqual(["u1", "u2"]);
|
||||
expect(messages.map((message) => message.createdAt)).toEqual([0, 0]);
|
||||
expect(projectThreadEvents(events)).toEqual(messages);
|
||||
});
|
||||
@@ -143,3 +143,35 @@ it("reuses the full directory during token updates and conditional revalidation"
|
||||
expect(api.fetchPromptIndex).toHaveBeenLastCalledWith("test", "a", expect.any(AbortSignal), { prompts: index, revision: "first" });
|
||||
expect(result.current.prompts).toBe(anchors);
|
||||
});
|
||||
|
||||
|
||||
it("merges a live input by transport identity without adding an anchor or reordering unknown-time prompts", async () => {
|
||||
const recovered = [
|
||||
{ id: "old", preview: "older", answerPreview: "", createdAt: 1000, cursor: "0", turnId: "old-input" },
|
||||
{ id: "persisted", preview: "same", answerPreview: "answer", createdAt: 0, cursor: "1", turnId: "input" },
|
||||
];
|
||||
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: recovered, revision: "recovered" });
|
||||
const users: UIMessage[] = [
|
||||
{ id: "optimistic", role: "user", content: "same", createdAt: 2000, turnId: "input" },
|
||||
{ id: "distinct", role: "user", content: "same", createdAt: 3000, turnId: "other-input" },
|
||||
];
|
||||
const { result, rerender } = renderHook(({ key, version }) => usePromptHistory(key, version, users), {
|
||||
wrapper: wrapper(), initialProps: { key: "a", version: 1 },
|
||||
});
|
||||
await waitFor(() => expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["old", "persisted", "distinct"]));
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({ schemaVersion: 3, projection: "events", events: [
|
||||
{ event: "user_message", chat_id: "a", text: "same", starts_turn: true, projection_id: "persisted", turn_id: "input", created_at_ms: 0 },
|
||||
{ event: "message", chat_id: "a", text: "answer", projection_id: "answer" },
|
||||
] });
|
||||
await act(async () => result.current.jump("persisted"));
|
||||
expect(result.current.target?.id).toBe("persisted");
|
||||
expect(result.current.window?.messages[0].createdAt).toBe(0);
|
||||
rerender({ key: "a", version: 2 });
|
||||
await waitFor(() => expect(api.fetchPromptIndex).toHaveBeenCalledTimes(2));
|
||||
expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["old", "persisted", "distinct"]);
|
||||
rerender({ key: "b", version: 1 });
|
||||
await waitFor(() => expect(api.fetchPromptIndex).toHaveBeenCalledTimes(3));
|
||||
expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["old", "persisted", "distinct"]);
|
||||
expect(result.current.window).toBeNull();
|
||||
expect(result.current.target).toBeNull();
|
||||
});
|
||||
Reference in new issue
Block a user