The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): deliver /background results to the originating conversation
liuhao1024d73a542b777b
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/background-complete-event.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/background-complete-event.test.tsxnew file mode 100644index 00000000000..54db6963fbc--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/background-complete-event.test.tsx@@ -0,0 +1,67 @@+import { act, cleanup } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { RpcEvent } from '@/types/hermes'++import { type MessageStreamHarness, renderMessageStream } from './test-harness'++const SID = 'session-1'+const OTHER_SID = 'session-2'++let stream: MessageStreamHarness++function mountStream() {+ stream = renderMessageStream(SID)+}++function emit(type: RpcEvent['type'], payload: RpcEvent['payload'] = {}, sessionId = SID) {+ act(() => stream.handleEvent({ payload, session_id: sessionId, type }))+}++function lastMessage(id = SID) {+ return stream.state(id).messages.at(-1)+}++describe('background.complete event', () => {+ beforeEach(() => {+ mountStream()+ })++ afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ })++ // #97635: the finished background turn's response has to land in the+ // conversation that started it — the event carries the originating session+ // id, so the result is appended there instead of surfacing in an unlinked+ // bg_* session.+ it('appends the result to the originating session as a system message', () => {+ emit('background.complete', { task_id: 'bg_104613_385db3', text: 'the answer' })++ const message = lastMessage()++ expect(message?.role).toBe('system')+ expect(message?.id).toBe('background-complete-bg_104613_385db3')+ expect(stream.text()).toBe('[bg bg_104613_385db3]\nthe answer')+ })++ it('keeps another session untouched when the event targets this one', () => {+ emit('background.complete', { task_id: 'bg_1', text: 'for the other chat' }, OTHER_SID)++ expect(lastMessage()).toBeUndefined()+ expect(stream.text(OTHER_SID)).toBe('[bg bg_1]\nfor the other chat')+ })++ it('appends without a task-id header when the backend omits the id', () => {+ emit('background.complete', { text: 'the answer' })++ expect(stream.text()).toBe('the answer')+ })++ it('drops an empty completion instead of appending a blank line', () => {+ emit('background.complete', { task_id: 'bg_1', text: ' ' })++ expect(lastMessage()).toBeUndefined()+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.tsindex bdae58a0862..07a80ad7f2a 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.ts@@ -210,6 +210,36 @@ export function handleStatusEvent(ctx: GatewayEventContext): boolean {return true}+ if (event.type === 'background.complete') {+ // prompt.background RPC (the TUI's /background path) reports the finished+ // background turn here; the event carries the originating session id, so+ // the result lands in the conversation that started the task. Persistent+ // transcript line (not a toast), mirroring the TUI's `[bg <task_id>]`+ // system line — without it the completion was indistinguishable from a+ // lost task (#97635).+ const text = coerceGatewayText(payload?.text).trim()++ if (text && sessionId) {+ const taskId = String(payload?.task_id ?? '').trim()++ flushQueuedDeltas(sessionId)+ updateSessionState(sessionId, state => ({+ ...state,+ messages: [+ ...state.messages,+ {+ id: `background-complete-${taskId || Date.now()}`,+ role: 'system',+ parts: [textPart(taskId ? `[bg ${taskId}]\n${text}` : text, occurredAt)],+ timestamp: occurredAt+ }+ ]+ }))+ }++ return true+ }+if (event.type === 'notification.show') {// Driver-agnostic agent notice (credits usage/grant/depleted/restored// from `agent/credits_tracker.py`). The Ink TUI renders these in itsdiff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex 325d43df1f7..cbb1b97353f 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@ -1098,6 +1098,82 @@ describe('usePromptActions /btw', () => {})})+describe('usePromptActions /background', () => {+ afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ })++ // #97635: the slash-worker route prints the completion from a+ // fire-and-forget thread after process_command already returned — past the+ // worker's stdout capture window — so the result never reached the desktop+ // conversation that started the task. The dedicated prompt.background RPC+ // is the TUI's path; the response arrives later as a background.complete+ // gateway event.+ it('routes through prompt.background (not slash.exec) and renders the start notice', async () => {+ const seeds: Record<string, unknown>[] = []++ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'prompt.background') {+ return { task_id: 'bg_104613_385db3' } as never+ }++ return {} as never+ })++ let handle: HarnessHandle | null = null+ await actRender(+ <Harness+ onReady={h => (handle = h)}+ onSeedState={s => seeds.push(s)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ />+ )++ await handle!.submitText('/background summarize the top HN stories')++ expect(requestGateway).toHaveBeenCalledWith('prompt.background', {+ session_id: RUNTIME_SESSION_ID,+ text: 'summarize the top HN stories'+ })+ expect(requestGateway).not.toHaveBeenCalledWith('slash.exec', expect.anything())+ expect(requestGateway).not.toHaveBeenCalledWith('command.dispatch', expect.anything())+ expect(renderedSeedTexts(seeds).some(text => text.includes('bg_104613_385db3'))).toBe(true)+ })++ it('falls back to the slash worker when an older gateway lacks prompt.background', async () => {+ const seeds: Record<string, unknown>[] = []++ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'prompt.background') {+ throw new Error('method not found: prompt.background')+ }++ if (method === 'slash.exec') {+ return { output: 'Background task started by legacy gateway' } as never+ }++ throw new Error(`unexpected method: ${method}`)+ })++ let handle: HarnessHandle | null = null+ await actRender(+ <Harness+ onReady={h => (handle = h)}+ onSeedState={s => seeds.push(s)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ />+ )++ await handle!.submitText('/background anything')++ expect(requestGateway).toHaveBeenCalledWith('slash.exec', expect.objectContaining({ command: 'background anything' }))+ expect(renderedSeedTexts(seeds).some(text => text.includes('legacy gateway'))).toBe(true)+ })+})+describe('usePromptActions exec fallback error reporting', () => {beforeEach(() => {setSessions(() => [sessionInfo()])diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex 21fdbd778fa..e8ad47e3a74 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@ -597,6 +597,58 @@ export function useSlashCommand(deps: SlashCommandDeps) {renderSlashOutput(`error: ${err instanceof Error ? err.message : String(err)}`)}},+ // /background (alias /bg) starts a detached background turn via the+ // gateway's prompt.background RPC — the TUI's path+ // (ui-tui/src/app/slash/commands/session.ts). It must NOT go through+ // runExec: the slash worker's HermesCLI prints the completion from a+ // fire-and-forget thread after process_command already returned, past+ // the worker's stdout capture window, so the result never reached the+ // conversation that started the task (#97635, #57444). The RPC replies+ // immediately with the task id; the response itself arrives later as a+ // background.complete gateway event, which the gateway-event dispatcher+ // appends to this session.+ background: async ctx => {+ const text = ctx.arg.trim()++ const resolved = await withSlashOutput(ctx)++ if (!resolved) {+ return+ }++ const { render: renderSlashOutput, sessionId } = resolved++ if (!text) {+ renderSlashOutput(+ 'Usage: /background <prompt> — the task runs in a separate session and the result appears here when done.'+ )++ return+ }++ try {+ const result = await requestGateway<{ task_id?: string }>('prompt.background', {+ session_id: sessionId,+ text+ })++ renderSlashOutput(+ result.task_id+ ? `Background task ${result.task_id} started — you can continue chatting; the result will appear here when done.`+ : 'Background task started — you can continue chatting; the result will appear here when done.'+ )+ } catch (err) {+ // Older gateways without the dedicated RPC still have the+ // slash-worker route — same compatibility fallback as runRpc.+ if (isMissingRpcMethod(err)) {+ await runExec(ctx)++ return+ }++ renderSlashOutput(`error: ${err instanceof Error ? err.message : String(err)}`)+ }+ },// /compress (alias /compact) runs the gateway's dedicated// session.compress RPC — the TUI's path// (ui-tui/src/app/slash/commands/session.ts). It must NOT go throughdiff --git a/apps/desktop/src/lib/desktop-slash-commands.test.ts b/apps/desktop/src/lib/desktop-slash-commands.test.tsindex c49dedc1187..fed673d9e8c 100644--- a/apps/desktop/src/lib/desktop-slash-commands.test.ts+++ b/apps/desktop/src/lib/desktop-slash-commands.test.ts@@ -145,6 +145,38 @@ describe('desktop slash command curation', () => {}})+ it('still routes commands without dedicated RPCs through exec()', () => {+ // /background deliberately NOT here — it has the dedicated+ // prompt.background RPC since #97635 (the slash worker's completion+ // print lands after the capture window closes, so the result never+ // reached the originating conversation).+ const execNames = [+ '/debug',+ '/goal',+ '/personality',+ '/queue',+ '/retry',+ '/rollback',+ '/tools',+ '/undo',+ '/version'+ ]++ for (const name of execNames) {+ expect(resolveDesktopCommand(name)?.surface).toEqual({ kind: 'exec' })+ }+ })++ it('distinguishes free prose from finite slash option lists', () => {+ expect(desktopSlashCommandArgumentMode('/goal')).toBe('mixed')+ expect(desktopSlashCommandArgumentMode('/steer')).toBe('text')+ expect(desktopSlashCommandArgumentMode('/queue')).toBe('text')+ expect(desktopSlashCommandArgumentMode('/background')).toBe('text')+ expect(desktopSlashCommandArgumentMode('/personality')).toBe('options')+ expect(desktopSlashCommandArgumentMode('/handoff')).toBe('options')+ expect(desktopSlashCommandArgumentMode('/version')).toBeNull()+ })+it('allows aliases to execute without cluttering the popover', () => {expect(isDesktopSlashSuggestion('/reset')).toBe(false)expect(isDesktopSlashCommand('/reset')).toBe(true)diff --git a/apps/desktop/src/lib/desktop-slash-commands.ts b/apps/desktop/src/lib/desktop-slash-commands.tsindex f8308969a4e..d8aa0910507 100644--- a/apps/desktop/src/lib/desktop-slash-commands.ts+++ b/apps/desktop/src/lib/desktop-slash-commands.ts@@ -56,6 +56,7 @@ export interface DesktopThemeCommandOption {* keyed by the id.*/export type DesktopActionId =+ | 'background'| 'branch'| 'browser'| 'btw'@@ -266,6 +267,20 @@ const DESKTOP_COMMAND_SPECS: readonly DesktopCommandSpec[] = [surface: action('btw'),argumentMode: 'text'},+ // /background must be an action (prompt.background RPC — the TUI's path),+ // not exec: the slash worker's HermesCLI prints the completion from a+ // fire-and-forget thread after process_command already returned, past the+ // worker's stdout capture window, so the result never reached the desktop+ // conversation that started the task (#97635).+ {+ name: '/background',+ description: 'Run a prompt in a background session',+ aliases: ['/bg'],+ surface: action('background'),+ argumentMode: 'text'+ },+ argumentMode: 'text'+ },{name: '/pet',description: 'Toggle or adopt a petdex mascot (/pet, /pet list, /pet boba)',