@yu_robotics/remote-cli-router 1.6.217 → 1.6.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +10 -4
  2. package/dist/binding/BindingManager.d.ts +3 -1
  3. package/dist/binding/BindingManager.d.ts.map +1 -1
  4. package/dist/binding/BindingManager.js +9 -2
  5. package/dist/binding/BindingManager.js.map +1 -1
  6. package/dist/binding/ThreadSelectionManager.d.ts +9 -4
  7. package/dist/binding/ThreadSelectionManager.d.ts.map +1 -1
  8. package/dist/binding/ThreadSelectionManager.js +21 -7
  9. package/dist/binding/ThreadSelectionManager.js.map +1 -1
  10. package/dist/feishu/ApprovalCards.d.ts +2 -1
  11. package/dist/feishu/ApprovalCards.d.ts.map +1 -1
  12. package/dist/feishu/ApprovalCards.js +2 -1
  13. package/dist/feishu/ApprovalCards.js.map +1 -1
  14. package/dist/feishu/FeishuLongConnHandler.d.ts +9 -5
  15. package/dist/feishu/FeishuLongConnHandler.d.ts.map +1 -1
  16. package/dist/feishu/FeishuLongConnHandler.js +77 -54
  17. package/dist/feishu/FeishuLongConnHandler.js.map +1 -1
  18. package/dist/server.d.ts +9 -7
  19. package/dist/server.d.ts.map +1 -1
  20. package/dist/server.js +344 -218
  21. package/dist/server.js.map +1 -1
  22. package/dist/storage/CardThreadState.d.ts +23 -0
  23. package/dist/storage/CardThreadState.d.ts.map +1 -0
  24. package/dist/storage/CardThreadState.js +58 -0
  25. package/dist/storage/CardThreadState.js.map +1 -0
  26. package/dist/storage/JsonStore.d.ts +13 -0
  27. package/dist/storage/JsonStore.d.ts.map +1 -1
  28. package/dist/storage/JsonStore.js +104 -7
  29. package/dist/storage/JsonStore.js.map +1 -1
  30. package/dist/utils/DeliveryDiagnostics.d.ts +46 -0
  31. package/dist/utils/DeliveryDiagnostics.d.ts.map +1 -0
  32. package/dist/utils/DeliveryDiagnostics.js +322 -0
  33. package/dist/utils/DeliveryDiagnostics.js.map +1 -0
  34. package/package.json +1 -1
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.FeishuLongConnHandler = void 0;
37
+ const DeliveryDiagnostics_1 = require("../utils/DeliveryDiagnostics");
37
38
  const lark = __importStar(require("@larksuiteoapi/node-sdk"));
38
39
  const uuid_1 = require("uuid");
39
40
  const BindingManager_1 = require("../binding/BindingManager");
@@ -51,6 +52,8 @@ const CardTables_1 = require("../utils/CardTables");
51
52
  * Uses Feishu SDK's WSClient for WebSocket long connection
52
53
  */
53
54
  class FeishuLongConnHandler {
55
+ cardDiagnostics = new DeliveryDiagnostics_1.CardDeliveryDiagnostics();
56
+ bindDiagnosticTask(cardId, taskId) { this.cardDiagnostics.bind(cardId, taskId); }
54
57
  workerContexts;
55
58
  settingsCards;
56
59
  client;
@@ -99,6 +102,7 @@ class FeishuLongConnHandler {
99
102
  appSecret: config.appSecret,
100
103
  appType: lark.AppType.SelfBuild,
101
104
  domain: lark.Domain.Feishu,
105
+ logger: (0, DeliveryDiagnostics_1.safeSdkLogger)(),
102
106
  });
103
107
  }
104
108
  /**
@@ -458,7 +462,7 @@ class FeishuLongConnHandler {
458
462
  // Generate message ID first
459
463
  const commandMessageId = (0, uuid_1.v4)();
460
464
  // Register streaming session BEFORE sending command
461
- const feishuMessageId = await this.sendStreamingStart(openId, `🤔 Executing ${command}...`, threadName);
465
+ const feishuMessageId = await this.sendStreamingStart(openId, `🤔 Executing ${command}...`, threadName, undefined, commandMessageId);
462
466
  const currentBinding = await this.bindingManager.getUserBinding(openId);
463
467
  if (!currentBinding?.devices.some((device) => device.deviceId === activeDevice.deviceId)) {
464
468
  throw new Error('Device ownership changed before the command could be sent.');
@@ -468,7 +472,10 @@ class FeishuLongConnHandler {
468
472
  }
469
473
  console.log(`[FeishuHandler] Created card ${feishuMessageId} for slash command ${commandMessageId}`);
470
474
  if (this.onStartStreaming) {
471
- this.onStartStreaming(commandMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, false, undefined, threadName, selectionFence);
475
+ await this.onStartStreaming(commandMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, false, undefined, threadName, selectionFence);
476
+ }
477
+ if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
478
+ throw new Error('This command was superseded or the device changed before it could be sent.');
472
479
  }
473
480
  // Send slash command to device - the client will execute it locally
474
481
  const success = await this.connectionHub.sendToDevice(activeDevice.deviceId, {
@@ -662,7 +669,7 @@ class FeishuLongConnHandler {
662
669
  return;
663
670
  }
664
671
  // Notify RouterServer to clear stale thread state for the old device
665
- this.onDeviceSwitch?.(openId, oldDeviceId, deviceId);
672
+ await this.onDeviceSwitch?.(openId, oldDeviceId, deviceId);
666
673
  await this.replyToMessage(messageId, `✅ Switched to device: **${device.deviceName}**\n\nDevice ID: \`${device.deviceId}\``);
667
674
  }
668
675
  catch (error) {
@@ -824,7 +831,7 @@ Examples:
824
831
  console.log(`[FeishuHandler] Creating streaming card for command ${commandMessageId}${threadId ? ` (threadId=${threadId})` : ''}${pendingNewThread ? ' (pendingNewThread)' : ''}`);
825
832
  // Register streaming session BEFORE sending command to avoid race condition
826
833
  // where stream chunks arrive before registration
827
- const feishuMessageId = await this.sendStreamingStart(openId, attachments ? '🖼️ Processing image...' : '🤔 Processing...', threadName);
834
+ const feishuMessageId = await this.sendStreamingStart(openId, attachments ? '🖼️ Processing image...' : '🤔 Processing...', threadName, undefined, commandMessageId);
828
835
  const currentBinding = await this.bindingManager.getUserBinding(openId);
829
836
  if (!currentBinding?.devices.some((device) => device.deviceId === activeDevice.deviceId)) {
830
837
  throw new Error('Device ownership changed before the command could be sent.');
@@ -834,7 +841,10 @@ Examples:
834
841
  }
835
842
  console.log(`[FeishuHandler] Created card ${feishuMessageId} for command ${commandMessageId}`);
836
843
  if (this.onStartStreaming) {
837
- this.onStartStreaming(commandMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, pendingNewThread, undefined, threadName, selectionFence);
844
+ await this.onStartStreaming(commandMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, pendingNewThread, undefined, threadName, selectionFence);
845
+ }
846
+ if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
847
+ throw new Error('This command was superseded or the device changed before it could be sent.');
838
848
  }
839
849
  // Send command to device
840
850
  const success = await this.connectionHub.sendToDevice(activeDevice.deviceId, {
@@ -954,7 +964,7 @@ Examples:
954
964
  });
955
965
  }
956
966
  catch (error) {
957
- console.error('Failed to reply to message:', error?.message || error);
967
+ (0, DeliveryDiagnostics_1.deliveryEvent)('text_reply_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
958
968
  }
959
969
  }
960
970
  /**
@@ -973,7 +983,7 @@ Examples:
973
983
  return true;
974
984
  }
975
985
  catch (error) {
976
- console.error('Failed to send message:', error?.message || error);
986
+ (0, DeliveryDiagnostics_1.deliveryEvent)('text_message_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
977
987
  return false;
978
988
  }
979
989
  }
@@ -981,26 +991,27 @@ Examples:
981
991
  * Send streaming message with card update support
982
992
  * Returns message_id for updating
983
993
  */
984
- async sendStreamingStart(openId, initialText = '🤔 Thinking...', threadName, cwd) {
985
- console.log(`[FeishuHandler] Creating interactive card v2 for ${openId}`);
994
+ async sendStreamingStart(openId, initialText = '🤔 Thinking...', threadName, cwd, diagnosticTaskId) {
995
+ let attempted = false;
986
996
  try {
987
997
  const elements = this.createResponseHeaderElements(threadName || 'Resolving thread...', cwd);
988
998
  elements.push({ tag: 'markdown', content: initialText });
989
- const result = await this.client.im.message.create({
999
+ const content = JSON.stringify({ schema: '2.0', body: { elements } });
1000
+ attempted = true;
1001
+ const result = await this.cardDiagnostics.deliver({ operation: 'create', taskId: diagnosticTaskId }, content, () => this.client.im.message.create({
990
1002
  params: { receive_id_type: 'open_id' },
991
1003
  data: {
992
1004
  receive_id: openId,
993
1005
  msg_type: 'interactive',
994
- content: JSON.stringify({
995
- schema: '2.0',
996
- body: { elements },
997
- }),
1006
+ content,
998
1007
  },
999
- });
1008
+ }));
1000
1009
  return result?.data?.message_id || null;
1001
1010
  }
1002
1011
  catch (error) {
1003
- console.error('Failed to send streaming start:', error?.message || error);
1012
+ // Actual request failures are already aggregated at the send boundary.
1013
+ if (!attempted)
1014
+ (0, DeliveryDiagnostics_1.deliveryEvent)('card_preparation_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
1004
1015
  return null;
1005
1016
  }
1006
1017
  }
@@ -1255,7 +1266,7 @@ Examples:
1255
1266
  };
1256
1267
  const jsonSize = JSON.stringify(cardData).length;
1257
1268
  const sizeLimit = this.CARD_DATA_SIZE_LIMIT - this.CARD_SIZE_BUFFER;
1258
- console.log(`[FeishuHandler] Card data size: ${jsonSize} bytes, limit: ${sizeLimit} bytes`);
1269
+ console.log(`[FeishuHandler] Card preflight size: ${jsonSize} UTF-16 units, limit: ${sizeLimit} units`);
1259
1270
  // Use buffer for safety (2.9MB instead of 3MB)
1260
1271
  if (jsonSize > sizeLimit) {
1261
1272
  console.log(`[FeishuHandler] Data size (${jsonSize}) exceeds limit (${sizeLimit})`);
@@ -1271,9 +1282,11 @@ Examples:
1271
1282
  * @param elements Array of Feishu Card 2.0 elements
1272
1283
  * @returns The new message ID, or null on error
1273
1284
  */
1274
- async createContinuationCard(openId, elements, onTextFallback, allowFallback = true, header, rootId) {
1285
+ async createContinuationCard(openId, elements, onTextFallback, allowFallback = true, header, rootId, diagnosticIndex) {
1286
+ let attempted = false;
1275
1287
  try {
1276
1288
  const content = JSON.stringify({ schema: '2.0', ...(header ? { header } : {}), body: { elements: (0, CardTables_1.limitCardTables)(elements) } });
1289
+ attempted = true;
1277
1290
  const result = await this.sendCardRequest(content, async (body) => {
1278
1291
  const response = await this.client.im.message.create({
1279
1292
  params: { receive_id_type: 'open_id' },
@@ -1286,18 +1299,21 @@ Examples:
1286
1299
  if (!response.code && response.data?.message_id)
1287
1300
  this.workerContexts?.remember(response.data.message_id, rootId ?? response.data.message_id, body);
1288
1301
  return response;
1289
- }, onTextFallback, allowFallback);
1302
+ }, onTextFallback, allowFallback, { operation: 'create', rootId, index: diagnosticIndex });
1290
1303
  return result.data?.message_id || null;
1291
1304
  }
1292
1305
  catch (error) {
1293
- console.error('Failed to create continuation card:', error?.message || error);
1306
+ // Actual request failures are already aggregated at the send boundary.
1307
+ if (!attempted)
1308
+ (0, DeliveryDiagnostics_1.deliveryEvent)('card_preparation_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
1294
1309
  return null;
1295
1310
  }
1296
1311
  }
1297
1312
  /** Retry a confirmed table-limit or Markdown parse rejection once with readable text. */
1298
- async sendCardRequest(content, send, onTextFallback, allowFallback = true) {
1313
+ async sendCardRequest(content, send, onTextFallback, allowFallback = true, context = { operation: 'update' }) {
1299
1314
  const checkedSend = async (body) => {
1300
- const result = await send(this.workerContexts?.decorate(body) ?? body);
1315
+ const decorated = this.workerContexts?.decorate(body) ?? body;
1316
+ const result = await this.cardDiagnostics.deliver(context, decorated, () => send(decorated));
1301
1317
  if (result?.code)
1302
1318
  throw result;
1303
1319
  return result;
@@ -1413,9 +1429,7 @@ Examples:
1413
1429
  return this._updateStreamingMessage(messageId, [...headerElements, ...elements], openId, headerElements);
1414
1430
  });
1415
1431
  }
1416
- async _updateStreamingMessage(messageId, elements, openId, continuationHeaderElements = [], trailingElements = [], keepCompletionWithBody = false) {
1417
- let updatingMessageId = messageId;
1418
- let updatingCardIndex = 0;
1432
+ async _updateStreamingMessage(messageId, elements, openId, continuationHeaderElements = [], trailingElements = [], keepCompletionWithBody = false, diagnosticOperation = 'update') {
1419
1433
  try {
1420
1434
  // Get or initialize message chain
1421
1435
  let chain = this.messageChains.get(messageId);
@@ -1445,8 +1459,6 @@ Examples:
1445
1459
  const nextToolIds = chunks.map(chunk => new Set(chunk.filter(isTool).map(element => element.element_id)));
1446
1460
  const clearDeliveredPage = async (index, elements) => {
1447
1461
  const cardId = chain[index];
1448
- updatingMessageId = cardId;
1449
- updatingCardIndex = index;
1450
1462
  const fallback = fallbackCards.has(index);
1451
1463
  const content = JSON.stringify({ schema: '2.0', body: { elements: fallback ? (0, CardTables_1.plainTextCard)(elements) : elements } });
1452
1464
  await this.sendCardRequest(content, async (body) => {
@@ -1454,7 +1466,7 @@ Examples:
1454
1466
  if (!result?.code)
1455
1467
  this.workerContexts?.remember(cardId, messageId, body);
1456
1468
  return result;
1457
- }, () => fallbackCards.add(index), !fallback);
1469
+ }, () => fallbackCards.add(index), !fallback, { operation: 'tail-clear', cardId, rootId: messageId, index });
1458
1470
  hashes[index] = '';
1459
1471
  };
1460
1472
  // Remove previous owners before publishing moved tools, including still-active
@@ -1502,16 +1514,16 @@ Examples:
1502
1514
  nextHashes[index] = (0, crypto_1.createHash)('sha256').update(payloads[index]).digest('hex');
1503
1515
  };
1504
1516
  const patchCard = async (index) => {
1505
- if (hashes[index] === nextHashes[index])
1517
+ if (hashes[index] === nextHashes[index]) {
1518
+ this.cardDiagnostics.skip({ operation: diagnosticOperation, cardId: chain[index], rootId: messageId, index });
1506
1519
  return;
1507
- updatingMessageId = chain[index];
1508
- updatingCardIndex = index;
1520
+ }
1509
1521
  await this.sendCardRequest(payloads[index], async (content) => {
1510
1522
  const result = await this.client.im.message.patch({ path: { message_id: chain[index] }, data: { content } });
1511
1523
  if (!result?.code)
1512
1524
  this.workerContexts?.remember(chain[index], messageId, content);
1513
1525
  return result;
1514
- }, () => usePlainText(index), !fallbackCards.has(index));
1526
+ }, () => usePlainText(index), !fallbackCards.has(index), { operation: diagnosticOperation, cardId: chain[index], rootId: messageId, index });
1515
1527
  // Failed requests must remain eligible for retry.
1516
1528
  hashes[index] = nextHashes[index];
1517
1529
  rememberPage(index);
@@ -1533,7 +1545,7 @@ Examples:
1533
1545
  console.log(`[FeishuHandler] Creating ${neededContinuationCards - existingContinuationCards.length} new continuation card(s)`);
1534
1546
  for (let i = existingContinuationCards.length; i < neededContinuationCards; i++) {
1535
1547
  const chunkIndex = i + 1;
1536
- const newMessageId = await this.createContinuationCard(openId, fallbackCards.has(chunkIndex) ? (0, CardTables_1.plainTextCard)(chunks[chunkIndex]) : chunks[chunkIndex], () => usePlainText(chunkIndex), !fallbackCards.has(chunkIndex), undefined, messageId);
1548
+ const newMessageId = await this.createContinuationCard(openId, fallbackCards.has(chunkIndex) ? (0, CardTables_1.plainTextCard)(chunks[chunkIndex]) : chunks[chunkIndex], () => usePlainText(chunkIndex), !fallbackCards.has(chunkIndex), undefined, messageId, chunkIndex);
1537
1549
  if (newMessageId) {
1538
1550
  chain.push(newMessageId);
1539
1551
  hashes[chunkIndex] = nextHashes[chunkIndex];
@@ -1550,13 +1562,8 @@ Examples:
1550
1562
  return true;
1551
1563
  }
1552
1564
  catch (error) {
1553
- const detail = error?.response?.data ?? error;
1554
- console.error('Failed to update streaming message:', {
1555
- rootMessageId: messageId, messageId: updatingMessageId, cardNumber: updatingCardIndex + 1,
1556
- code: detail?.code,
1557
- subCode: typeof detail?.msg === 'string' ? /ErrCode:\s*(\d+)/.exec(detail.msg)?.[1] : undefined,
1558
- logId: detail?.log_id, message: error?.message || 'Card update failed',
1559
- });
1565
+ // Attempt errors are recorded and rate-limited at the exact send boundary.
1566
+ // Do not print the SDK error again here (it can contain the entire card).
1560
1567
  return false;
1561
1568
  }
1562
1569
  }
@@ -1622,7 +1629,7 @@ Examples:
1622
1629
  // Repack changed previews and clear obsolete tool copies without retracting messages.
1623
1630
  const trailingElements = !queueConfirmation ? [...footerElements, ...threadSwitchElements] : threadSwitchElements;
1624
1631
  const keepCompletionWithBody = !bare && !queueConfirmation;
1625
- const updated = await this._updateStreamingMessage(messageId, finalElements, openId, headerElements, trailingElements, keepCompletionWithBody);
1632
+ const updated = await this._updateStreamingMessage(messageId, finalElements, openId, headerElements, trailingElements, keepCompletionWithBody, 'finalize');
1626
1633
  if (!updated) {
1627
1634
  return false;
1628
1635
  }
@@ -1631,7 +1638,7 @@ Examples:
1631
1638
  if (options?.onDelivered) {
1632
1639
  const delivered = this.messageChains.get(messageId);
1633
1640
  if (delivered && delivered.length > 0)
1634
- options.onDelivered([...delivered]);
1641
+ await options.onDelivered([...delivered]);
1635
1642
  }
1636
1643
  // Store thread switch card state for later refresh (before cleanup)
1637
1644
  if (!bare && threads && threads.length >= 1) {
@@ -1658,7 +1665,7 @@ Examples:
1658
1665
  return true;
1659
1666
  }
1660
1667
  catch (error) {
1661
- console.error('Failed to finalize streaming message:', error?.message || error);
1668
+ (0, DeliveryDiagnostics_1.deliveryEvent)('card_finalize_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
1662
1669
  return false;
1663
1670
  }
1664
1671
  }
@@ -1822,7 +1829,7 @@ Examples:
1822
1829
  if (!result?.code)
1823
1830
  this.workerContexts?.remember(cardMessageId, rootId, content);
1824
1831
  return result;
1825
- });
1832
+ }, undefined, true, { operation: 'controls', cardId: cardMessageId, rootId });
1826
1833
  this.threadSwitchCardState.set(cardMessageId, { ...state, activeThreadId: newActiveThreadId });
1827
1834
  });
1828
1835
  }
@@ -1836,7 +1843,7 @@ Examples:
1836
1843
  if (!result?.code)
1837
1844
  this.workerContexts?.remember(cardId, rootId, body);
1838
1845
  return result;
1839
- });
1846
+ }, undefined, true, { operation: 'controls', cardId, rootId });
1840
1847
  // A concurrent reset can change controls without changing the streaming source elements.
1841
1848
  this.cardContentHashes.delete(rootId);
1842
1849
  });
@@ -1926,12 +1933,15 @@ Examples:
1926
1933
  if (typeof openMessageId !== 'string')
1927
1934
  return { toast: { type: 'error', content: 'This thread card has expired. Run /thread list for a fresh card.' } };
1928
1935
  try {
1929
- await this.onCardSwitchThread?.(openId, openMessageId, parsed.threadId, parsed.threadName ?? parsed.threadId);
1930
- this.refreshThreadSwitchButtons(openMessageId, parsed.threadId).catch((err) => console.error('[FeishuLongConnHandler] Failed to refresh thread switch buttons:', err));
1931
- return { toast: { type: 'success', content: `Switched to: ${parsed.threadName ?? parsed.threadId}` } };
1936
+ const selectedName = await this.onCardSwitchThread?.(openId, openMessageId, parsed.threadId, parsed.threadName ?? parsed.threadId);
1937
+ if (selectedName && typeof selectedName === 'object') {
1938
+ return { toast: { type: 'info', content: selectedName.notice } };
1939
+ }
1940
+ this.refreshThreadSwitchButtons(openMessageId, parsed.threadId).catch((err) => (0, DeliveryDiagnostics_1.deliveryEvent)('card_controls_failed', (0, DeliveryDiagnostics_1.safeCardError)(err)));
1941
+ return { toast: { type: 'success', content: `Switched to: ${selectedName ?? parsed.threadName ?? parsed.threadId}` } };
1932
1942
  }
1933
1943
  catch (error) {
1934
- console.error('[FeishuLongConnHandler] Card action switch_thread failed:', error);
1944
+ (0, DeliveryDiagnostics_1.deliveryEvent)('card_switch_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
1935
1945
  return { toast: { type: 'error', content: error instanceof Error ? error.message : 'Thread selection failed.' } };
1936
1946
  }
1937
1947
  }
@@ -1944,7 +1954,7 @@ Examples:
1944
1954
  return { toast: { type: 'info', content: 'Creating new thread...' } };
1945
1955
  }
1946
1956
  catch (error) {
1947
- console.error('[FeishuLongConnHandler] Card action new_thread failed:', error);
1957
+ (0, DeliveryDiagnostics_1.deliveryEvent)('card_new_thread_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
1948
1958
  return { toast: { type: 'error', content: error instanceof Error ? error.message : 'Could not create a thread.' } };
1949
1959
  }
1950
1960
  }
@@ -1957,7 +1967,7 @@ Examples:
1957
1967
  return { toast: { type: 'success', content: parsed.action === 'queue_confirm' ? 'Queue confirmation sent' : 'Queue request cancelled' } };
1958
1968
  }
1959
1969
  catch (error) {
1960
- console.error('[FeishuLongConnHandler] Queue action failed:', error);
1970
+ (0, DeliveryDiagnostics_1.deliveryEvent)('card_queue_action_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
1961
1971
  return { toast: { type: 'error', content: 'Queue action failed' } };
1962
1972
  }
1963
1973
  }
@@ -1986,13 +1996,25 @@ Examples:
1986
1996
  this.queueActionStates.delete(queueId);
1987
1997
  throw new Error('No active online device found');
1988
1998
  }
1999
+ const selectionFence = this.onCaptureSelection?.(openId, activeDevice.deviceId);
1989
2000
  let executionMessageId;
1990
2001
  if (action === 'confirm') {
1991
2002
  executionMessageId = (0, uuid_1.v4)();
1992
2003
  const feishuMessageId = this.connectionHub.supportsQueueStarted(activeDevice.deviceId)
1993
2004
  ? null
1994
- : await this.sendStreamingStart(openId, '🤔 Queued message confirmed. Waiting for the current task to finish...');
1995
- this.onStartStreaming?.(executionMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, false, cardMessageId);
2005
+ : await this.sendStreamingStart(openId, '🤔 Queued message confirmed. Waiting for the current task to finish...', undefined, undefined, executionMessageId);
2006
+ try {
2007
+ await this.onStartStreaming?.(executionMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, false, cardMessageId, undefined, selectionFence);
2008
+ }
2009
+ catch (error) {
2010
+ // No command was sent. A failed durable route must not consume the confirmation.
2011
+ this.queueActionStates.delete(queueId);
2012
+ throw error;
2013
+ }
2014
+ }
2015
+ if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
2016
+ this.queueActionStates.delete(queueId);
2017
+ throw new Error('This queue action was superseded or the device changed before it could be sent.');
1996
2018
  }
1997
2019
  const controlMessageId = (0, uuid_1.v4)();
1998
2020
  const suffix = executionMessageId ? ` ${executionMessageId}` : '';
@@ -2066,7 +2088,7 @@ Examples:
2066
2088
  });
2067
2089
  }
2068
2090
  catch (error) {
2069
- console.error('[FeishuLongConnHandler] Failed to update queue confirmation card:', error?.message || error);
2091
+ (0, DeliveryDiagnostics_1.deliveryEvent)('card_queue_update_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
2070
2092
  }
2071
2093
  }
2072
2094
  /**
@@ -2117,6 +2139,7 @@ Examples:
2117
2139
  * Stop the Feishu connection
2118
2140
  */
2119
2141
  async stop() {
2142
+ this.cardDiagnostics.close();
2120
2143
  try {
2121
2144
  console.log('Stopping Feishu WebSocket connection...');
2122
2145
  // Close WebSocket connection — must call close() to stop internal ping