()
| 1963 | // ask() call so messages that queued up during a long turn coalesce |
| 1964 | // into a single follow-up turn instead of N separate turns. |
| 1965 | const drainCommandQueue = async () => { |
| 1966 | while ((command = dequeue(isMainThread))) { |
| 1967 | if ( |
| 1968 | command.mode !== 'prompt' && |
| 1969 | command.mode !== 'orphaned-permission' && |
| 1970 | command.mode !== 'task-notification' |
| 1971 | ) { |
| 1972 | throw new Error( |
| 1973 | 'only prompt commands are supported in streaming mode', |
| 1974 | ) |
| 1975 | } |
| 1976 | |
| 1977 | // Non-prompt commands (task-notification, orphaned-permission) carry |
| 1978 | // side effects or orphanedPermission state, so they process singly. |
| 1979 | // Prompt commands greedily collect followers with matching workload. |
| 1980 | const batch: QueuedCommand[] = [command] |
| 1981 | if (command.mode === 'prompt') { |
| 1982 | while (canBatchWith(command, peek(isMainThread))) { |
| 1983 | batch.push(dequeue(isMainThread)!) |
| 1984 | } |
| 1985 | if (batch.length > 1) { |
| 1986 | command = { |
| 1987 | ...command, |
| 1988 | value: joinPromptValues(batch.map(c => c.value)), |
| 1989 | uuid: batch.findLast(c => c.uuid)?.uuid ?? command.uuid, |
| 1990 | } |
| 1991 | } |
| 1992 | } |
| 1993 | const batchUuids = batch.map(c => c.uuid).filter(u => u !== undefined) |
| 1994 | |
| 1995 | // QueryEngine will emit a replay for command.uuid (the last uuid in |
| 1996 | // the batch) via its messagesToAck path. Emit replays here for the |
| 1997 | // rest so consumers that track per-uuid delivery (clank's |
| 1998 | // asyncMessages footer, CCR) see an ack for every message they sent, |
| 1999 | // not just the one that survived the merge. |
| 2000 | if (options.replayUserMessages && batch.length > 1) { |
| 2001 | for (const c of batch) { |
| 2002 | if (c.uuid && c.uuid !== command.uuid) { |
| 2003 | output.enqueue({ |
| 2004 | type: 'user', |
| 2005 | message: { role: 'user', content: c.value }, |
| 2006 | session_id: getSessionId(), |
| 2007 | parent_tool_use_id: null, |
| 2008 | uuid: c.uuid, |
| 2009 | isReplay: true, |
| 2010 | } satisfies SDKUserMessageReplay) |
| 2011 | } |
| 2012 | } |
| 2013 | } |
| 2014 | |
| 2015 | // Combine all MCP clients. appState.mcp is populated incrementally |
| 2016 | // per-server by main.tsx (mirrors useManageMCPConnections). Reading |
| 2017 | // fresh per-command means late-connecting servers are visible on the |
| 2018 | // next turn. registerElicitationHandlers is idempotent (tracking set). |
| 2019 | const appState = getAppState() |
| 2020 | const allMcpClients = [ |
| 2021 | ...appState.mcp.clients, |
| 2022 | ...sdkClients, |
no test coverage detected