File size: 68,367 Bytes
1f21206 4e7af9b 1f21206 4e7af9b 1f21206 4e7af9b 1f21206 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 | /**
* WebSocket connection handler
*
* 管理 WebSocket 连接生命周期,处理消息路由。
* 用户消息通过 CLI 子进程(stream-json 模式)处理,
* CLI stdout 消息被转换为 ServerMessage 并转发到 WebSocket。
*/
import type { ServerWebSocket } from 'bun'
import type { ClientMessage, ServerMessage } from './events.js'
import * as os from 'node:os'
import * as fs from 'node:fs'
import * as path from 'node:path'
import {
ConversationStartupError,
conversationService,
} from '../services/conversationService.js'
import { computerUseApprovalService } from '../services/computerUseApprovalService.js'
import { sessionService } from '../services/sessionService.js'
import { SettingsService } from '../services/settingsService.js'
import { ProviderService } from '../services/providerService.js'
import { isOpenAIOfficialProviderId } from '../services/openaiOfficialProvider.js'
import { diagnosticsService } from '../services/diagnosticsService.js'
import { deriveTitle, generateTitle, saveAiTitle } from '../services/titleService.js'
import { parseSlashCommand } from '../../utils/slashCommandParsing.js'
import {
COMMAND_NAME_TAG,
LOCAL_COMMAND_STDERR_TAG,
LOCAL_COMMAND_STDOUT_TAG,
} from '../../constants/xml.js'
import { shouldCreateWorktreeForSessionLaunch } from '../services/repositoryLaunchService.js'
const settingsService = new SettingsService()
const providerService = new ProviderService()
/**
* Cache slash commands from CLI init messages, keyed by sessionId.
*/
export type SessionSlashCommand = {
name: string
description: string
argumentHint?: string
}
const sessionSlashCommands = new Map<string, SessionSlashCommand[]>()
/**
* Timers for delayed session cleanup after client disconnect.
* If a client reconnects within 5 minutes, the timer is cancelled.
*/
const sessionCleanupTimers = new Map<string, ReturnType<typeof setTimeout>>()
/**
* Track sessions where user requested stop — suppress the CLI_ERROR that
* follows an interrupt so the frontend doesn't show "处理过程中发生错误".
*/
const sessionStopRequested = new Set<string>()
/**
* Track user message count and title state per session for auto-title generation.
*/
const sessionTitleState = new Map<string, {
userMessageCount: number
hasCustomTitle: boolean
firstUserMessage: string
allUserMessages: string[]
startedGenerationCounts: Set<number>
}>()
const runtimeOverrides = new Map<string, {
providerId: string | null
modelId: string
}>()
const runtimeTransitionPromises = new Map<string, Promise<void>>()
const sessionStartupPromises = new Map<string, Promise<void>>()
const lastResolvedStartupWorkDirs = new Map<string, string>()
const prewarmPendingSessions = new Set<string>()
const prewarmedSessions = new Set<string>()
const prewarmIdleTimers = new Map<string, ReturnType<typeof setTimeout>>()
const DEFAULT_PREWARM_IDLE_TIMEOUT_MS = 5 * 60_000
async function sendRepositoryStartupStatus(
ws: ServerWebSocket<WebSocketData>,
sessionId: string,
reason: 'user_message' | 'prewarm_session',
): Promise<void> {
if (reason !== 'user_message') return
const launchInfo = await sessionService.getSessionLaunchInfo(sessionId).catch(() => null)
const repository = launchInfo?.repository
if (!repository) return
if (shouldCreateWorktreeForSessionLaunch(launchInfo)) {
sendMessage(ws, { type: 'status', state: 'thinking', verb: 'Creating worktree' })
}
}
export function getSlashCommands(sessionId: string): SessionSlashCommand[] {
return sessionSlashCommands.get(sessionId) || []
}
export type WebSocketData = {
sessionId: string
connectedAt: number
channel: 'client' | 'sdk'
sdkToken: string | null
serverPort: number
serverHost: string
}
// Active WebSocket sessions
const activeSessions = new Map<string, ServerWebSocket<WebSocketData>>()
export const handleWebSocket = {
open(ws: ServerWebSocket<WebSocketData>) {
const { sessionId, channel, sdkToken } = ws.data
if (channel === 'sdk') {
if (!conversationService.authorizeSdkConnection(sessionId, sdkToken)) {
console.warn(`[WS] Rejected SDK connection for session: ${sessionId}`)
ws.close(1008, 'Invalid SDK token')
return
}
conversationService.attachSdkConnection(sessionId, ws)
console.log(`[WS] SDK connected for session: ${sessionId}`)
return
}
console.log(`[WS] Client connected for session: ${sessionId}`)
// Cancel pending cleanup timer if client reconnects
const pendingTimer = sessionCleanupTimers.get(sessionId)
if (pendingTimer) {
clearTimeout(pendingTimer)
sessionCleanupTimers.delete(sessionId)
}
activeSessions.set(sessionId, ws)
if (prewarmedSessions.has(sessionId)) {
bindPrewarmMetadataCapture(sessionId)
} else {
rebindSessionOutput(sessionId, ws)
}
const msg: ServerMessage = { type: 'connected', sessionId }
ws.send(JSON.stringify(msg))
},
message(ws: ServerWebSocket<WebSocketData>, rawMessage: string | Buffer) {
if (ws.data.channel === 'sdk') {
const payload = typeof rawMessage === 'string' ? rawMessage : rawMessage.toString()
conversationService.handleSdkPayload(ws.data.sessionId, payload)
return
}
try {
const message = JSON.parse(
typeof rawMessage === 'string' ? rawMessage : rawMessage.toString()
) as ClientMessage
switch (message.type) {
case 'user_message':
handleUserMessage(ws, message).catch((err) => {
void diagnosticsService.recordEvent({
type: 'ws_user_message_failed',
severity: 'error',
sessionId: ws.data.sessionId,
summary: err instanceof Error ? err.message : String(err),
details: err,
})
console.error(`[WS] Unhandled error in handleUserMessage:`, err)
})
break
case 'permission_response':
handlePermissionResponse(ws, message)
break
case 'computer_use_permission_response':
handleComputerUsePermissionResponse(ws, message)
break
case 'set_permission_mode':
handleSetPermissionMode(ws, message)
break
case 'set_runtime_config':
void handleSetRuntimeConfig(ws, message)
break
case 'prewarm_session':
void handlePrewarmSession(ws)
break
case 'stop_generation':
handleStopGeneration(ws)
break
case 'ping':
ws.send(JSON.stringify({ type: 'pong' } satisfies ServerMessage))
break
default:
sendError(ws, `Unknown message type: ${(message as any).type}`, 'UNKNOWN_TYPE')
}
} catch (error) {
sendError(ws, `Invalid message format: ${error}`, 'PARSE_ERROR')
}
},
close(ws: ServerWebSocket<WebSocketData>, code: number, reason: string) {
const { sessionId, channel } = ws.data
if (channel === 'sdk') {
console.log(`[WS] SDK disconnected from session: ${sessionId} (${code}: ${reason})`)
conversationService.detachSdkConnection(sessionId)
return
}
console.log(`[WS] Client disconnected from session: ${sessionId} (${code}: ${reason})`)
if (activeSessions.get(sessionId) !== ws) {
console.log(`[WS] Ignoring stale client disconnect for session: ${sessionId}`)
return
}
computerUseApprovalService.cancelSession(sessionId)
activeSessions.delete(sessionId)
conversationService.clearOutputCallbacks(sessionId)
// Schedule delayed cleanup: if the client doesn't reconnect within 30 seconds,
// stop the CLI subprocess to avoid leaking resources.
const cleanupTimer = setTimeout(() => {
sessionCleanupTimers.delete(sessionId)
if (!activeSessions.has(sessionId)) {
console.log(`[WS] Session ${sessionId} not reconnected after 30s, stopping CLI subprocess`)
conversationService.stopSession(sessionId)
cleanupSessionRuntimeState(sessionId)
}
}, 30_000)
sessionCleanupTimers.set(sessionId, cleanupTimer)
},
drain(ws: ServerWebSocket<WebSocketData>) {
// Backpressure handling - called when the socket is ready to receive more data
},
}
// ============================================================================
// Message handlers
// ============================================================================
async function handleUserMessage(
ws: ServerWebSocket<WebSocketData>,
message: Extract<ClientMessage, { type: 'user_message' }>
) {
const { sessionId } = ws.data
// Clear any stale stop flag from a previous turn
sessionStopRequested.delete(sessionId)
clearPrewarmState(sessionId)
const desktopSlashCommand = getDesktopSlashCommand(message.content)
if (desktopSlashCommand?.commandName === 'clear' && desktopSlashCommand.args.trim()) {
sendMessage(ws, {
type: 'error',
message: 'The /clear command does not accept arguments.',
code: 'INVALID_SLASH_COMMAND_ARGS',
})
sendMessage(ws, { type: 'status', state: 'idle' })
return
}
if (desktopSlashCommand?.commandName === 'clear') {
await handleDesktopClearCommand(ws)
return
}
// Send thinking status
sendMessage(ws, { type: 'status', state: 'thinking', verb: 'Thinking' })
const initialRuntimeTransition = await waitForRuntimeTransitionBeforeUserTurn(ws, sessionId)
if (!initialRuntimeTransition.ok) return
if (initialRuntimeTransition.waited) {
sendMessage(ws, { type: 'status', state: 'thinking', verb: 'Thinking' })
}
// Track and emit the first placeholder title before CLI startup/streaming.
let titleState = sessionTitleState.get(sessionId)
if (!titleState) {
titleState = {
userMessageCount: 0,
hasCustomTitle: !!(await sessionService.getCustomTitle(sessionId)),
firstUserMessage: '',
allUserMessages: [],
startedGenerationCounts: new Set<number>(),
}
sessionTitleState.set(sessionId, titleState)
}
const titleInput = getTitleInputForUserMessage(message.content, desktopSlashCommand)
if (titleInput) {
titleState.userMessageCount++
titleState.allUserMessages.push(titleInput)
if (titleState.userMessageCount === 1) {
titleState.firstUserMessage = titleInput
}
triggerTitleGeneration(ws, sessionId)
}
// 启动 CLI 子进程(如果还没有)
try {
await ensureCliSessionStarted(ws, sessionId, 'user_message')
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err)
const code =
err instanceof ConversationStartupError ? err.code : 'CLI_START_FAILED'
console.error(`[WS] CLI start failed for ${sessionId}: ${errMsg}`)
sendMessage(ws, {
type: 'error',
message: await buildSessionStartupDiagnosticMessage(sessionId, errMsg),
code,
retryable:
err instanceof ConversationStartupError ? err.retryable : false,
})
sendMessage(ws, { type: 'status', state: 'idle' })
return
}
const startupRuntimeTransition = await waitForRuntimeTransitionBeforeUserTurn(ws, sessionId)
if (startupRuntimeTransition.ok) {
if (startupRuntimeTransition.waited) {
sendMessage(ws, { type: 'status', state: 'thinking', verb: 'Thinking' })
}
} else {
return
}
// Register the callback before sending the turn so startup errors are not lost.
// Keep output muted until the current user turn is enqueued to avoid forwarding
// any pre-turn SDK chatter as fresh chat history.
let userMessageSent = false
const shouldForwardCurrentTurnLocalCommand =
createCurrentTurnLocalCommandForwarder(desktopSlashCommand)
rebindSessionOutput(sessionId, ws, {
shouldForward: (cliMsg) => {
if (userMessageSent || (cliMsg.type === 'result' && cliMsg.is_error)) {
return true
}
return shouldForwardCurrentTurnLocalCommand(cliMsg)
},
})
const sent = conversationService.sendMessage(
sessionId,
message.content,
message.attachments
)
if (!sent) {
sendMessage(ws, {
type: 'error',
message: 'CLI process is not running. The session may have ended or the process crashed.',
code: 'CLI_NOT_RUNNING',
})
sendMessage(ws, { type: 'status', state: 'idle' })
return
}
userMessageSent = true
}
async function handleDesktopClearCommand(
ws: ServerWebSocket<WebSocketData>,
) {
const { sessionId } = ws.data
const workDir = conversationService.getSessionWorkDir(sessionId)
conversationService.stopSession(sessionId)
conversationService.clearOutputCallbacks(sessionId)
sessionSlashCommands.delete(sessionId)
sessionTitleState.delete(sessionId)
cleanupStreamState(sessionId)
try {
await sessionService.clearSessionTranscript(sessionId, workDir || undefined)
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err)
sendMessage(ws, {
type: 'error',
message: errMsg,
code: 'SESSION_CLEAR_FAILED',
})
sendMessage(ws, { type: 'status', state: 'idle' })
return
}
sendMessage(ws, {
type: 'system_notification',
subtype: 'session_cleared',
message: 'Conversation cleared',
})
sendMessage(ws, {
type: 'message_complete',
usage: { input_tokens: 0, output_tokens: 0 },
})
}
async function handlePrewarmSession(ws: ServerWebSocket<WebSocketData>) {
const { sessionId } = ws.data
if (conversationService.hasSession(sessionId) || sessionStartupPromises.has(sessionId)) {
return
}
const launchInfo = await sessionService.getSessionLaunchInfo(sessionId).catch(() => null)
if (launchInfo?.repository) {
console.log(`[WS] Skipping prewarm for pending repository launch session ${sessionId}`)
return
}
prewarmPendingSessions.add(sessionId)
void ensureCliSessionStarted(ws, sessionId, 'prewarm_session')
.then(() => {
if (!prewarmPendingSessions.delete(sessionId)) return
bindPrewarmMetadataCapture(sessionId)
markPrewarmed(sessionId)
})
.catch((err) => {
prewarmPendingSessions.delete(sessionId)
console.warn(
`[WS] Prewarm failed for ${sessionId}: ${
err instanceof Error ? err.message : String(err)
}`,
)
})
}
function handlePermissionResponse(
ws: ServerWebSocket<WebSocketData>,
message: Extract<ClientMessage, { type: 'permission_response' }>
) {
const { sessionId } = ws.data
conversationService.respondToPermission(
sessionId,
message.requestId,
message.allowed,
message.rule,
message.updatedInput,
)
console.log(`[WS] Permission response for ${message.requestId}: ${message.allowed}`)
}
function handleComputerUsePermissionResponse(
ws: ServerWebSocket<WebSocketData>,
message: Extract<ClientMessage, { type: 'computer_use_permission_response' }>
) {
const { sessionId } = ws.data
const ok = computerUseApprovalService.resolveApproval(
message.requestId,
message.response,
)
if (!ok) {
console.warn(
`[WS] Ignored Computer Use permission response for unknown request ${message.requestId} from ${sessionId}`
)
}
}
function handleSetPermissionMode(
ws: ServerWebSocket<WebSocketData>,
message: Extract<ClientMessage, { type: 'set_permission_mode' }>
) {
const { sessionId } = ws.data
// Switching to/from bypassPermissions requires the CLI to be (re)started with
// --dangerously-skip-permissions. The CLI rejects a runtime set_permission_mode
// to bypassPermissions if it wasn't launched with that flag. Rather than just
// sending the SDK message (which would silently fail), restart the CLI subprocess
// with the correct arguments so the new permission mode takes effect.
const needsRestart =
conversationService.hasSession(sessionId) &&
(message.mode === 'bypassPermissions' || conversationService.getSessionPermissionMode(sessionId) === 'bypassPermissions')
if (needsRestart) {
void enqueueRuntimeTransition(sessionId, () =>
restartSessionWithPermissionMode(ws, sessionId, message.mode),
)
return
}
const ok = conversationService.setPermissionMode(sessionId, message.mode)
if (!ok) {
console.warn(`[WS] Ignored permission mode update for inactive session ${sessionId}`)
}
}
async function handleSetRuntimeConfig(
ws: ServerWebSocket<WebSocketData>,
message: Extract<ClientMessage, { type: 'set_runtime_config' }>
) {
const { sessionId } = ws.data
const modelId = typeof message.modelId === 'string' ? message.modelId.trim() : ''
if (!modelId) {
sendMessage(ws, {
type: 'error',
message: 'Runtime model selection is invalid.',
code: 'RUNTIME_CONFIG_INVALID',
})
return
}
const nextOverride = {
providerId: message.providerId ?? null,
modelId,
}
const prevOverride = runtimeOverrides.get(sessionId)
runtimeOverrides.set(sessionId, nextOverride)
if (
prevOverride &&
prevOverride.providerId === nextOverride.providerId &&
prevOverride.modelId === nextOverride.modelId
) {
return
}
if (!conversationService.hasSession(sessionId)) {
const pendingStartup = sessionStartupPromises.get(sessionId)
if (pendingStartup) {
await enqueueRuntimeTransition(sessionId, async () => {
await pendingStartup.catch(() => undefined)
const currentOverride = runtimeOverrides.get(sessionId)
if (
currentOverride?.providerId !== nextOverride.providerId ||
currentOverride.modelId !== nextOverride.modelId ||
!conversationService.hasSession(sessionId)
) {
return
}
await restartSessionWithRuntimeConfig(ws, sessionId)
})
}
return
}
await enqueueRuntimeTransition(sessionId, () =>
restartSessionWithRuntimeConfig(ws, sessionId),
)
}
async function restartSessionWithPermissionMode(
ws: ServerWebSocket<WebSocketData>,
sessionId: string,
mode: string,
): Promise<void> {
try {
// Persist the new mode first so it's read on restart
await settingsService.setPermissionMode(mode)
const workDir = conversationService.getSessionWorkDir(sessionId)
conversationService.stopSession(sessionId)
// Rebuild runtime settings (will pick up the persisted mode)
const runtimeSettings = await getRuntimeSettings(sessionId)
const sdkUrl =
`ws://${ws.data.serverHost}:${ws.data.serverPort}/sdk/${sessionId}` +
`?token=${encodeURIComponent(crypto.randomUUID())}`
await conversationService.startSession(sessionId, workDir, sdkUrl, runtimeSettings)
sendMessage(ws, { type: 'status', state: 'idle' })
console.log(`[WS] Restarted CLI for ${sessionId} with permission mode: ${mode}`)
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err)
void diagnosticsService.recordEvent({
type: 'permission_restart_failed',
severity: 'error',
sessionId,
summary: errMsg,
details: { mode, error: err },
})
console.error(`[WS] Failed to restart CLI for ${sessionId}: ${errMsg}`)
sendMessage(ws, {
type: 'error',
message: await buildSessionStartupDiagnosticMessage(
sessionId,
`Failed to restart session with new permission mode: ${errMsg}`,
),
code: 'CLI_RESTART_FAILED',
})
sendMessage(ws, { type: 'status', state: 'idle' })
}
}
async function restartSessionWithRuntimeConfig(
ws: ServerWebSocket<WebSocketData>,
sessionId: string,
): Promise<void> {
try {
const workDir = conversationService.getSessionWorkDir(sessionId)
conversationService.stopSession(sessionId)
const runtimeSettings = await getRuntimeSettings(sessionId)
const sdkUrl =
`ws://${ws.data.serverHost}:${ws.data.serverPort}/sdk/${sessionId}` +
`?token=${encodeURIComponent(crypto.randomUUID())}`
await conversationService.startSession(sessionId, workDir, sdkUrl, runtimeSettings)
sendMessage(ws, { type: 'status', state: 'idle' })
console.log(`[WS] Restarted CLI for ${sessionId} with runtime override`)
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err)
void diagnosticsService.recordEvent({
type: 'runtime_config_restart_failed',
severity: 'error',
sessionId,
summary: errMsg,
details: { runtimeOverride: runtimeOverrides.get(sessionId), error: err },
})
console.error(`[WS] Failed to restart CLI for ${sessionId} after runtime override: ${errMsg}`)
sendMessage(ws, {
type: 'error',
message: await buildSessionStartupDiagnosticMessage(
sessionId,
`Failed to switch provider/model: ${errMsg}`,
),
code: 'CLI_RESTART_FAILED',
})
sendMessage(ws, { type: 'status', state: 'idle' })
}
}
function handleStopGeneration(ws: ServerWebSocket<WebSocketData>) {
const { sessionId } = ws.data
console.log(`[WS] Stop generation requested for session: ${sessionId}`)
sessionStopRequested.add(sessionId)
if (conversationService.hasSession(sessionId)) {
// First try graceful interrupt via SDK control message
conversationService.sendInterrupt(sessionId)
// Force-kill if still running after 3 seconds
setTimeout(() => {
if (conversationService.hasSession(sessionId)) {
console.log(`[WS] Force-killing CLI subprocess for session: ${sessionId}`)
conversationService.stopSession(sessionId)
}
}, 3_000)
}
sendMessage(ws, { type: 'status', state: 'idle' })
}
// ============================================================================
// Title generation
// ============================================================================
function triggerTitleGeneration(ws: ServerWebSocket<WebSocketData>, sessionId: string): void {
const state = sessionTitleState.get(sessionId)
if (!state || state.hasCustomTitle) return
const count = state.userMessageCount
// Generate on count 1 (first response) and count 3 (with more context)
if (count !== 1 && count !== 3) return
if (state.startedGenerationCounts.has(count)) return
state.startedGenerationCounts.add(count)
const text = count === 1
? state.firstUserMessage
: state.allUserMessages.join('\n')
const runtimeProviderId = runtimeOverrides.get(sessionId)?.providerId
// Fire-and-forget: derive quick title, then upgrade with AI
void (async () => {
try {
// Stage 1: quick placeholder (only on first message)
if (count === 1) {
const placeholder = deriveTitle(text)
if (placeholder) {
const saved = await saveAiTitle(sessionId, placeholder)
if (!saved) {
state.hasCustomTitle = true
return
}
sendMessage(ws, { type: 'session_title_updated', sessionId, title: placeholder })
}
}
// Stage 2: AI-generated title
const aiTitle = await generateTitle(text, runtimeProviderId)
if (aiTitle) {
const saved = await saveAiTitle(sessionId, aiTitle)
if (!saved) {
state.hasCustomTitle = true
return
}
sendMessage(ws, { type: 'session_title_updated', sessionId, title: aiTitle })
}
} catch (err) {
console.error(`[Title] Failed to generate title for ${sessionId}:`, err)
}
})()
}
// ============================================================================
// CLI message translation
// ============================================================================
/**
* Per-session streaming state to avoid cross-session interference.
* Each session tracks its own dedup flag, active block types, and tool blocks.
*/
type SessionStreamState = {
hasReceivedStreamEvents: boolean
activeBlockTypes: Map<number, 'text' | 'tool_use' | 'thinking'>
activeToolBlocks: Map<number, { toolName: string; toolUseId: string; inputJson: string; parentToolUseId?: string }>
pendingLocalCommand?: { name: string; args: string }
/** Tool blocks whose input JSON failed to parse in content_block_stop.
* The assistant message carries the complete input — defer to that. */
pendingToolBlocks: Map<string, { toolName: string; toolUseId: string; parentToolUseId?: string }>
toolParentUseIds: Map<string, string>
lastApiError?: {
message: string
code: string
}
}
const sessionStreamStates = new Map<string, SessionStreamState>()
function getStreamState(sessionId: string): SessionStreamState {
let state = sessionStreamStates.get(sessionId)
if (!state) {
state = {
hasReceivedStreamEvents: false,
activeBlockTypes: new Map(),
activeToolBlocks: new Map(),
pendingLocalCommand: undefined,
pendingToolBlocks: new Map(),
toolParentUseIds: new Map(),
lastApiError: undefined,
}
sessionStreamStates.set(sessionId, state)
}
return state
}
function cliParentToolUseId(cliMsg: any): string | undefined {
return typeof cliMsg.parent_tool_use_id === 'string' && cliMsg.parent_tool_use_id.length > 0
? cliMsg.parent_tool_use_id
: undefined
}
function rememberToolParentUseId(
streamState: SessionStreamState,
toolUseId: string | undefined,
parentToolUseId: string | undefined,
): void {
if (!toolUseId || !parentToolUseId) return
streamState.toolParentUseIds.set(toolUseId, parentToolUseId)
}
function consumeToolParentUseId(
streamState: SessionStreamState,
toolUseId: string | undefined,
): string | undefined {
if (!toolUseId) return undefined
const parentToolUseId = streamState.toolParentUseIds.get(toolUseId)
streamState.toolParentUseIds.delete(toolUseId)
return parentToolUseId
}
/** Clean up stream state when session disconnects */
function cleanupStreamState(sessionId: string) {
sessionStreamStates.delete(sessionId)
}
function cleanupSessionRuntimeState(sessionId: string) {
cleanupStreamState(sessionId)
sessionSlashCommands.delete(sessionId)
sessionTitleState.delete(sessionId)
runtimeOverrides.delete(sessionId)
runtimeTransitionPromises.delete(sessionId)
sessionStartupPromises.delete(sessionId)
lastResolvedStartupWorkDirs.delete(sessionId)
clearPrewarmState(sessionId)
}
function getPrewarmIdleTimeoutMs(): number {
const raw = process.env.CC_HAHA_PREWARM_IDLE_TIMEOUT_MS
if (!raw) return DEFAULT_PREWARM_IDLE_TIMEOUT_MS
const parsed = Number.parseInt(raw, 10)
return Number.isFinite(parsed) && parsed >= 0
? parsed
: DEFAULT_PREWARM_IDLE_TIMEOUT_MS
}
function clearPrewarmState(sessionId: string) {
prewarmPendingSessions.delete(sessionId)
prewarmedSessions.delete(sessionId)
const timer = prewarmIdleTimers.get(sessionId)
if (timer) {
clearTimeout(timer)
prewarmIdleTimers.delete(sessionId)
}
}
function markPrewarmed(sessionId: string) {
prewarmedSessions.add(sessionId)
const timeoutMs = getPrewarmIdleTimeoutMs()
if (timeoutMs === 0) return
const existingTimer = prewarmIdleTimers.get(sessionId)
if (existingTimer) clearTimeout(existingTimer)
const timer = setTimeout(() => {
prewarmIdleTimers.delete(sessionId)
if (!prewarmedSessions.has(sessionId)) return
console.log(`[WS] Prewarmed session ${sessionId} idle for ${timeoutMs}ms, stopping CLI subprocess`)
conversationService.stopSession(sessionId)
prewarmedSessions.delete(sessionId)
}, timeoutMs)
prewarmIdleTimers.set(sessionId, timer)
}
function cacheSessionInitMetadata(sessionId: string, cliMsg: any) {
if (cliMsg?.type !== 'system' || cliMsg.subtype !== 'init') return
if (typeof cliMsg.cwd === 'string' && cliMsg.cwd.trim()) {
conversationService.updateSessionWorkDir(sessionId, cliMsg.cwd)
void (async () => {
await sessionService.appendSessionMetadata(sessionId, {
workDir: cliMsg.cwd,
})
await sessionService.deletePlaceholderSessionFiles(sessionId, cliMsg.cwd)
})()
}
if (cliMsg.slash_commands && Array.isArray(cliMsg.slash_commands)) {
updateSessionSlashCommands(sessionId, cliMsg.slash_commands, { notifyClient: false })
}
}
function extractAssistantText(cliMsg: any): string {
const content = cliMsg?.message?.content
if (!Array.isArray(content)) return ''
const textBlock = content.find(
(block: unknown): block is { type: string; text: string } =>
!!block &&
typeof block === 'object' &&
(block as { type?: unknown }).type === 'text' &&
typeof (block as { text?: unknown }).text === 'string',
)
return textBlock?.text || ''
}
function isDuplicateOfLastApiError(
lastApiError: SessionStreamState['lastApiError'],
resultMessage: string,
): boolean {
if (!lastApiError?.message) return false
if (resultMessage === lastApiError.message) return true
return (
resultMessage.includes(lastApiError.message) &&
/CLI (?:process exited unexpectedly|exited during startup)/i.test(resultMessage)
)
}
function bindPrewarmMetadataCapture(sessionId: string) {
for (const msg of conversationService.getRecentSdkMessages(sessionId)) {
cacheSessionInitMetadata(sessionId, msg)
}
if (!conversationService.hasSession(sessionId)) return
conversationService.clearOutputCallbacks(sessionId)
conversationService.onOutput(sessionId, (cliMsg) => {
cacheSessionInitMetadata(sessionId, cliMsg)
})
}
async function resolveSessionWorkDir(sessionId: string, fallback = os.homedir()): Promise<string> {
let workDir = fallback
try {
const resolved = await sessionService.getSessionWorkDir(sessionId)
if (resolved) workDir = resolved
console.log(
`[WS] resolveSessionWorkDir: sessionId=${sessionId}, resolved workDir=${JSON.stringify(
resolved,
)}, will spawn CLI with workDir=${workDir}`,
)
} catch (resolveErr) {
console.warn(
`[WS] resolveSessionWorkDir: failed to resolve workDir for ${sessionId}, using fallback=${workDir}: ${
resolveErr instanceof Error ? resolveErr.message : String(resolveErr)
}`,
)
}
return workDir
}
async function ensureCliSessionStarted(
ws: ServerWebSocket<WebSocketData>,
sessionId: string,
reason: 'user_message' | 'prewarm_session',
): Promise<void> {
const pendingStartup = sessionStartupPromises.get(sessionId)
if (pendingStartup) {
await pendingStartup
return
}
if (conversationService.hasSession(sessionId)) return
const startup = (async () => {
const workDir = await resolveSessionWorkDir(sessionId)
lastResolvedStartupWorkDirs.set(sessionId, workDir)
const runtimeSettings = await getRuntimeSettings(sessionId)
const sdkUrl =
`ws://${ws.data.serverHost}:${ws.data.serverPort}/sdk/${sessionId}` +
`?token=${encodeURIComponent(crypto.randomUUID())}`
await sendRepositoryStartupStatus(ws, sessionId, reason)
console.log(`[WS] Starting CLI for ${sessionId} due to ${reason}`)
await conversationService.startSession(sessionId, workDir, sdkUrl, runtimeSettings)
})()
sessionStartupPromises.set(sessionId, startup)
try {
await startup
} finally {
if (sessionStartupPromises.get(sessionId) === startup) {
sessionStartupPromises.delete(sessionId)
}
}
}
export function translateCliMessage(cliMsg: any, sessionId: string): ServerMessage[] {
const streamState = getStreamState(sessionId)
switch (cliMsg.type) {
case 'assistant': {
if (cliMsg.error || cliMsg.isApiErrorMessage) {
const message = extractAssistantText(cliMsg) || cliMsg.error || 'Unknown API error'
const code = typeof cliMsg.error === 'string' ? cliMsg.error : 'API_ERROR'
streamState.lastApiError = { message, code }
return [{
type: 'error',
message,
code,
}]
}
// If we already received stream_events, text/thinking were already sent.
// Only extract tool_use blocks (stream_event's content_block_stop lacks complete tool info).
if (cliMsg.message?.content && Array.isArray(cliMsg.message.content)) {
const messages: ServerMessage[] = []
for (const block of cliMsg.message.content) {
if (streamState.hasReceivedStreamEvents) {
// Stream events handled most blocks — but any tool_use whose
// input JSON failed to parse in content_block_stop was deferred.
// Emit those now with the complete input from the assistant message.
if (block.type === 'tool_use' && streamState.pendingToolBlocks.has(block.id)) {
const pending = streamState.pendingToolBlocks.get(block.id)!
streamState.pendingToolBlocks.delete(block.id)
rememberToolParentUseId(streamState, block.id, pending.parentToolUseId)
messages.push({
type: 'tool_use_complete',
toolName: pending.toolName || block.name,
toolUseId: block.id,
input: block.input,
parentToolUseId: pending.parentToolUseId,
})
}
} else {
// No stream events received — this is the only source, process everything
if (block.type === 'thinking' && block.thinking) {
messages.push({ type: 'thinking', text: block.thinking })
} else if (block.type === 'text' && block.text) {
messages.push({ type: 'content_start', blockType: 'text' })
messages.push({ type: 'content_delta', text: block.text })
} else if (block.type === 'tool_use') {
const parentToolUseId = cliParentToolUseId(cliMsg)
rememberToolParentUseId(streamState, block.id, parentToolUseId)
messages.push({
type: 'tool_use_complete',
toolName: block.name,
toolUseId: block.id,
input: block.input,
parentToolUseId,
})
}
}
}
// Reset flags for next turn
streamState.hasReceivedStreamEvents = false
streamState.pendingToolBlocks.clear()
return messages
}
return []
}
case 'user': {
// Bug #1: 处理 tool_result 消息
// CLI 发送 type:'user' 消息,其中 content 包含 tool_result 块
const messages: ServerMessage[] = []
if (isCompactSummaryMessageContent(cliMsg.message?.content)) {
messages.push({
type: 'system_notification',
subtype: 'compact_summary',
message: cliMsg.message.content,
data: {
isSynthetic: cliMsg.isSynthetic,
},
})
}
const localCommandOutput = extractLocalCommandOutput(
cliMsg.message?.content,
)
if (localCommandOutput) {
const pendingLocalCommand = streamState.pendingLocalCommand
streamState.pendingLocalCommand = undefined
if (!isCompactLocalCommandOutput(localCommandOutput)) {
const goalEvent = extractGoalEvent(
localCommandOutput,
pendingLocalCommand,
)
if (goalEvent) {
messages.push({
type: 'system_notification',
subtype: 'goal_event',
message: goalEvent.message,
data: goalEvent,
})
} else {
messages.push({ type: 'content_start', blockType: 'text' })
messages.push({ type: 'content_delta', text: localCommandOutput })
}
}
}
if (cliMsg.message?.content && Array.isArray(cliMsg.message.content)) {
for (const block of cliMsg.message.content) {
if (block.type === 'tool_result') {
const rememberedParentToolUseId = consumeToolParentUseId(streamState, block.tool_use_id)
const parentToolUseId =
cliParentToolUseId(cliMsg) ?? rememberedParentToolUseId
messages.push({
type: 'tool_result',
toolUseId: block.tool_use_id,
content: block.content,
isError: !!block.is_error,
parentToolUseId,
})
}
}
}
return messages
}
case 'stream_event': {
streamState.hasReceivedStreamEvents = true
const event = cliMsg.event
if (!event) return []
switch (event.type) {
case 'message_start': {
return [{ type: 'status', state: 'thinking' }]
}
case 'content_block_start': {
const contentBlock = event.content_block
if (!contentBlock) return []
const index = event.index ?? 0
if (contentBlock.type === 'tool_use') {
const parentToolUseId = cliParentToolUseId(cliMsg)
streamState.activeBlockTypes.set(index, 'tool_use')
// Track tool info so content_block_stop can emit complete data
streamState.activeToolBlocks.set(index, {
toolName: contentBlock.name || '',
toolUseId: contentBlock.id || '',
inputJson: '',
parentToolUseId,
})
return [{
type: 'content_start',
blockType: 'tool_use',
toolName: contentBlock.name,
toolUseId: contentBlock.id,
parentToolUseId,
}]
}
if (contentBlock.type === 'thinking' || contentBlock.type === 'redacted_thinking') {
streamState.activeBlockTypes.set(index, 'thinking')
return [{ type: 'status', state: 'thinking', verb: 'Thinking' }]
}
streamState.activeBlockTypes.set(index, 'text')
return [{ type: 'content_start', blockType: 'text' }]
}
case 'content_block_delta': {
const delta = event.delta
if (!delta) return []
if (delta.type === 'text_delta' && delta.text) {
return [{ type: 'content_delta', text: delta.text }]
}
if (delta.type === 'input_json_delta' && delta.partial_json) {
// Accumulate tool input JSON
const index = event.index ?? 0
const toolBlock = streamState.activeToolBlocks.get(index)
if (toolBlock) toolBlock.inputJson += delta.partial_json
return [{ type: 'content_delta', toolInput: delta.partial_json }]
}
if (delta.type === 'thinking_delta' && delta.thinking) {
return [{ type: 'thinking', text: delta.thinking }]
}
return []
}
case 'content_block_stop': {
const index = event.index ?? 0
const blockType = streamState.activeBlockTypes.get(index)
streamState.activeBlockTypes.delete(index)
if (blockType === 'tool_use') {
const toolBlock = streamState.activeToolBlocks.get(index)
streamState.activeToolBlocks.delete(index)
if (toolBlock) {
const parentToolUseId =
cliParentToolUseId(cliMsg) ?? toolBlock.parentToolUseId
let parsedInput = null
try { parsedInput = JSON.parse(toolBlock.inputJson) } catch {}
if (parsedInput !== null) {
rememberToolParentUseId(streamState, toolBlock.toolUseId, parentToolUseId)
return [{
type: 'tool_use_complete',
toolName: toolBlock.toolName,
toolUseId: toolBlock.toolUseId,
input: parsedInput,
parentToolUseId,
}]
}
// JSON parse failed — defer to the assistant message which
// carries the complete, already-parsed tool input.
console.warn(
`[WS] Tool input JSON parse failed for ${toolBlock.toolName} (${toolBlock.toolUseId}), deferring to assistant message`,
)
streamState.pendingToolBlocks.set(toolBlock.toolUseId, {
toolName: toolBlock.toolName,
toolUseId: toolBlock.toolUseId,
parentToolUseId,
})
}
}
return []
}
case 'message_stop': {
// message_stop is handled by the 'result' message
return []
}
case 'message_delta': {
// message_delta may contain stop_reason or usage updates
return []
}
default:
return []
}
}
case 'control_request': {
// 权限请求 — CLI 需要用户授权才能执行工具
if (cliMsg.request?.subtype === 'can_use_tool') {
return [{
type: 'permission_request',
requestId: cliMsg.request_id,
toolName: cliMsg.request.tool_name || 'Unknown',
toolUseId:
typeof cliMsg.request.tool_use_id === 'string'
? cliMsg.request.tool_use_id
: undefined,
input: cliMsg.request.input || {},
description: cliMsg.request.description,
}]
}
return []
}
case 'control_response':
return []
case 'result': {
// 对话结果(成功或错误)
const usage = {
input_tokens: cliMsg.usage?.input_tokens || 0,
output_tokens: cliMsg.usage?.output_tokens || 0,
}
if (cliMsg.is_error) {
// If the user requested stop, this "error" is just the interrupt
// result — don't show it as an error in the chat UI.
if (sessionStopRequested.has(sessionId)) {
sessionStopRequested.delete(sessionId)
return [{ type: 'message_complete', usage }]
}
const resultMessage =
(typeof cliMsg.result === 'string' && cliMsg.result) ||
(Array.isArray(cliMsg.errors) && cliMsg.errors.length > 0
? cliMsg.errors.join('\n')
: 'Unknown error')
if (isDuplicateOfLastApiError(streamState.lastApiError, resultMessage)) {
streamState.lastApiError = undefined
return [{ type: 'message_complete', usage }]
}
// 错误和完成消息都发送
return [
{
type: 'error',
message: resultMessage,
code: 'CLI_ERROR',
},
{ type: 'message_complete', usage },
]
}
// Clear stop flag on successful completion too
sessionStopRequested.delete(sessionId)
streamState.lastApiError = undefined
return [{ type: 'message_complete', usage }]
}
case 'system': {
// 区分不同的 system 子类型
const subtype = cliMsg.subtype
if (subtype === 'api_retry') {
const apiRetryMessage = toApiRetryServerMessage(cliMsg)
return apiRetryMessage ? [apiRetryMessage] : []
}
if (subtype === 'init') {
// CLI 初始化完成 — 缓存 slash commands 并发送模型信息
// NOTE: Do NOT send status:idle here — the CLI init fires while
// processing the first user message, and sending idle would reset
// the frontend's streaming state prematurely.
cacheSessionInitMetadata(sessionId, cliMsg)
const messages: ServerMessage[] = [
// Send model info as a system notification, not a status change
{ type: 'system_notification', subtype: 'init', message: `Model: ${cliMsg.model || 'unknown'}`, data: { model: cliMsg.model } },
]
// Send slash commands to frontend
const cmds = sessionSlashCommands.get(sessionId)
if (cmds && cmds.length > 0) {
messages.push({
type: 'system_notification',
subtype: 'slash_commands',
data: cmds,
})
}
return messages
}
if (subtype === 'memory_saved') {
return [{
type: 'system_notification',
subtype: 'memory_saved',
message: cliMsg.message,
data: {
writtenPaths: Array.isArray(cliMsg.writtenPaths) ? cliMsg.writtenPaths : [],
teamCount: typeof cliMsg.teamCount === 'number' ? cliMsg.teamCount : undefined,
verb: typeof cliMsg.verb === 'string' ? cliMsg.verb : undefined,
},
}]
}
if (subtype === 'status') {
if (cliMsg.status === 'compacting') {
return [{
type: 'status',
state: 'compacting',
verb: 'Compacting conversation',
}]
}
if (cliMsg.status == null) {
return [{ type: 'status', state: 'thinking', verb: 'Thinking' }]
}
return []
}
if (subtype === 'hook_started' || subtype === 'hook_response') {
// Hook 执行中 — 不转发给前端
return []
}
if (subtype === 'local_command' || subtype === 'local_command_output') {
const localCommand = extractLocalCommand(cliMsg.content ?? cliMsg.message)
if (localCommand) {
streamState.pendingLocalCommand = localCommand
return []
}
const localCommandOutput = extractLocalCommandOutput(
cliMsg.content ?? cliMsg.message,
{ allowUntagged: subtype === 'local_command_output' },
)
if (!localCommandOutput) return []
const goalEvent = extractGoalEvent(
localCommandOutput,
streamState.pendingLocalCommand,
)
streamState.pendingLocalCommand = undefined
if (goalEvent) {
return [{
type: 'system_notification',
subtype: 'goal_event',
message: goalEvent.message,
data: goalEvent,
}]
}
return [
{ type: 'content_start', blockType: 'text' },
{ type: 'content_delta', text: localCommandOutput },
]
}
// Bug #7: 处理 task/team system 消息
if (subtype === 'task_notification') {
return [{
type: 'system_notification',
subtype: 'task_notification',
message: cliMsg.message || cliMsg.title,
data: cliMsg,
}]
}
if (subtype === 'task_started') {
return [
{
type: 'system_notification',
subtype: 'task_started',
message: cliMsg.message || cliMsg.description || 'Task started',
data: cliMsg,
},
{
type: 'status',
state: 'tool_executing',
verb: cliMsg.message || cliMsg.description || 'Task started',
},
]
}
if (subtype === 'task_progress') {
return [
{
type: 'system_notification',
subtype: 'task_progress',
message: cliMsg.message || cliMsg.summary || cliMsg.description || 'Task in progress',
data: cliMsg,
},
{
type: 'status',
state: 'tool_executing',
verb: cliMsg.message || cliMsg.summary || cliMsg.description || 'Task in progress',
},
]
}
if (subtype === 'session_state_changed') {
return [{
type: 'system_notification',
subtype: 'session_state_changed',
message: cliMsg.message,
data: cliMsg,
}]
}
if (subtype === 'compact_boundary') {
return [{
type: 'system_notification',
subtype: 'compact_boundary',
message: getCompactBoundaryMessage(cliMsg),
data: cliMsg.compact_metadata ?? cliMsg,
}]
}
// 其他 system 消息
return []
}
default:
// 未知类型 — 调试输出但不转发
console.log(`[WS] Unknown CLI message type: ${cliMsg.type}`, JSON.stringify(cliMsg).substring(0, 200))
return []
}
}
// ============================================================================
// Helpers
// ============================================================================
function finiteNumber(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null
}
function normalizeRetryCount(value: unknown): number | null {
const numeric = finiteNumber(value)
if (numeric === null) return null
return Math.max(0, Math.trunc(numeric))
}
function readRetryErrorRecord(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
return value as Record<string, unknown>
}
function readRetryErrorString(value: unknown, keys: string[]): string | undefined {
const record = readRetryErrorRecord(value)
if (!record) return undefined
for (const key of keys) {
const candidate = record[key]
if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()
}
return undefined
}
function toApiRetryServerMessage(cliMsg: any): ServerMessage | null {
const attempt = normalizeRetryCount(cliMsg.attempt)
const maxRetries = normalizeRetryCount(cliMsg.max_retries)
const retryDelayMs = normalizeRetryCount(cliMsg.retry_delay_ms)
if (attempt === null || maxRetries === null || retryDelayMs === null) return null
const embeddedError = readRetryErrorRecord(cliMsg.error)
const embeddedStatus = embeddedError ? finiteNumber(embeddedError.status) : null
const rawStatus = cliMsg.error_status === null
? null
: finiteNumber(cliMsg.error_status) ?? embeddedStatus
const errorType = typeof cliMsg.error === 'string' && cliMsg.error.trim()
? cliMsg.error.trim()
: readRetryErrorString(cliMsg.error, ['type', 'code', 'name'])
const errorMessage = readRetryErrorString(cliMsg.error, ['message', 'error'])
return {
type: 'api_retry',
attempt,
maxRetries,
retryDelayMs,
errorStatus: rawStatus === null ? null : Math.trunc(rawStatus),
...(errorType ? { errorType } : {}),
...(errorMessage ? { errorMessage } : {}),
}
}
function sendMessage(ws: ServerWebSocket<WebSocketData>, message: ServerMessage) {
ws.send(JSON.stringify(message))
}
function sendError(ws: ServerWebSocket<WebSocketData>, message: string, code: string) {
sendMessage(ws, { type: 'error', message, code })
}
function getDesktopSlashCommand(content: string): ReturnType<typeof parseSlashCommand> {
const parsed = parseSlashCommand(content.trim())
if (!parsed || parsed.isMcp) return null
return parsed
}
function getTitleInputForUserMessage(
content: string,
command: ReturnType<typeof parseSlashCommand>,
): string | null {
if (command?.commandName !== 'goal') return content
const args = command.args.trim()
if (!args || args === 'clear') return null
return args
}
export function createCurrentTurnLocalCommandForwarder(
command: ReturnType<typeof parseSlashCommand>,
): (cliMsg: any) => boolean {
let awaitingCurrentTurnLocalCommandOutput = false
return (cliMsg: any) => {
if (command && isMatchingCurrentTurnLocalCommand(cliMsg, command)) {
awaitingCurrentTurnLocalCommandOutput = true
return true
}
if (command?.commandName === 'goal' && isLocalCommandOutputMessage(cliMsg)) {
const output = extractLocalCommandOutput(
cliMsg.content ?? cliMsg.message,
{ allowUntagged: cliMsg.subtype === 'local_command_output' },
)
if (output && looksLikeGoalCommandOutput(output)) {
awaitingCurrentTurnLocalCommandOutput = false
return true
}
}
if (
awaitingCurrentTurnLocalCommandOutput &&
isLocalCommandOutputMessage(cliMsg)
) {
awaitingCurrentTurnLocalCommandOutput = false
return true
}
return false
}
}
function isMatchingCurrentTurnLocalCommand(
cliMsg: any,
command: NonNullable<ReturnType<typeof parseSlashCommand>>,
): boolean {
if (cliMsg?.type !== 'system' || cliMsg?.subtype !== 'local_command') {
return false
}
const localCommand = extractLocalCommand(cliMsg.content ?? cliMsg.message)
if (!localCommand) return false
return (
localCommand.name === command.commandName &&
localCommand.args.trim() === command.args.trim()
)
}
function isLocalCommandOutputMessage(cliMsg: any): boolean {
if (
cliMsg?.type !== 'system' ||
(cliMsg?.subtype !== 'local_command' &&
cliMsg?.subtype !== 'local_command_output')
) {
return false
}
return extractLocalCommandOutput(
cliMsg.content ?? cliMsg.message,
{ allowUntagged: cliMsg.subtype === 'local_command_output' },
) !== null
}
function extractLocalCommandOutput(
content: unknown,
options: { allowUntagged?: boolean } = {},
): string | null {
const raw = typeof content === 'string'
? content
: Array.isArray(content)
? content
.flatMap((block) => {
if (!block || typeof block !== 'object') return []
const text = (block as { text?: unknown }).text
return typeof text === 'string' ? [text] : []
})
.join('\n')
: ''
if (!raw) return null
const stdout = extractTaggedContent(raw, LOCAL_COMMAND_STDOUT_TAG)
if (stdout !== null) return stdout
const stderr = extractTaggedContent(raw, LOCAL_COMMAND_STDERR_TAG)
if (stderr !== null) return stderr
if (options.allowUntagged) {
const normalized = raw.trim()
return normalized || null
}
return null
}
function isCompactLocalCommandOutput(output: string): boolean {
return output.trim() === 'Compacted'
}
function extractTaggedContent(raw: string, tag: string): string | null {
const match = raw.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`))
return match?.[1]?.trim() ?? null
}
function extractLocalCommand(content: unknown): { name: string; args: string } | null {
const raw = typeof content === 'string'
? content
: Array.isArray(content)
? content
.flatMap((block) => {
if (!block || typeof block !== 'object') return []
const text = (block as { text?: unknown }).text
return typeof text === 'string' ? [text] : []
})
.join('\n')
: ''
const name = extractTaggedContent(raw, COMMAND_NAME_TAG)
if (!name) return null
return {
name: name.replace(/^\//, ''),
args: extractTaggedContent(raw, 'command-args') ?? '',
}
}
type GoalEventData = {
action: 'created' | 'replaced' | 'status' | 'paused' | 'resumed' | 'completed' | 'cleared' | 'message'
status?: string
objective?: string
budget?: string
elapsed?: string
continuations?: string
message?: string
}
function extractGoalEvent(
output: string,
command?: { name: string; args: string },
): GoalEventData | null {
if (command && command.name !== 'goal') return null
const trimmed = output.trim()
if (!trimmed) return null
if (trimmed === 'Goal cleared.' || trimmed.startsWith('Goal cleared:')) {
return { action: 'cleared', message: trimmed }
}
if (trimmed === 'Goal marked complete.') {
return { action: 'completed', message: trimmed }
}
if (trimmed === 'No active goal.') {
return { action: 'message', message: trimmed }
}
if (trimmed.startsWith('Goal set:')) {
const objective = trimmed.slice('Goal set:'.length).trim()
return {
action: 'created',
status: 'active',
objective: objective || undefined,
message: trimmed,
}
}
return command?.name === 'goal' ? { action: 'message', message: trimmed } : null
}
function looksLikeGoalCommandOutput(output: string): boolean {
const trimmed = output.trim()
return (
trimmed.startsWith('Goal set:') ||
trimmed.startsWith('Goal cleared:') ||
trimmed === 'Goal cleared.' ||
trimmed === 'Goal marked complete.' ||
trimmed === 'No active goal.'
)
}
function getCompactBoundaryMessage(cliMsg: any): string {
const message = typeof cliMsg?.message === 'string' ? cliMsg.message.trim() : ''
if (message) return message
const content = typeof cliMsg?.content === 'string' ? cliMsg.content.trim() : ''
if (content) return content
return 'Context compacted'
}
function isCompactSummaryMessageContent(content: unknown): content is string {
return (
typeof content === 'string' &&
content.trim().startsWith(
'This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.',
)
)
}
function rebindSessionOutput(
sessionId: string,
ws: ServerWebSocket<WebSocketData>,
options?: {
shouldForward?: (cliMsg: any) => boolean
},
) {
if (!conversationService.hasSession(sessionId)) return
conversationService.clearOutputCallbacks(sessionId)
conversationService.onOutput(sessionId, (cliMsg) => {
if (options?.shouldForward && !options.shouldForward(cliMsg)) {
return
}
const serverMsgs = translateCliMessage(cliMsg, sessionId)
for (const msg of serverMsgs) {
sendMessage(ws, msg)
}
if (cliMsg.type === 'result') {
triggerTitleGeneration(ws, sessionId)
}
})
}
type RuntimeSettings = {
permissionMode?: string
model?: string
effort?: string
thinking?: 'disabled'
providerId?: string | null
}
function isKnownRuntimeProviderId(
providerId: string,
providers: Array<{ id: string }>,
): boolean {
return (
isOpenAIOfficialProviderId(providerId) ||
providers.some((provider) => provider.id === providerId)
)
}
async function getRuntimeSettings(sessionId?: string): Promise<RuntimeSettings> {
const runtimeOverride = sessionId ? runtimeOverrides.get(sessionId) : undefined
if (runtimeOverride) {
if (typeof runtimeOverride.providerId === 'string') {
const { providers } = await providerService.listProviders()
const providerExists = isKnownRuntimeProviderId(runtimeOverride.providerId, providers)
if (!providerExists) {
console.warn(
`[WS] Ignoring stale runtime provider id for ${sessionId}: ${runtimeOverride.providerId}`,
)
runtimeOverrides.delete(sessionId!)
return getDefaultRuntimeSettings()
}
}
const userSettings = await settingsService.getUserSettings()
const effort =
typeof userSettings.effort === 'string' && userSettings.effort.trim()
? userSettings.effort
: undefined
const thinking = resolveDesktopThinkingMode(userSettings)
return {
permissionMode: await settingsService.getPermissionMode().catch(() => undefined),
model: runtimeOverride.modelId,
effort,
thinking,
providerId: runtimeOverride.providerId,
}
}
return getDefaultRuntimeSettings()
}
async function getDefaultRuntimeSettings(): Promise<RuntimeSettings> {
// First check if CLI has an authProvider configured in ~/.claude.json
// (opencode, nvidia, openrouter, local, etc.) - these take precedence
// over cc-haha providers since they are managed by the CLI's /login command
const cliConfig = await readCliGlobalConfig()
if (cliConfig?.authProvider && cliConfig.authProvider !== 'anthropic' && cliConfig.authProvider !== 'openai') {
const userSettings = await settingsService.getUserSettings()
const baseModel =
typeof userSettings.model === 'string' && userSettings.model.trim()
? userSettings.model
: undefined
const modelContext =
typeof userSettings.modelContext === 'string' && userSettings.modelContext.trim()
? userSettings.modelContext
: undefined
const effort =
typeof userSettings.effort === 'string' && userSettings.effort.trim()
? userSettings.effort
: undefined
const thinking = resolveDesktopThinkingMode(userSettings)
return {
permissionMode: await settingsService.getPermissionMode().catch(() => undefined),
model: baseModel ? (modelContext ? `${baseModel}:${modelContext}` : baseModel) : undefined,
effort,
thinking,
providerId: undefined, // CLI manages auth via ~/.claude.json - pass undefined so shouldMarkManagedOAuth checks cli config
}
}
// Check if a custom cc-haha provider is active
const { providers, activeId } = await providerService.listProviders()
let resolvedActiveId = activeId
if (activeId && !isKnownRuntimeProviderId(activeId, providers)) {
console.warn(`[WS] Active provider id is stale, falling back to official provider: ${activeId}`)
resolvedActiveId = null
await providerService.activateOfficial()
}
const userSettings = await settingsService.getUserSettings()
const providerSettings = resolvedActiveId
? await providerService.getManagedSettings()
: undefined
const modelSettings = providerSettings ?? userSettings
const modelContext =
typeof modelSettings.modelContext === 'string' && modelSettings.modelContext.trim()
? modelSettings.modelContext
: undefined
const effort =
typeof userSettings.effort === 'string' && userSettings.effort.trim()
? userSettings.effort
: undefined
const thinking = resolveDesktopThinkingMode(userSettings)
let model: string | undefined
if (resolvedActiveId) {
// Provider is active — only consult provider-managed cc-haha settings.
// Global ~/.claude/settings.json model values must not bleed into provider mode.
const baseModel =
typeof modelSettings.model === 'string' && modelSettings.model.trim()
? modelSettings.model
: ''
if (baseModel) {
model = baseModel
if (modelContext) model += `:${modelContext}`
}
} else {
// No provider — pass model normally
const baseModel =
typeof userSettings.model === 'string' && userSettings.model.trim()
? userSettings.model
: undefined
model = baseModel ? (modelContext ? `${baseModel}:${modelContext}` : baseModel) : undefined
}
return {
permissionMode: await settingsService.getPermissionMode().catch(() => undefined),
model,
effort,
thinking,
providerId: resolvedActiveId,
}
}
function resolveDesktopThinkingMode(
settings: Record<string, unknown>,
): 'disabled' | undefined {
return settings.alwaysThinkingEnabled === false ? 'disabled' : undefined
}
/**
* Read CLI's ~/.claude.json directly to check authProvider.
* Bypasses getGlobalConfig cache since this runs in the server process
* and needs to reflect changes made by CLI's /login command.
*/
function readCliGlobalConfig(): {
authProvider?: 'anthropic' | 'openai' | 'openrouter' | 'local' | 'opencode' | 'nvidia'
openCodeApiKey?: string
openCodeModelName?: string
nvidiaApiKey?: string
openRouterApiKey?: string
localBaseUrl?: string
localModelName?: string
} | null {
const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude')
const configPath = path.join(configDir, '.claude.json')
try {
const raw = fs.readFileSync(configPath, 'utf-8')
return JSON.parse(raw)
} catch {
return null
}
}
async function buildSessionStartupDiagnosticMessage(
sessionId: string,
cause: string,
): Promise<string> {
const lines = [
cause,
'',
'Desktop service diagnostics:',
`- sessionId: ${sessionId}`,
]
try {
const recentWorkDir = lastResolvedStartupWorkDirs.get(sessionId)
const workDir =
recentWorkDir ||
conversationService.getSessionWorkDir(sessionId) ||
await sessionService.getSessionWorkDir(sessionId)
lines.push(`- workDir: ${workDir ?? '(unknown)'}`)
} catch (err) {
lines.push(`- workDir: failed to resolve (${err instanceof Error ? err.message : String(err)})`)
}
const runtimeOverride = runtimeOverrides.get(sessionId)
if (runtimeOverride) {
lines.push(`- runtimeOverride.providerId: ${runtimeOverride.providerId ?? '(official)'}`)
lines.push(`- runtimeOverride.modelId: ${runtimeOverride.modelId}`)
} else {
lines.push('- runtimeOverride: (none)')
}
try {
const { providers, activeId } = await providerService.listProviders()
lines.push(`- activeProviderId: ${activeId ?? '(official)'}`)
lines.push(`- configuredProviders: ${providers.length}`)
if (providers.length > 0) {
lines.push(
`- providerIndex: ${providers
.map((provider) => `${provider.name} (${provider.id})`)
.join(', ')}`,
)
}
} catch (err) {
lines.push(`- providers: failed to read (${err instanceof Error ? err.message : String(err)})`)
}
return lines.join('\n')
}
function enqueueRuntimeTransition(
sessionId: string,
transition: () => Promise<void>,
): Promise<void> {
const previous = runtimeTransitionPromises.get(sessionId) ?? Promise.resolve()
const next = previous
.catch(() => {})
.then(transition)
.finally(() => {
if (runtimeTransitionPromises.get(sessionId) === next) {
runtimeTransitionPromises.delete(sessionId)
}
})
runtimeTransitionPromises.set(sessionId, next)
return next
}
async function waitForRuntimeTransitionBeforeUserTurn(
ws: ServerWebSocket<WebSocketData>,
sessionId: string,
): Promise<{ ok: boolean; waited: boolean }> {
let waited = false
let pendingRuntimeTransition = runtimeTransitionPromises.get(sessionId)
while (pendingRuntimeTransition) {
waited = true
try {
await pendingRuntimeTransition
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err)
void diagnosticsService.recordEvent({
type: 'runtime_transition_failed',
severity: 'error',
sessionId,
summary: errMsg,
details: err,
})
console.error(`[WS] Runtime transition failed before handling user message for ${sessionId}: ${errMsg}`)
sendMessage(ws, {
type: 'error',
message: `Failed to switch provider/model: ${errMsg}`,
code: 'CLI_RESTART_FAILED',
})
sendMessage(ws, { type: 'status', state: 'idle' })
return { ok: false, waited }
}
const nextTransition = runtimeTransitionPromises.get(sessionId)
pendingRuntimeTransition =
nextTransition && nextTransition !== pendingRuntimeTransition
? nextTransition
: undefined
}
return { ok: true, waited }
}
/**
* Send a message to a specific session's WebSocket (for use by services)
*/
export function sendToSession(sessionId: string, message: ServerMessage): boolean {
const ws = activeSessions.get(sessionId)
if (!ws) return false
ws.send(JSON.stringify(message))
return true
}
export function updateSessionSlashCommands(
sessionId: string,
commands: unknown[],
options: { notifyClient?: boolean } = {},
): SessionSlashCommand[] {
const normalized = commands
.map(normalizeSessionSlashCommand)
.filter((command): command is SessionSlashCommand => command !== null)
sessionSlashCommands.set(sessionId, normalized)
if (options.notifyClient !== false) {
sendToSession(sessionId, {
type: 'system_notification',
subtype: 'slash_commands',
data: normalized,
})
}
return normalized
}
function normalizeSessionSlashCommand(command: unknown): SessionSlashCommand | null {
if (typeof command === 'string') {
return command.trim() ? { name: command, description: '' } : null
}
if (!command || typeof command !== 'object') return null
const record = command as {
name?: unknown
command?: unknown
description?: unknown
argumentHint?: unknown
}
const name =
typeof record.name === 'string'
? record.name
: typeof record.command === 'string'
? record.command
: ''
if (!name.trim()) return null
return {
name,
description: typeof record.description === 'string' ? record.description : '',
...(typeof record.argumentHint === 'string' ? { argumentHint: record.argumentHint } : {}),
}
}
export function closeSessionConnection(sessionId: string, reason = 'session closed'): boolean {
const cleanupTimer = sessionCleanupTimers.get(sessionId)
if (cleanupTimer) {
clearTimeout(cleanupTimer)
sessionCleanupTimers.delete(sessionId)
}
computerUseApprovalService.cancelSession(sessionId)
conversationService.clearOutputCallbacks(sessionId)
cleanupSessionRuntimeState(sessionId)
const ws = activeSessions.get(sessionId)
if (!ws) return false
activeSessions.delete(sessionId)
ws.close(1000, reason)
return true
}
export function getActiveSessionIds(): string[] {
return Array.from(activeSessions.keys())
}
export function __resetWebSocketHandlerStateForTests(): void {
for (const timer of sessionCleanupTimers.values()) clearTimeout(timer)
for (const timer of prewarmIdleTimers.values()) clearTimeout(timer)
activeSessions.clear()
sessionCleanupTimers.clear()
prewarmIdleTimers.clear()
}
|