Skip to content

Commit 86fcaed

Browse files
committed
Preserve pending setup prompts and message action order
Keep pending model setup prompts and session recovery until dispatch or queue insertion is accepted. Defer retries during another send, resolve readiness and preset editing for the pending chat, and preserve new composer drafts. Prevent retries from entering another selected chat's queue. Preserve Detail, Copy, Speak order when actions are inserted or replaced, without remounting unchanged controls. Add behavioral and browser regressions, including preset-switch draft persistence, and update the WebUI contracts. Validation: 84 focused tests passed; git diff --check passed.
1 parent 39960e6 commit 86fcaed

9 files changed

Lines changed: 239 additions & 35 deletions

‎tests/test_model_gate_dispatch_race.py‎

Lines changed: 125 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import re
2+
import shutil
23
from pathlib import Path
34

5+
import pytest
6+
7+
from test_chat_loading_refresh import run_module
8+
49
STORE = Path("webui/components/chat/model-gate-store.js").read_text(encoding="utf-8")
510

611

@@ -14,14 +19,14 @@ def test_dispatch_captures_pending_before_await():
1419
body = _function_source("dispatchPendingIfConfigured")
1520
capture_at = body.index("const pending = this.pending;")
1621
latch_at = body.index("this.dispatching = true;")
17-
await_at = body.index("await this.canSendToModel();")
22+
await_at = body.index("await this.canSendToModel(pending.context);")
1823
assert capture_at < await_at
1924
assert latch_at < await_at
2025

2126

2227
def test_dispatch_rechecks_pending_identity_after_await():
2328
body = _function_source("dispatchPendingIfConfigured")
24-
await_at = body.index("await this.canSendToModel();")
29+
await_at = body.index("await this.canSendToModel(pending.context);")
2530
recheck_at = body.index("this.pending !== pending")
2631
assert await_at < recheck_at
2732

@@ -37,3 +42,121 @@ def test_dispatch_never_reads_message_without_pending_guard():
3742
def test_open_advanced_catch_reports_readable_message():
3843
body = _function_source("openAdvancedModelConfiguration")
3944
assert "error?.message" in body
45+
46+
47+
GATE_HARNESS = """
48+
const saved = new Map();
49+
const sessionStorage = {setItem: (key, value) => saved.set(key, value),
50+
getItem: key => saved.get(key) || null, removeItem: key => saved.delete(key)};
51+
const document = {addEventListener() {}};
52+
const createStore = (_name, model) => model;
53+
const modelConfigStore = {}, onboardingStore = {};
54+
const requests = [];
55+
const callJsonApi = async (endpoint, data) => {
56+
requests.push({endpoint, data});
57+
return {model_configured: true};
58+
};
59+
"""
60+
61+
62+
@pytest.mark.skipif(not shutil.which("node"), reason="Node.js is required")
63+
def test_gate_keeps_saved_prompt_until_an_idle_send_accepts_it():
64+
run_module("webui/components/chat/model-gate-store.js", GATE_HARNESS, """
65+
store.start({message: 'Original prompt', attachments: [], messageId: 'pending-id', context: 'chat-a'});
66+
const pending = store.pending;
67+
const savedPrompt = [...saved.values()][0];
68+
let sends = 0, accepted = false;
69+
globalThis.sendMessage = async () => { sends++; return accepted; };
70+
globalThis.sendMessage.inFlight = true;
71+
await store.dispatchPendingIfConfigured();
72+
assert.equal(store.pending, pending);
73+
assert.equal([...saved.values()][0], savedPrompt);
74+
assert.equal(store.connected, false);
75+
assert.equal(sends, 0);
76+
77+
globalThis.sendMessage.inFlight = false;
78+
await store.dispatchPendingIfConfigured();
79+
assert.equal(store.pending, pending, 'failed send discarded the pending prompt');
80+
assert.equal([...saved.values()][0], savedPrompt);
81+
assert.equal(store.connected, false);
82+
assert.equal(requests.at(-1).data.context_id, 'chat-a');
83+
84+
accepted = true;
85+
await store.dispatchPendingIfConfigured();
86+
assert.equal(sends, 2);
87+
assert.equal(store.pending, null);
88+
assert.equal(saved.size, 0);
89+
assert.equal(store.connected, true);
90+
""")
91+
92+
93+
@pytest.mark.skipif(not shutil.which("node"), reason="Node.js is required")
94+
def test_gate_rechecks_send_busy_state_after_readiness_await():
95+
run_module("webui/components/chat/model-gate-store.js", GATE_HARNESS, """
96+
store.start({message: 'Original prompt', attachments: [], messageId: 'pending-id', context: 'chat-a'});
97+
const pending = store.pending;
98+
let resolve;
99+
store.canSendToModel = () => new Promise(done => { resolve = done; });
100+
let sends = 0;
101+
globalThis.sendMessage = async () => { sends++; return true; };
102+
const dispatch = store.dispatchPendingIfConfigured();
103+
globalThis.sendMessage.inFlight = true;
104+
resolve(true);
105+
await dispatch;
106+
assert.equal(sends, 0);
107+
assert.equal(store.pending, pending);
108+
assert.equal(store.connected, false);
109+
assert.equal(saved.size, 1);
110+
""")
111+
112+
113+
@pytest.mark.skipif(not shutil.which("node"), reason="Node.js is required")
114+
def test_rejected_first_send_retries_after_rendering_without_touching_new_draft():
115+
index = Path("webui/index.js").read_text(encoding="utf-8")
116+
start = index.index("export async function sendMessage(")
117+
end = index.index("globalThis.sendMessage = sendMessage;", start)
118+
run_module("webui/components/chat/model-gate-store.js", GATE_HARNESS, index[start:end] + """
119+
const modelGateStore = store;
120+
const context = 'chat-a';
121+
const attachmentsStore = {getAttachmentsForSending: () => []};
122+
const inputStore = {message: 'Original prompt', reset() { this.message = ''; }};
123+
const chatsStore = {selectedContext: {running: false}};
124+
const messageQueueStore = {hasQueue: false};
125+
const callJsExtensions = async () => {};
126+
const msgs = {scrollOnNextProcessGroup() {}};
127+
const forceScrollChatToBottom = () => {}, adjustTextareaHeight = () => {};
128+
const generateGUID = () => 'pending-id', setContext = () => {};
129+
const toastFetchError = (_text, error) => { throw error; };
130+
const messages = [];
131+
const api = {fetchApi: async (_url, options) => {
132+
messages.push(JSON.parse(options.body));
133+
return {json: async () => messages.length === 1
134+
? {model_not_configured: true, context}
135+
: {message: 'Message received.', context}};
136+
}};
137+
const setMessages = async rows => {
138+
if (rows.some(row => row.type === 'model_setup_gate')) {
139+
inputStore.message = 'New unsent draft';
140+
await store.dispatchPendingIfConfigured();
141+
}
142+
};
143+
globalThis.sendMessage = sendMessage;
144+
await sendMessage();
145+
await new Promise(setImmediate);
146+
assert.equal(messages.length, 2, 'the pending prompt was never retried after the send settled');
147+
assert.equal(messages[1].text, 'Original prompt');
148+
assert.equal(messages[1].message_id, 'pending-id');
149+
assert.equal(inputStore.message, 'New unsent draft');
150+
assert.equal(store.pending, null);
151+
assert.equal(saved.size, 0);
152+
assert.equal(store.connected, true);
153+
154+
store.start({message: 'Prompt for another chat', attachments: [], messageId: 'other-id', context: 'chat-b'});
155+
chatsStore.selectedContext.running = true;
156+
messageQueueStore.addToQueue = () => { throw new Error('pending prompt entered the selected chat queue'); };
157+
await store.dispatchPendingIfConfigured();
158+
assert.equal(messages.at(-1).context, 'chat-b');
159+
assert.equal(messages.at(-1).text, 'Prompt for another chat');
160+
assert.equal(inputStore.message, 'New unsent draft');
161+
assert.equal(store.pending, null);
162+
""")

‎tests/test_webui_plugin_process_types.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,84 @@ def serve(route):
6868
browser.close()
6969

7070

71+
def test_action_buttons_keep_order_and_mounted_nodes_during_updates(page):
72+
page.evaluate("""async () => {
73+
const {createActionButton, syncActionButtons} = await import(
74+
'/components/messages/action-buttons/simple-action-buttons.js');
75+
const bar = document.createElement('div');
76+
const expand = document.createElement('button');
77+
expand.className = 'expand-btn';
78+
const plugin = document.createElement('button');
79+
bar.append(expand, plugin);
80+
document.body.append(bar);
81+
const buttons = names => names.map(name => createActionButton(name));
82+
const order = () => [...bar.querySelectorAll('.action-button')]
83+
.map(button => button.dataset.actionKey.split(':')[0]).join(',');
84+
try {
85+
syncActionButtons(bar, buttons(['detail', 'copy', 'speak']));
86+
check(order() === 'detail,copy,speak', 'new action bar reversed its actions');
87+
const mounted = [...bar.querySelectorAll('.action-button')];
88+
mounted[1].focus();
89+
const observer = new MutationObserver(() => {});
90+
observer.observe(bar, {childList:true});
91+
syncActionButtons(bar, buttons(['detail', 'copy', 'speak']));
92+
check(observer.takeRecords().length === 0, 'stream update remounted unchanged buttons');
93+
observer.disconnect();
94+
check(document.activeElement === mounted[1], 'stream update lost button focus');
95+
syncActionButtons(bar, buttons(['detail', 'other', 'speak']));
96+
check(order() === 'detail,other,speak', 'replacement moved behind a retained action');
97+
check(bar.querySelector('.action-speak') === mounted[2], 'unchanged trailing action was remounted');
98+
syncActionButtons(bar, buttons(['copy', 'speak']));
99+
check(order() === 'copy,speak', 'omitting an action changed the remaining order');
100+
check(expand.parentNode === bar && plugin.parentNode === bar, 'extension or collapse action was removed');
101+
check(bar.lastChild === plugin, 'standard actions moved behind the plugin action');
102+
} finally {
103+
bar.remove();
104+
}
105+
}""")
106+
107+
108+
def test_preset_switch_preserves_composer_and_saved_chat_draft(page):
109+
page.evaluate("""async () => {
110+
const input = (await import('/components/chat/input/input-store.js')).store;
111+
const chats = (await import('/components/sidebar/chats/chats-store.js')).store;
112+
const {switcherState, switcherMethods} = await import('/plugins/_model_config/webui/switcher-mixin.js');
113+
const previousFetch = window.fetch, previousAlpine = window.Alpine, previousChat = chats.selected;
114+
const requests = [];
115+
const editor = document.createElement('div');
116+
editor.id = 'chat-input';
117+
editor.contentEditable = 'true';
118+
document.body.append(editor);
119+
try {
120+
chats.selected = 'draft-chat';
121+
window.fetch = async (url, options) => {
122+
if (url === '/api/csrf_token') return new Response(JSON.stringify({ok:true, token:'fixture'}));
123+
requests.push(JSON.parse(options.body));
124+
return new Response(JSON.stringify({ok:true, preset_name:'Fast'}));
125+
};
126+
input.mountEditor(editor);
127+
input.message = 'An unfinished prompt\\nwith a second line';
128+
const draft = input.message;
129+
window.Alpine = {store: name => name === 'chats' ? {selected:'draft-chat'} : undefined};
130+
const switcher = {...switcherState, ...switcherMethods,
131+
loadSwitcherState: async () => ({allowed:true, presets:[{name:'Fast'}],
132+
override:{preset_name:'Fast'}, configuredPreset:'Default', effectivePreset:'Fast'})};
133+
check(await switcher.selectPresetSwitch('draft-chat', 'Fast'), 'preset switch failed');
134+
await switcher.refreshSwitcher('draft-chat');
135+
check(switcher.switcherEffectivePreset === 'Fast', 'preset selection did not change');
136+
check(requests[0].context_id === 'draft-chat', 'preset switch targeted another chat');
137+
check(input.message === draft && editor.textContent === draft, 'preset switch cleared the composer');
138+
check(sessionStorage.getItem('a0:chat-draft:draft-chat') === draft, 'preset switch erased session recovery');
139+
} finally {
140+
window.fetch = previousFetch;
141+
window.Alpine = previousAlpine;
142+
input.unmountEditor(editor);
143+
chats.selected = previousChat;
144+
editor.remove();
145+
}
146+
}""")
147+
148+
71149
@pytest.mark.parametrize("mode", ["collapsed", "current", "expanded"])
72150
@pytest.mark.parametrize("replay", [False, True])
73151
@pytest.mark.parametrize("enabled", [False, True])

‎tests/test_webui_send_pause_responsiveness_static.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ def test_pause_snapshots_respect_in_flight_clicks() -> None:
2222
def test_send_message_guards_against_in_flight_duplicates() -> None:
2323
index_js = read("webui", "index.js")
2424

25-
assert "if (sendMessage.inFlight) return;" in index_js
25+
assert "if (sendMessage.inFlight) return false;" in index_js
2626
assert "sendMessage.inFlight = true;" in index_js
2727
fn = index_js[index_js.index("export async function sendMessage") : index_js.index("globalThis.sendMessage = sendMessage;")]
28-
assert fn.index("if (sendMessage.inFlight) return;") < fn.index("callJsExtensions")
28+
assert fn.index("if (sendMessage.inFlight) return false;") < fn.index("callJsExtensions")
2929
assert "finally {" in fn
3030
assert "sendMessage.inFlight = false;" in fn.split("finally {", 1)[1].split("}", 1)[0]

‎webui/AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
- Component HTML loaded by the shared loader may include `<title>`, module scripts, body content, and scoped styles; modal content uses the same loader path.
2929
- Do not bypass WebSocket origin/auth/CSRF assumptions from frontend code.
3030
- `index.js` rechecks the selected context after asynchronous snapshot hooks and message rendering; an older snapshot must not replace selection or sidebar state after a chat switch or creation.
31+
- `index.js`'s `sendMessage` reports accepted dispatch or queue insertion with `true`; busy, rejected, or failed sends must not consume a setup-gate prompt. Release its send latch before resuming a deferred gate retry.
3132
- Avoid editing vendored files unless intentionally updating the vendor asset.
3233
- Startup scripts in `index.html` must be local and non-parser-blocking: use ES modules, `defer`, or `async` for every script with `src`.
3334
- Baseline main and login pages must load scripts, styles, fonts, and images from same-origin vendored or first-party assets so they remain usable without internet access.

‎webui/components/chat/AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
- `navigation/` owns chat navigation state.
1313
- `top-section/` owns chat header/top area.
1414
- `model-gate-store.js` and `model-setup-gate.html` own the deferred in-thread model setup gate.
15-
- Gate dispatch (`dispatchPendingIfConfigured`) must capture `pending` and raise its latch before any await, and re-verify pending identity after awaits; pending is never re-read from the store after an await point.
15+
- Gate dispatch (`dispatchPendingIfConfigured`) captures `pending` before awaiting and uses that object for the payload; re-check its identity and the send latch after readiness resolves. Keep pending state and session recovery until the send is accepted. Busy sends defer retry until `sendMessage` settles; readiness and preset-editor reads use the pending chat's context. A retry for another context must never enter the selected chat's queue.
1616

1717
## Local Contracts
1818

@@ -21,7 +21,7 @@
2121
- Do not bypass CSRF or WebSocket state-sync expectations.
2222
- The shared composer can be mounted on the Welcome screen with no selected chat; sending from that state must create and select a chat context before dispatch.
2323
- Text-only and attachment sends must render the first user turn immediately with the request message ID so the backend log merges into the same row.
24-
- Unsent composer text is kept as a separate browser-session draft for each selected chat and restored when switching contexts; a Welcome-screen prompt must follow the chat created for its first send.
24+
- Unsent composer text is kept as a separate browser-session draft for each selected chat and restored when switching contexts; a Welcome-screen prompt must follow the chat created for its first send. Preset changes and setup-gate retries must preserve any new unsent composer draft.
2525
- Composer text uses the main UI font by default; typing a triple-backtick fence and pressing Enter turns that line into a visual code block that serializes back to fenced Markdown, while pasted fenced Markdown stays plain text.
2626
- The contenteditable composer sizes naturally between its CSS minimum and maximum heights; do not freeze measured scroll heights into pixels during mounting or editing.
2727
- The backend rejects dispatches when no chat model is configured: a `user_message_ui` extension in `_model_config` flags the chat and `/message_async` returns a `model_not_configured` payload before logging or dispatching. The client opens the setup gate from that response and must not round-trip a per-send configuration pre-check.

‎webui/components/chat/model-gate-store.js‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,9 @@ export const store = createStore("modelGate", {
5252
});
5353
},
5454

55-
async canSendToModel() {
55+
async canSendToModel(contextId) {
5656
try {
57-
const data = await callJsonApi("/plugins/_model_config/model_config_get", {});
57+
const data = await callJsonApi("/plugins/_model_config/model_config_get", { context_id: contextId });
5858
this.applyModelStatus(data);
5959
if (!data?.model_configured) await this.refreshConnectedAccountState();
6060
return !!data?.model_configured;
@@ -135,7 +135,7 @@ export const store = createStore("modelGate", {
135135

136136
async openAdvancedModelConfiguration() {
137137
try {
138-
const data = await callJsonApi("/plugins/_model_config/model_config_get", {});
138+
const data = await callJsonApi("/plugins/_model_config/model_config_get", { context_id: this.pending?.context || "" });
139139
await modelConfigStore.openPresetEditor(
140140
data?.selected_preset || data?.configured_preset || "Default"
141141
);
@@ -152,22 +152,23 @@ export const store = createStore("modelGate", {
152152
async dispatchPendingIfConfigured() {
153153
this.init();
154154
const pending = this.pending;
155-
if (this.dispatching || !pending) return;
155+
if (this.dispatching || !pending || globalThis.sendMessage?.inFlight) return;
156156
this.dispatching = true;
157157
try {
158-
const configured = await this.canSendToModel();
159-
if (!configured || this.pending !== pending) return;
160-
this.pending = null;
161-
this.connected = true;
162-
this.clearSavedPending();
163-
await globalThis.sendMessage?.({
158+
const configured = await this.canSendToModel(pending.context);
159+
if (!configured || this.pending !== pending || globalThis.sendMessage?.inFlight) return;
160+
const accepted = await globalThis.sendMessage?.({
164161
skipExtensions: true,
165162
preserveInput: true,
166163
message: pending.message,
167164
attachments: pending.attachments,
168165
messageId: pending.messageId,
169166
context: pending.context,
170167
});
168+
if (!accepted || this.pending !== pending) return;
169+
this.pending = null;
170+
this.connected = true;
171+
this.clearSavedPending();
171172
} finally {
172173
this.dispatching = false;
173174
}

‎webui/components/messages/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
- Terminal output keeps text-size adjustment at 100% so mobile browsers do not inflate its wide, unwrapped content when streamed or expanded; preserve horizontal scrolling and normal browser zoom.
1919
- Keep message action chrome out of text selection so copy/paste captures message content without button labels or icons.
2020
- Reconcile standard action buttons in place during streamed updates so hover, focus, tooltips, and click feedback survive while handlers receive the latest message data; position buttons by index and never re-insert an already-mounted button, since re-inserting detaches and remounts it mid-stream. Preserve extension-owned buttons in the same action bar.
21-
- Order standard message actions as Detail, Copy, then Speak; omit unavailable actions without changing the relative order of the remaining controls. Plugin-rendered message actions must follow the same order.
21+
- Order standard message actions as Detail, Copy, then Speak; omit unavailable actions without changing the relative order of the remaining controls. Insert new or replaced actions before the next retained action or the stable extension anchor, never using a newly inserted action as that anchor. Plugin-rendered message actions must follow the same order.
2222
- Collapsible action rows keep the hover-revealed `Show less` control laid out with reserved space on pointer devices; hover reveals it through opacity only so the row height never shifts, and its opacity fade matches the row fade so it never disappears ahead of sibling buttons.
2323
- Keep collapsed process-step detail text out of the DOM; opening a step may materialize its current cached log data and collapsing it must discard that heavy detail again without removing extension action hooks.
2424
- Preference-driven process detail modes must await the same materialization path as manual expansion and accept an explicit chat-history target for off-screen window staging. `STEP` opens only the current non-utility step at the live tail; historical windows must not invent a current step at their boundary.

0 commit comments

Comments
 (0)