@yu_robotics/remote-cli-router 1.6.271 → 1.6.273

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 (40) hide show
  1. package/README.md +1 -1
  2. package/dist/feishu/CommandMenu.d.ts.map +1 -1
  3. package/dist/feishu/CommandMenu.js +3 -4
  4. package/dist/feishu/CommandMenu.js.map +1 -1
  5. package/dist/feishu/FeishuLongConnHandler.d.ts +11 -6
  6. package/dist/feishu/FeishuLongConnHandler.d.ts.map +1 -1
  7. package/dist/feishu/FeishuLongConnHandler.js +149 -107
  8. package/dist/feishu/FeishuLongConnHandler.js.map +1 -1
  9. package/dist/feishu/MachineCommandForm.d.ts +5 -12
  10. package/dist/feishu/MachineCommandForm.d.ts.map +1 -1
  11. package/dist/feishu/MachineCommandForm.js +2 -4
  12. package/dist/feishu/MachineCommandForm.js.map +1 -1
  13. package/dist/feishu/ScheduleCards.d.ts.map +1 -1
  14. package/dist/feishu/ScheduleCards.js +7 -4
  15. package/dist/feishu/ScheduleCards.js.map +1 -1
  16. package/dist/files/AutomaticFileEnrollment.d.ts +1 -0
  17. package/dist/files/AutomaticFileEnrollment.d.ts.map +1 -1
  18. package/dist/files/AutomaticFileEnrollment.js +20 -6
  19. package/dist/files/AutomaticFileEnrollment.js.map +1 -1
  20. package/dist/files/FileTransfers.d.ts.map +1 -1
  21. package/dist/files/FileTransfers.js +29 -10
  22. package/dist/files/FileTransfers.js.map +1 -1
  23. package/dist/server.d.ts.map +1 -1
  24. package/dist/server.js +69 -24
  25. package/dist/server.js.map +1 -1
  26. package/dist/storage/CardThreadState.d.ts +1 -0
  27. package/dist/storage/CardThreadState.d.ts.map +1 -1
  28. package/dist/storage/CardThreadState.js +6 -3
  29. package/dist/storage/CardThreadState.js.map +1 -1
  30. package/dist/tips/TipCatalog.js +2 -2
  31. package/dist/tips/assets/abort-consequences.png +0 -0
  32. package/dist/tips/assets/clear-thread-context.png +0 -0
  33. package/dist/tips/assets/command-menu-navigation.png +0 -0
  34. package/dist/tips/assets/reply-in-original-thread.png +0 -0
  35. package/dist/tips/assets/schedule-in-original-thread.png +0 -0
  36. package/dist/tips/catalog.zh-CN.json +93 -24
  37. package/dist/tips/ui.zh-CN.json +22 -2
  38. package/dist/websocket/ConnectionHub.js +2 -1
  39. package/dist/websocket/ConnectionHub.js.map +1 -1
  40. package/package.json +1 -1
@@ -75,6 +75,7 @@ class FeishuLongConnHandler {
75
75
  client;
76
76
  wsClient = null;
77
77
  bindingManager;
78
+ store;
78
79
  connectionHub = null;
79
80
  appId;
80
81
  appSecret;
@@ -112,6 +113,7 @@ class FeishuLongConnHandler {
112
113
  constructor(config) {
113
114
  this.appId = config.appId;
114
115
  this.appSecret = config.appSecret;
116
+ this.store = config.store;
115
117
  this.bindingManager = new BindingManager_1.BindingManager(config.store);
116
118
  // Initialize Feishu SDK client for API calls
117
119
  this.client = new lark.Client({
@@ -198,6 +200,7 @@ class FeishuLongConnHandler {
198
200
  */
199
201
  onResolveActiveThread;
200
202
  onRecoverThreads;
203
+ onCommandNotSent;
201
204
  /**
202
205
  * Set active thread resolution callback
203
206
  */
@@ -276,7 +279,13 @@ class FeishuLongConnHandler {
276
279
  return;
277
280
  }
278
281
  // Abort must remain responsive while file admission/download is pending.
279
- if (this.parseMessageContent(message).trim() !== '/abort')
282
+ const commandText = this.parseMessageContent(message).trim();
283
+ // Reject old client commands before preview logging or backend passthrough.
284
+ if (/^\/proxy(?:\s|$)/i.test(commandText)) {
285
+ await this.replyToMessage(messageId, 'Machine proxy settings were removed. Use /machine add with a direct SSH destination.');
286
+ return;
287
+ }
288
+ if (commandText !== '/abort')
280
289
  await this.fileAdmissions.get(openId)?.catch(() => { });
281
290
  // The file may have been admitted while this reply was waiting above.
282
291
  if (parentId)
@@ -446,31 +455,32 @@ class FeishuLongConnHandler {
446
455
  * Handle slash command passthrough to client
447
456
  * Passes unknown slash commands to the local Claude Code instance
448
457
  */
449
- async handleSlashCommandPassthrough(openId, messageId, content, command, threadId, threadName, sourceDeviceId, useActiveThread = false, originalFence) {
458
+ async handleSlashCommandPassthrough(openId, messageId, content, command, threadId, threadName, sourceDeviceId, useActiveThread = false, originalFence, fromMenu = false) {
459
+ const fail = async (message) => {
460
+ if (fromMenu)
461
+ return message;
462
+ await this.replyToMessage(messageId, message);
463
+ };
450
464
  try {
451
465
  // Find user binding
452
466
  const binding = await this.bindingManager.getUserBinding(openId);
453
467
  if (!binding) {
454
- await this.replyToMessage(messageId, '❌ You have not bound a device yet, please send /bind <binding-code> to bind first');
455
- return;
468
+ return fail('❌ You have not bound a device yet, please send /bind <binding-code> to bind first');
456
469
  }
457
470
  // Resolve the destination and selection together.
458
471
  const activeDevice = sourceDeviceId
459
472
  ? binding.devices.find((device) => device.deviceId === sourceDeviceId)
460
473
  : await this.bindingManager.getActiveDevice(openId);
461
474
  if (!activeDevice) {
462
- await this.replyToMessage(messageId, '❌ No active device found. Please use /device list to view your devices');
463
- return;
475
+ return fail('❌ No active device found. Please use /device list to view your devices');
464
476
  }
465
477
  // Check if ConnectionHub is available
466
478
  if (!this.connectionHub) {
467
- await this.replyToMessage(messageId, '❌ Server error: ConnectionHub not initialized');
468
- return;
479
+ return fail('❌ Server error: ConnectionHub not initialized');
469
480
  }
470
481
  // Check if device is online
471
482
  if (!this.connectionHub.isDeviceOnline(activeDevice.deviceId)) {
472
- await this.replyToMessage(messageId, `❌ Device ${activeDevice.deviceName} is currently offline, please ensure the device is started and connected to the server`);
473
- return;
483
+ return fail(`❌ Device ${activeDevice.deviceName} is currently offline, please ensure the device is started and connected to the server`);
474
484
  }
475
485
  if (useActiveThread && (content.trim() === '/thread' || content.trim() === '/thread list')
476
486
  && await this.onRecoverThreads?.(openId, activeDevice.deviceId, messageId))
@@ -483,16 +493,14 @@ class FeishuLongConnHandler {
483
493
  }
484
494
  catch (error) {
485
495
  if (error instanceof Error && error.message.startsWith('Saved thread selection is invalid')) {
486
- await this.replyToMessage(messageId, `❌ ${error.message}`);
487
- return;
496
+ return fail(`❌ ${error.message}`);
488
497
  }
489
498
  throw error;
490
499
  }
491
500
  }
492
501
  const selectionFence = originalFence ?? this.onCaptureSelection?.(openId, activeDevice.deviceId);
493
502
  if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
494
- await this.replyToMessage(messageId, 'The device or thread selection changed. Reopen /skills.');
495
- return;
503
+ return fail('The device or thread selection changed. Reopen /skills.');
496
504
  }
497
505
  console.log(`[FeishuHandler] Passing through slash command: ${command}${threadId ? ` (threadId=${threadId})` : ''}`);
498
506
  // Generate message ID first
@@ -501,17 +509,17 @@ class FeishuLongConnHandler {
501
509
  const feishuMessageId = await this.sendStreamingStart(openId, `🤔 Executing ${command}...`, threadName, undefined, commandMessageId);
502
510
  const currentBinding = await this.bindingManager.getUserBinding(openId);
503
511
  if (!currentBinding?.devices.some((device) => device.deviceId === activeDevice.deviceId)) {
504
- throw new Error('Device ownership changed before the command could be sent.');
512
+ return fail('Device ownership changed before the command could be sent. Reopen /skills.');
505
513
  }
506
514
  if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
507
- throw new Error('This command was superseded or the device changed before it could be sent.');
515
+ return fail('This command was superseded or the device changed before it could be sent. Reopen /skills.');
508
516
  }
509
517
  console.log(`[FeishuHandler] Created card ${feishuMessageId} for slash command ${commandMessageId}`);
510
518
  if (this.onStartStreaming) {
511
519
  await this.onStartStreaming(commandMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, false, undefined, threadName, selectionFence);
512
520
  }
513
521
  if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
514
- throw new Error('This command was superseded or the device changed before it could be sent.');
522
+ return fail('This command was superseded or the device changed before it could be sent. Reopen /skills.');
515
523
  }
516
524
  // Send slash command to device - the client will execute it locally
517
525
  const success = await this.connectionHub.sendToDevice(activeDevice.deviceId, {
@@ -524,12 +532,12 @@ class FeishuLongConnHandler {
524
532
  threadId, // Forward threadId to CLI for per-thread routing
525
533
  });
526
534
  if (!success) {
527
- await this.replyToMessage(messageId, '❌ Command sending failed, please try again later');
535
+ return fail('❌ Command sending failed, please try again later');
528
536
  }
529
537
  }
530
538
  catch (error) {
531
539
  console.error('Error handling slash command passthrough:', error);
532
- await this.replyToMessage(messageId, '❌ Error processing command, please try again later');
540
+ return fail('❌ Error processing command, please try again later');
533
541
  }
534
542
  }
535
543
  /**
@@ -823,17 +831,25 @@ class FeishuLongConnHandler {
823
831
  const state = this.commandMenus.get(cardId);
824
832
  if (!state || state.openId !== openId || state.expires <= Date.now())
825
833
  throw new Error('Reopen /skills for a fresh menu.');
834
+ const validate = () => {
835
+ if (this.commandMenus.get(cardId) !== state || state.expires <= Date.now())
836
+ throw new Error('Reopen /skills for a fresh menu.');
837
+ if (state.fence && !this.onValidateSelection?.(state.fence))
838
+ throw new Error('Selection changed. Reopen /skills.');
839
+ };
840
+ validate();
826
841
  return state.menu.click(action, form, async (elements) => {
842
+ validate();
827
843
  const result = await this.client.im.message.patch({ path: { message_id: cardId },
828
844
  data: { content: JSON.stringify({ schema: '2.0', header: CommandMenu_1.commandMenuHeader, body: { elements } }) } });
829
845
  if (result.code)
830
846
  throw new Error('Menu update failed.');
831
847
  }, async (content) => {
832
848
  const [command, operation, target] = content.split(/\s+/);
833
- if (state.fence && !this.onValidateSelection?.(state.fence))
834
- throw new Error('Selection changed. Reopen /skills.');
849
+ validate();
835
850
  if (command === '/device' && (operation === 'switch' || operation === 'unbind')) {
836
851
  const binding = await this.bindingManager.getUserBinding(openId);
852
+ validate();
837
853
  const epoch = state.deviceEpochs.get(target);
838
854
  if (!binding || !epoch || this.bindingManager.getCardThreadEpoch(openId, target) !== epoch
839
855
  || !binding.devices.some(device => device.deviceId === target))
@@ -853,7 +869,9 @@ class FeishuLongConnHandler {
853
869
  if (command === '/thread' && content === '/thread list' && state.topLevel
854
870
  && await this.onRecoverThreads?.(openId, state.deviceId, cardId, state.fence))
855
871
  return;
856
- await this.handleSlashCommandPassthrough(openId, cardId, content, command, state.threadId, state.threadName, state.deviceId, false, state.fence);
872
+ const failure = await this.handleSlashCommandPassthrough(openId, cardId, content, command, state.threadId, state.threadName, state.deviceId, false, state.fence, true);
873
+ if (failure)
874
+ throw new Error(failure);
857
875
  });
858
876
  }
859
877
  async handleHelpCommand(openId, messageId) {
@@ -914,6 +932,7 @@ Examples:
914
932
  * Handle regular command (non-slash commands)
915
933
  */
916
934
  async handleRegularCommand(openId, messageId, content, threadId, pendingNewThread = false, threadName, attachments, fileReference, sourceDeviceId, useActiveThread = false, selectionIntent) {
935
+ let unsent;
917
936
  try {
918
937
  // Find user binding
919
938
  const binding = await this.bindingManager.getUserBinding(openId);
@@ -964,6 +983,7 @@ Examples:
964
983
  // Register streaming session BEFORE sending command to avoid race condition
965
984
  // where stream chunks arrive before registration
966
985
  const feishuMessageId = await this.sendStreamingStart(openId, attachments ? '🖼️ Processing image...' : '🤔 Processing...', threadName, undefined, commandMessageId);
986
+ unsent = { commandId: commandMessageId, cardId: feishuMessageId };
967
987
  const currentBinding = await this.bindingManager.getUserBinding(openId);
968
988
  if (!currentBinding?.devices.some((device) => device.deviceId === activeDevice.deviceId)) {
969
989
  throw new Error('Device ownership changed before the command could be sent.');
@@ -989,16 +1009,24 @@ Examples:
989
1009
  openId,
990
1010
  threadId, // Forward threadId to CLI for per-thread routing
991
1011
  });
992
- if (!success) {
993
- // Send failed - delete the streaming session and notify user
994
- if (this.onStartStreaming) {
995
- // We need a way to clean up, for now just send error as new message
996
- await this.replyToMessage(messageId, '❌ Command sending failed, please try again later');
997
- }
998
- }
1012
+ if (!success)
1013
+ throw new Error('Command sending failed.');
999
1014
  }
1000
1015
  catch (error) {
1001
1016
  console.error('Error handling regular command:', error);
1017
+ if (unsent) {
1018
+ const notice = 'Command was not sent. Check the device and thread, then resend your message.';
1019
+ try {
1020
+ await this.onCommandNotSent?.(unsent.commandId);
1021
+ }
1022
+ catch (failure) {
1023
+ (0, DeliveryDiagnostics_1.deliveryEvent)('unsent_command_cleanup_failed', (0, DeliveryDiagnostics_1.safeCardError)(failure));
1024
+ }
1025
+ if (unsent.cardId && await this.finalizeStreamingMessage(unsent.cardId, [{ tag: 'markdown', content: notice }], undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, false, { bare: true }))
1026
+ return;
1027
+ await this.replyToMessage(messageId, notice);
1028
+ return;
1029
+ }
1002
1030
  await this.replyToMessage(messageId, '❌ Error processing command, please try again later');
1003
1031
  }
1004
1032
  }
@@ -1103,8 +1131,11 @@ Examples:
1103
1131
  * Send message to user
1104
1132
  */
1105
1133
  async sendMessage(openId, text) {
1134
+ return !!await this.sendMessageWithReceipt(openId, text);
1135
+ }
1136
+ async sendMessageWithReceipt(openId, text) {
1106
1137
  try {
1107
- await this.client.im.message.create({
1138
+ const receipt = await this.client.im.message.create({
1108
1139
  params: { receive_id_type: 'open_id' },
1109
1140
  data: {
1110
1141
  receive_id: openId,
@@ -1112,11 +1143,14 @@ Examples:
1112
1143
  content: JSON.stringify({ text }),
1113
1144
  },
1114
1145
  });
1115
- return true;
1146
+ const id = receipt?.data?.message_id;
1147
+ if (receipt?.code || typeof id !== 'string' || !id.trim())
1148
+ throw new Error('Feishu text delivery was not confirmed.');
1149
+ return id;
1116
1150
  }
1117
1151
  catch (error) {
1118
1152
  (0, DeliveryDiagnostics_1.deliveryEvent)('text_message_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
1119
- return false;
1153
+ return null;
1120
1154
  }
1121
1155
  }
1122
1156
  /**
@@ -1138,7 +1172,7 @@ Examples:
1138
1172
  content,
1139
1173
  },
1140
1174
  }));
1141
- return result?.data?.message_id || null;
1175
+ return result?.code ? null : result?.data?.message_id || null;
1142
1176
  }
1143
1177
  catch (error) {
1144
1178
  // Actual request failures are already aggregated at the send boundary.
@@ -1839,9 +1873,8 @@ Examples:
1839
1873
  if (metadataElement)
1840
1874
  footerElements.push(metadataElement);
1841
1875
  finalElements.push(...elements, ...footerElements);
1842
- if (queueConfirmation) {
1843
- finalElements.push(...this.createQueueConfirmationElements(queueConfirmation));
1844
- }
1876
+ const queueElements = queueConfirmation ? this.createQueueConfirmationElements(queueConfirmation) : [];
1877
+ finalElements.push(...queueElements);
1845
1878
  // Append thread switch buttons when at least one thread exists
1846
1879
  let threadSwitchElements = [];
1847
1880
  // The reply's owner and the destination of new messages are independent.
@@ -1875,8 +1908,15 @@ Examples:
1875
1908
  // card IDs before any callback can arrive.
1876
1909
  if (options?.onDelivered) {
1877
1910
  const delivered = this.messageChains.get(messageId);
1878
- if (delivered && delivered.length > 0)
1879
- await options.onDelivered([...delivered]);
1911
+ if (delivered?.length) {
1912
+ if (queueElements.length) {
1913
+ const chunks = this.splitElementsIntoChunks(finalElements, headerElements, trailingElements, undefined, keepCompletionWithBody, this.inlineFiles?.hasRoot(messageId));
1914
+ const page = chunks.findIndex(chunk => chunk.includes(queueElements.at(-1)));
1915
+ await options.onDelivered([...delivered], delivered[page]);
1916
+ }
1917
+ else
1918
+ await options.onDelivered([...delivered]);
1919
+ }
1880
1920
  }
1881
1921
  if (!bare && this.inlineFiles) {
1882
1922
  const chunks = this.splitElementsIntoChunks(finalElements, headerElements, trailingElements, undefined, keepCompletionWithBody, this.inlineFiles?.hasRoot(messageId));
@@ -2134,7 +2174,7 @@ Examples:
2134
2174
  return { toast };
2135
2175
  void click.then(result => {
2136
2176
  if (result.type === 'error')
2137
- return this.sendMessage(openId, result.content);
2177
+ return this.replyToMessage(data.context.open_message_id, result.content);
2138
2178
  }).catch(() => { });
2139
2179
  return { toast: { type: 'info', content: 'Processing your selection.' } };
2140
2180
  }
@@ -2294,11 +2334,13 @@ Examples:
2294
2334
  if (queueActionResult === 'already_processed') {
2295
2335
  return { toast: { type: 'info', content: 'This queue request was already processed' } };
2296
2336
  }
2297
- return { toast: { type: 'success', content: parsed.action === 'queue_confirm' ? 'Queue confirmation sent' : 'Queue request cancelled' } };
2337
+ if (queueActionResult !== 'sent')
2338
+ throw new Error('Queue action unavailable.');
2339
+ return { toast: { type: 'info', content: parsed.action === 'queue_confirm' ? 'Queue confirmation sent' : 'Queue cancellation sent' } };
2298
2340
  }
2299
2341
  catch (error) {
2300
2342
  (0, DeliveryDiagnostics_1.deliveryEvent)('card_queue_action_failed', (0, DeliveryDiagnostics_1.safeCardError)(error));
2301
- return { toast: { type: 'error', content: 'Queue action failed' } };
2343
+ return { toast: { type: 'error', content: 'Queue action failed. Check /queue on the original device.' } };
2302
2344
  }
2303
2345
  }
2304
2346
  }
@@ -2314,83 +2356,79 @@ Examples:
2314
2356
  }
2315
2357
  /** Register confirmed work; capable clients request a card when execution starts. */
2316
2358
  async sendQueueActionFromCardAction(openId, action, queueId, threadId, cardMessageId) {
2359
+ const route = cardMessageId && this.store.getCardThread(cardMessageId);
2360
+ if (!cardMessageId || !route || route.queueId !== queueId || route.openId !== openId || route.threadId !== threadId) {
2361
+ throw new Error('This queue card has expired. Use /queue on the original device.');
2362
+ }
2363
+ const { deviceId, epoch } = route;
2364
+ const fence = this.onCaptureSelection?.(openId, deviceId);
2365
+ const current = () => this.store.getCardThread(cardMessageId) === route
2366
+ && (!fence || (fence.epoch === epoch && this.onValidateSelection?.(fence) === true));
2367
+ const device = await this.bindingManager.getActiveDevice(openId);
2368
+ const hub = this.connectionHub;
2369
+ if (!current() || device?.deviceId !== deviceId || !hub?.isDeviceOnline(deviceId)) {
2370
+ throw new Error('The original device changed or is offline.');
2371
+ }
2317
2372
  this.removeExpiredQueueActionStates();
2318
- const previousAction = this.queueActionStates.get(queueId);
2319
- if (previousAction) {
2373
+ const key = JSON.stringify([openId, deviceId, epoch, threadId, queueId]);
2374
+ const previous = this.queueActionStates.get(key);
2375
+ if (previous) {
2376
+ await previous.sent;
2320
2377
  return 'already_processed';
2321
2378
  }
2322
- this.queueActionStates.set(queueId, { action, processedAt: Date.now() });
2323
- const binding = await this.bindingManager.getUserBinding(openId);
2324
- const activeDevice = binding ? await this.bindingManager.getActiveDevice(openId) : null;
2325
- if (!activeDevice || !this.connectionHub?.isDeviceOnline(activeDevice.deviceId)) {
2326
- this.queueActionStates.delete(queueId);
2327
- throw new Error('No active online device found');
2328
- }
2329
- const selectionFence = this.onCaptureSelection?.(openId, activeDevice.deviceId);
2330
- let executionMessageId;
2331
- if (action === 'confirm') {
2332
- executionMessageId = (0, uuid_1.v4)();
2333
- const feishuMessageId = this.connectionHub.supportsQueueStarted(activeDevice.deviceId)
2334
- ? null
2335
- : await this.sendStreamingStart(openId, '🤔 Queued message confirmed. Waiting for the current task to finish...', undefined, undefined, executionMessageId);
2336
- try {
2337
- await this.onStartStreaming?.(executionMessageId, openId, feishuMessageId, activeDevice.deviceId, threadId, false, cardMessageId, undefined, selectionFence);
2338
- }
2339
- catch (error) {
2340
- // No command was sent. A failed durable route must not consume the confirmation.
2341
- this.queueActionStates.delete(queueId);
2342
- throw error;
2343
- }
2344
- }
2345
- if (selectionFence && this.onValidateSelection && !this.onValidateSelection(selectionFence)) {
2346
- this.queueActionStates.delete(queueId);
2347
- throw new Error('This queue action was superseded or the device changed before it could be sent.');
2348
- }
2349
- const controlMessageId = (0, uuid_1.v4)();
2350
- const suffix = executionMessageId ? ` ${executionMessageId}` : '';
2351
- // An idle thread can start immediately. Its receipt must not be patched
2352
- // back to "waiting" after the start event has already arrived.
2353
- let finishDecision;
2354
- const decision = new Promise((resolve) => { finishDecision = resolve; });
2355
- if (cardMessageId)
2356
- this.queueCardDecisions.set(cardMessageId, decision);
2357
- try {
2358
- const success = await this.connectionHub.sendToDevice(activeDevice.deviceId, {
2359
- type: types_1.MessageType.COMMAND,
2360
- messageId: controlMessageId,
2361
- timestamp: Date.now(),
2362
- content: `/queue ${action} ${queueId}${suffix}`,
2363
- openId,
2364
- threadId,
2379
+ const send = async () => {
2380
+ let executionId;
2381
+ if (action === 'confirm') {
2382
+ executionId = (0, uuid_1.v4)();
2383
+ const placeholder = hub.supportsQueueStarted(deviceId) ? null
2384
+ : await this.sendStreamingStart(openId, 'Requesting queue confirmation...', undefined, undefined, executionId);
2385
+ await this.onStartStreaming?.(executionId, openId, placeholder, deviceId, threadId, false, cardMessageId, undefined, fence);
2386
+ }
2387
+ if (!current())
2388
+ throw new Error('The device changed before the queue action could be sent.');
2389
+ const suffix = executionId ? ` ${executionId}` : '';
2390
+ const sent = await hub.sendToDevice(deviceId, {
2391
+ type: types_1.MessageType.COMMAND, messageId: (0, uuid_1.v4)(), timestamp: Date.now(),
2392
+ content: `/queue ${action} ${queueId}${suffix}`, openId, threadId,
2365
2393
  });
2366
- if (!success)
2394
+ if (!sent)
2367
2395
  throw new Error('Failed to send queue action to device');
2368
- if (cardMessageId)
2369
- await this.updateQueueConfirmationCard(cardMessageId, action);
2396
+ await this.updateQueueConfirmationCard(cardMessageId, action, current);
2397
+ };
2398
+ const sent = Promise.resolve().then(send);
2399
+ this.queueActionStates.set(key, { sent, processedAt: Date.now() });
2400
+ // An idle thread can start before the send promise settles.
2401
+ this.queueCardDecisions.set(cardMessageId, sent);
2402
+ try {
2403
+ await sent;
2370
2404
  return 'sent';
2371
2405
  }
2372
2406
  catch (error) {
2373
- this.queueActionStates.delete(queueId);
2407
+ this.queueActionStates.delete(key);
2374
2408
  throw error;
2375
2409
  }
2376
2410
  finally {
2377
- finishDecision();
2378
- if (cardMessageId)
2379
- this.queueCardDecisions.delete(cardMessageId);
2411
+ this.queueCardDecisions.delete(cardMessageId);
2380
2412
  }
2381
2413
  }
2382
2414
  /** Leave a historical queue receipt after output moves to a new card. */
2383
- async markQueueCardStarted(cardMessageId) {
2415
+ async markQueueCardStarted(cardMessageId, current = () => true) {
2384
2416
  await this.queueCardDecisions.get(cardMessageId);
2385
- await this.withMessageLock(cardMessageId, () => this.client.im.message.patch({
2386
- path: { message_id: cardMessageId },
2387
- data: {
2388
- content: JSON.stringify({
2389
- schema: '2.0',
2390
- body: { elements: [{ tag: 'markdown', content: "<text_tag color='blue'>Running</text_tag>\n\nThe queued message is now running. Follow progress in the new execution card." }] },
2391
- }),
2392
- },
2393
- }));
2417
+ await this.withMessageLock(cardMessageId, async () => {
2418
+ if (!current())
2419
+ return;
2420
+ const result = await this.client.im.message.patch({
2421
+ path: { message_id: cardMessageId },
2422
+ data: {
2423
+ content: JSON.stringify({
2424
+ schema: '2.0',
2425
+ body: { elements: [{ tag: 'markdown', content: "<text_tag color='blue'>Running</text_tag>\n\nThe queued message is now running. Follow progress in the new execution card." }] },
2426
+ }),
2427
+ },
2428
+ });
2429
+ if (result?.code)
2430
+ throw new Error('Queue start card update failed.');
2431
+ });
2394
2432
  }
2395
2433
  removeExpiredQueueActionStates() {
2396
2434
  const expiry = Date.now() - this.QUEUE_ACTION_STATE_TTL_MS;
@@ -2400,13 +2438,15 @@ Examples:
2400
2438
  }
2401
2439
  }
2402
2440
  }
2403
- async updateQueueConfirmationCard(cardMessageId, action) {
2441
+ async updateQueueConfirmationCard(cardMessageId, action, current) {
2404
2442
  const content = action === 'confirm'
2405
- ? "<text_tag color='green'>Queued</text_tag>\n\nThis message was accepted into the thread queue. Use /queue to check its status. If the queue is paused, use /queue continue to resume."
2406
- : "<text_tag color='grey'>Cancelled</text_tag>\n\nThis message was not added to the thread queue.";
2443
+ ? "Queue confirmation sent. See the CLI response or use /queue to check its status. If the queue is paused, use /queue continue to resume."
2444
+ : "Queue cancellation sent. See the CLI response or use /queue to check its status.";
2407
2445
  try {
2408
2446
  await this.withMessageLock(cardMessageId, async () => {
2409
- await this.client.im.message.patch({
2447
+ if (!current())
2448
+ return;
2449
+ const result = await this.client.im.message.patch({
2410
2450
  path: { message_id: cardMessageId },
2411
2451
  data: {
2412
2452
  content: JSON.stringify({
@@ -2415,6 +2455,8 @@ Examples:
2415
2455
  }),
2416
2456
  },
2417
2457
  });
2458
+ if (result?.code)
2459
+ throw new Error('Queue confirmation card update failed.');
2418
2460
  });
2419
2461
  }
2420
2462
  catch (error) {