Skip to content

The agent that grows with you

fix(onboarding): review fixes for reconnect replay and the setup slash gate

alt-glitchbda3a363e969
diff --git a/apps/desktop/src/api/canonical-clarify-lifecycle.test.ts b/apps/desktop/src/api/canonical-clarify-lifecycle.test.ts
index 2b36083dff3..7407773373c 100644
--- a/apps/desktop/src/api/canonical-clarify-lifecycle.test.ts
+++ b/apps/desktop/src/api/canonical-clarify-lifecycle.test.ts
@@ -124,3 +124,16 @@ test('snapshots expose batch question params without losing already locked answe
id: 'question-1', method: 'clarify', params: { session_id: 'waiting', questions, answers }
}])
})
+
+test('a snapshot keeps the owner\'s server requests beside the projected prompts', () => {
+ const card = { id: 'srq-1', method: 'setup_beat', params: { session_id: 'waiting', beat: 'name', card: {} } }
+
+ const snapshot = new CanonicalDesktopProtocol().result('session.activate', { session_id: 'waiting' }, {
+ session_id: 'waiting', revision: 1, execution_generation: 3, open_requests: [card], prompts: [
+ { kind: 'approval', prompt_id: 'approve-1', command: 'ls', choices: ['once', 'deny'], execution_generation: 3 }
+ ]
+ })
+
+ expect(snapshot.open_requests.map((entry: { id: string }) => entry.id)).toEqual(['srq-1', 'approve-1'])
+ expect(snapshot.open_requests[0]).toEqual(card)
+})
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 3f596f6ea06..8fc55915e53 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -733,9 +733,10 @@ export class CanonicalDesktopProtocol {
return projected
})
- const open_requests = prompts.map((prompt: Record<string, unknown>) => ({
+ // The owner's server requests (setup cards, batch clarify, sudo) ride beside the projected prompts.
+ const open_requests = [...(value.open_requests ?? []), ...prompts.map((prompt: Record<string, unknown>) => ({
id: prompt.prompt_id, method: prompt.kind, params: canonicalPromptParams(prompt.kind, sid, prompt)
- }))
+ }))]
return { ...value, open_requests, pending_approval: prompts.find((p: any) => p.kind === 'approval'), pending_clarify: prompts.find((p: any) => p.kind === 'clarify'), info: { ...value.info, stored_session_id: value.stored_session_id, pending_submissions: value.pending_submissions, replay_epoch: value.replay_epoch, last_sequence: value.last_sequence, execution_generation: value.execution_generation, running: value.running } }
}
diff --git a/apps/desktop/src/app/chat/composer/hooks/slash-localization.test.tsx b/apps/desktop/src/app/chat/composer/hooks/slash-localization.test.tsx
index 68c982754a9..0c9d4b5d3d5 100644
--- a/apps/desktop/src/app/chat/composer/hooks/slash-localization.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/slash-localization.test.tsx
@@ -102,7 +102,7 @@ describe('desktop slash description localization', () => {
function Probe() {
api.setLocale = useI18n().setLocale
- api.search = useSlashCompletions({ gateway: { request } as unknown as HermesGateway }).adapter.search
+ api.search = useSlashCompletions({ gateway: { request } as unknown as HermesGateway }).adapter?.search
return null
}
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-completions-owner-route.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-completions-owner-route.test.tsx
index 12746768201..f247931e813 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-completions-owner-route.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-completions-owner-route.test.tsx
@@ -90,7 +90,7 @@ describe('composer completions route to the session owner', () => {
const api: { search?: Search } = {}
function Probe() {
- api.search = useSlashCompletions({ gateway, sessionId: SESSION }).adapter.search
+ api.search = useSlashCompletions({ gateway, sessionId: SESSION }).adapter?.search
return null
}
@@ -128,7 +128,7 @@ describe('composer completions route to the session owner', () => {
const api: { search?: Search } = {}
function Probe() {
- api.search = useSlashCompletions({ gateway, sessionId: SESSION }).adapter.search
+ api.search = useSlashCompletions({ gateway, sessionId: SESSION }).adapter?.search
return null
}
@@ -160,7 +160,7 @@ describe('composer completions route to the session owner', () => {
const api: { search?: Search } = {}
function Probe() {
- api.search = useAtCompletions({ cwd: '/repo', gateway, sessionId: SESSION }).adapter.search
+ api.search = useAtCompletions({ cwd: '/repo', gateway, sessionId: SESSION }).adapter?.search
return null
}
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
index 9fba46206e0..f56d2f4c6ac 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
@@ -1048,6 +1048,19 @@ describe('useComposerSubmit with a setup card waiting in the onboarding chat', (
expect($notifications.get().map(note => note.kind)).toEqual(['info'])
})
+ it('queues no slash command while setup is in progress (Cmd/Ctrl+Enter)', () => {
+ $onboardingPhase.set('shown')
+ $onboardingSession.set({ connectionId: null, runId: 'run-1', runtimeId: 'runtime-session', storedId: 'stored-session' })
+
+ const { clearDraft, hook, onSubmit, queueCurrentDraft } = renderSubmitHook({ busy: true, text: '/help' })
+
+ act(() => hook.result.current.queueDraft())
+
+ expect(queueCurrentDraft).not.toHaveBeenCalled()
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(clearDraft).not.toHaveBeenCalled()
+ })
+
it('runs slash commands as usual in the same chat once setup has ended', () => {
$onboardingPhase.set('done')
$onboardingSession.set({ connectionId: null, runId: 'run-1', runtimeId: 'runtime-session', storedId: 'stored-session' })
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index dc63974f434..dd1f256f25f 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@ -365,6 +365,19 @@ export function useComposerSubmit({
return yielded ? 'yielded' : null
}
+ // Slash commands come after setup. Every send action asks here first, so the words stay put and one
+ // note (re-shown, never stacked) says why.
+ const refusedDuringSetup = (text: string): boolean => {
+ if (!isSlashCommandText(text) || !isOnboardingChat(sessionId)) {
+ return false
+ }
+
+ notify({ id: 'onboarding-slash-off', kind: 'info', message: t.firstRun.slashOffBody, title: t.firstRun.slashOffTitle })
+ focusInput()
+
+ return true
+ }
+
const submitDraft = () => {
if (disabled) {
return
@@ -395,11 +408,7 @@ export function useComposerSubmit({
const text = pathifyRefs(draftRef.current)
const payloadPresent = text.trim().length > 0 || attachments.length > 0
- // Slash commands come after setup: the words stay put, and one note (re-shown, never stacked) says why.
- if (isSlashCommandText(text) && isOnboardingChat(sessionId)) {
- notify({ id: 'onboarding-slash-off', kind: 'info', message: t.firstRun.slashOffBody, title: t.firstRun.slashOffTitle })
- focusInput()
-
+ if (refusedDuringSetup(text)) {
return
}
@@ -514,7 +523,7 @@ export function useComposerSubmit({
}
const queueDraft = () => {
- if (disabled || !busy) {
+ if (disabled || !busy || refusedDuringSetup(draftRef.current)) {
return
}
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.test.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.test.ts
index bab3d62b8d8..c582ae52b83 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.test.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.test.ts
@@ -68,7 +68,7 @@ function mountTrigger(editor: HTMLDivElement, items: Unstable_TriggerItem[], sla
editorRef,
requestMainFocus: vi.fn(),
setComposerText,
- slash: { adapter, loading: false, off: slashOff }
+ slash: { adapter: slashOff ? null : adapter, loading: false }
})
)
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts
index e5b7e234003..17606d9cf22 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts
@@ -88,8 +88,6 @@ export function rebuildAroundCaret(editor: HTMLDivElement, tokenLength: number,
interface CompletionSource {
adapter: Unstable_TriggerAdapter | null
loading: boolean
- /** Opens no menu: `/` in the onboarding chat before its setup ends. */
- off?: boolean
}
interface UseComposerTriggerOptions {
@@ -146,7 +144,8 @@ export function useComposerTrigger({
setTriggerActiveExplicit(false)
}, [])
- const slashOff = Boolean(slash.off)
+ // A `/` source with no adapter offers no menu (the onboarding chat before its setup ends).
+ const slashOff = !slash.adapter
const refreshTrigger = useCallback(() => {
const editor = editorRef.current
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.test.tsx
index aad05c65b2a..d044bb53c75 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.test.tsx
@@ -46,7 +46,7 @@ function harness(gateway: HermesGateway, options: { profile?: string } = {}) {
function Probe() {
const { adapter } = useSlashCompletions({ gateway, ...options })
- api.search = adapter.search
+ api.search = adapter?.search
return null
}
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts
index 533fbf76169..c724c593b0e 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts
@@ -59,10 +59,9 @@ function commandText(value: string): string {
const SESSION_INLINE_LIMIT = 7
export interface SlashCompletions {
- adapter: Unstable_TriggerAdapter
+ /** Null while this session offers no `/` menu: the onboarding chat before its setup ends. */
+ adapter: Unstable_TriggerAdapter | null
loading: boolean
- /** No `/` menu for this session: the onboarding chat before its setup ends. */
- off: boolean
}
/** Live `/` completions backed by the gateway's `complete.slash` RPC. */
@@ -359,5 +358,5 @@ export function useSlashCompletions(options: {
// Slash commands come after setup: none in the onboarding chat until its run ends.
const off = useStore(useMemo(() => onboardingChatStore(sessionId ?? null), [sessionId]))
- return { ...live, off }
+ return off ? { adapter: null, loading: false } : live
}
diff --git a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
index a275e6a0717..ea84ea5315e 100644
--- a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
@@ -307,7 +307,9 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
}
const before = textBeforeCaret(editor)
- const detected = detectTrigger(before ?? composerPlainText(editor))
+ const typed = detectTrigger(before ?? composerPlainText(editor))
+ // A `/` source with no adapter offers no menu (the onboarding chat before its setup ends).
+ const detected = typed?.kind === '/' && !slash.adapter ? null : typed
if (detected) {
const rect = editor.getBoundingClientRect()
@@ -326,7 +328,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
if (detected?.kind !== trigger?.kind || detected?.query !== trigger?.query) {
setTriggerActive(0)
}
- }, [trigger])
+ }, [slash.adapter, trigger])
const closeTrigger = useCallback(() => {
setTrigger(null)
diff --git a/gateway/local_desktop_ui.py b/gateway/local_desktop_ui.py
index 61d738d4bb6..6a9cfc46b66 100644
--- a/gateway/local_desktop_ui.py
+++ b/gateway/local_desktop_ui.py
@@ -214,7 +214,9 @@ def _ask(turn, agent, method, params, timeout):
live = authority.sessions.get(session_id)
if live is None:
return ""
- value = ask_viewer(live.event_stream, session_id, method, dict(params), timeout=timeout,
+ # Automatic window requests (reads, a preview click, the tour) are not handed to a reconnecting
+ # viewer again: a second delivery would repeat the action.
+ value = ask_viewer(live.event_stream, session_id, method, dict(params), timeout=timeout, replay=False,
cancelled=lambda: bool(getattr(agent, "_interrupt_requested", False)))
return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
diff --git a/gateway/session_server_requests.py b/gateway/session_server_requests.py
index 64d31eaefa6..10c9c0ba251 100644
--- a/gateway/session_server_requests.py
+++ b/gateway/session_server_requests.py
@@ -22,14 +22,16 @@ _POLL_S = 0.25
class _Pending:
- __slots__ = ("event", "events", "locked", "method", "params", "qids", "result", "session_id", "value")
+ __slots__ = ("event", "events", "locked", "method", "params", "qids", "replay", "result", "session_id", "value")
- def __init__(self, session_id, qids=None, events=None, method=None, params=None):
+ def __init__(self, session_id, qids=None, events=None, method=None, params=None, replay=True):
self.event = threading.Event()
self.session_id = session_id
self.method = method
- # The frame's params as sent, so a viewer that reconnects gets the request again.
+ # The frame's params as sent, so a viewer that reconnects gets the request again; ``replay`` False
+ # for an automatic window request (a preview click), which a second delivery would run twice.
self.params = params or {}
+ self.replay = replay
# The live session's own event stream the request went out on: one per authority (profile) and
# session mount, so a viewer of another profile's same-named session can never settle it.
self.events = events
@@ -95,10 +97,12 @@ def resolve(frame, *, session_ok=lambda session_id, events: True) -> bool:
return True
-def ask_viewer(events, session_id, method, params, *, cancelled=lambda: False, timeout=REQUEST_TIMEOUT_S) -> str:
+def ask_viewer(events, session_id, method, params, *, cancelled=lambda: False, timeout=REQUEST_TIMEOUT_S,
+ replay=True) -> str:
"""Send one one-string server→client request (``sudo``, ``secret``: ``ValueResult``) to the
- session's attached viewers and wait for its ``value``; "" on skip, interrupt, timeout or no viewer."""
- pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout)
+ session's attached viewers and wait for its ``value``; "" on skip, interrupt, timeout or no viewer.
+ ``replay=False``: a reconnecting viewer is not handed it again (``open_requests``)."""
+ pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout, replay=replay)
return pending.value if pending is not None else ""
@@ -123,7 +127,8 @@ def open_requests(events, session_id) -> list[dict]:
carried them (plus a batch's answers locked so far): what ``session.resume`` and
``session.events.since`` hand a reconnecting viewer to re-render (``OpenRequestEntry``)."""
with _lock:
- waiting_now = [(rid, p) for rid, p in _open.items() if p.session_id == session_id and p.events is events]
+ waiting_now = [(rid, p) for rid, p in _open.items()
+ if p.session_id == session_id and p.events is events and p.replay]
return [{"id": rid, "method": p.method,
"params": {**p.params, "answers": dict(p.locked)} if p.locked else dict(p.params)}
for rid, p in waiting_now]
@@ -163,11 +168,11 @@ def lock_answer(request_id, question_id, answer, *, session_ok=lambda session_id
return remaining
-def _ask(events, session_id, method, params, *, cancelled, timeout, qids=None):
+def _ask(events, session_id, method, params, *, cancelled, timeout, qids=None, replay=True):
if not events.fanout.transports():
return None
request_id = f"srq-{uuid.uuid4().hex[:12]}"
- pending = _Pending(session_id, qids, events, method, {"session_id": session_id, **params})
+ pending = _Pending(session_id, qids, events, method, {"session_id": session_id, **params}, replay)
with _lock:
_open[request_id] = pending
events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": method, "params": pending.params})
diff --git a/tests/gateway/test_server_request_resume_replay.py b/tests/gateway/test_server_request_resume_replay.py
index 7a15e512177..d21d276f1d8 100644
--- a/tests/gateway/test_server_request_resume_replay.py
+++ b/tests/gateway/test_server_request_resume_replay.py
@@ -11,7 +11,7 @@ import asyncio
import pytest
from tests.gateway.test_onboarding_on_the_authority import _desktop, _request, _Transport
-from tests.waiting import async_wait_until
+from tests.waiting import async_wait_until, wait_until
async def _reload(desktop):
@@ -53,3 +53,26 @@ async def test_a_resumed_viewer_gets_the_waiting_setup_card_and_its_answer_unblo
assert not waiting(live.event_stream, stored, "setup_beat")
finally:
await desktop.connection.close()
+
+
+def test_an_automatic_window_request_is_not_handed_to_a_reconnecting_viewer():
+ """A preview click still in flight at a reconnect would run twice if replayed; a card is replayed."""
+ import threading
+ from gateway.session_events import SessionEvents
+ from gateway.session_server_requests import ask_viewer, ask_viewer_result, open_requests, waiting, withdraw
+ events = SessionEvents()
+ events.fanout.attach(_Transport())
+ asks = [threading.Thread(target=ask_viewer, args=(events, "s1", "preview.act", {"action": "click"}),
+ kwargs={"timeout": 10, "replay": False}),
+ threading.Thread(target=ask_viewer_result, args=(events, "s1", "setup_beat", {"beat": "name"}),
+ kwargs={"timeout": 10})]
+ for ask in asks:
+ ask.start()
+ try:
+ wait_until(lambda: waiting(events, "s1", "preview.act") and waiting(events, "s1", "setup_beat"), timeout=5)
+ assert [entry["method"] for entry in open_requests(events, "s1")] == ["setup_beat"]
+ finally:
+ withdraw(events, "s1", "preview.act")
+ withdraw(events, "s1", "setup_beat")
+ for ask in asks:
+ ask.join(5)