@yu_robotics/remote-cli-router 1.6.184 → 1.6.189

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.
package/dist/server.js CHANGED
@@ -27,6 +27,7 @@ const ws_1 = require("ws");
27
27
  const FeishuLongConnHandler_1 = require("./feishu/FeishuLongConnHandler");
28
28
  const ConnectionHub_1 = require("./websocket/ConnectionHub");
29
29
  const BindingManager_1 = require("./binding/BindingManager");
30
+ const ThreadSelectionManager_1 = require("./binding/ThreadSelectionManager");
30
31
  const types_1 = require("./types");
31
32
  const ToolFormatter_1 = require("./utils/ToolFormatter");
32
33
  const DELEGATION_PROGRESS_PHASES = new Set([
@@ -73,9 +74,8 @@ class RouterServer {
73
74
  // Entries are NOT removed on finalize so users can reply to completed cards.
74
75
  // Each entry carries an expiresAt timestamp for TTL-based eviction.
75
76
  cardThreadMap = new Map();
76
- // Map from openId to the user's currently active thread (set by card button click).
77
- // New top-level messages (no parent_id) are routed to this thread.
78
- activeThreadMap = new Map();
77
+ selections;
78
+ threadInventoryRequests = new Map();
79
79
  deviceAuth;
80
80
  fileTransfers;
81
81
  constructor(config, store) {
@@ -84,6 +84,10 @@ class RouterServer {
84
84
  this.app = new koa_1.default();
85
85
  this.connectionHub = new ConnectionHub_1.ConnectionHub();
86
86
  this.bindingManager = new BindingManager_1.BindingManager(store);
87
+ this.selections = new ThreadSelectionManager_1.ThreadSelectionManager(this.bindingManager, {
88
+ names: () => undefined,
89
+ notify: async (openId, text) => { await this.feishuLongConnHandler.sendMessage(openId, text); },
90
+ });
87
91
  this.deviceAuth = new DeviceAuth_1.DeviceAuth(path_1.default.join(path_1.default.dirname(config.getConfigPath() || path_1.default.join(os_1.default.homedir(), '.remote-cli-router', 'config.json')), 'device-auth.json'));
88
92
  // Initialize FeishuLongConnHandler (WebSocket mode)
89
93
  this.feishuLongConnHandler = new FeishuLongConnHandler_1.FeishuLongConnHandler({
@@ -145,10 +149,16 @@ class RouterServer {
145
149
  if ((await this.bindingManager.getDeviceBinding(deviceId))?.openId !== openId)
146
150
  throw new Error('Device ownership changed.');
147
151
  await this.deviceAuth.enroll(deviceId, openId, publicKey);
152
+ this.selections.invalidateDevice(openId, deviceId);
153
+ this.expireDeviceCards(deviceId);
148
154
  this.connectionHub.disconnectDevice(deviceId);
149
155
  this.fileTransfers.disconnect(deviceId);
150
156
  };
151
157
  this.feishuLongConnHandler.onRevokeDevice = async (deviceId) => {
158
+ const owner = await this.bindingManager.getDeviceBinding(deviceId);
159
+ if (owner?.openId)
160
+ this.selections.invalidateDevice(owner.openId, deviceId);
161
+ this.expireDeviceCards(deviceId);
152
162
  await this.deviceAuth.revoke(deviceId);
153
163
  this.connectionHub.disconnectDevice(deviceId);
154
164
  this.fileTransfers.disconnect(deviceId);
@@ -158,8 +168,8 @@ class RouterServer {
158
168
  sendToDevice: (deviceId, message) => this.connectionHub.sendToDevice(deviceId, message),
159
169
  create: (openId, elements, header) => this.feishuLongConnHandler.sendTaskNotificationCard(openId, elements, header),
160
170
  update: (cardId, elements, header) => this.feishuLongConnHandler.updateApprovalCard(cardId, elements, header),
161
- registerReplyRoute: (cardId, threadId, deviceId) => {
162
- this.cardThreadMap.set(cardId, { threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
171
+ registerReplyRoute: (cardId, threadId, deviceId, openId) => {
172
+ this.cardThreadMap.set(cardId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
163
173
  },
164
174
  });
165
175
  this.feishuLongConnHandler.onApprovalAction = (openId, requestId, cardId, decision) => this.approvalCards.click(openId, requestId, cardId, decision);
@@ -191,7 +201,9 @@ class RouterServer {
191
201
  })
192
202
  : this.maintenanceCards.reply(openId, id, cardId, action);
193
203
  // Register callback for streaming message start
194
- this.feishuLongConnHandler.setOnStartStreaming((messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName) => {
204
+ this.feishuLongConnHandler.setOnCaptureSelection((openId, deviceId) => this.selections.capture(openId, deviceId));
205
+ this.feishuLongConnHandler.setOnValidateSelection(fence => this.selections.isCurrent(fence));
206
+ this.feishuLongConnHandler.setOnStartStreaming((messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName, selectionIntent) => {
195
207
  console.log(`[RouterServer] Registering streaming session: msgId=${messageId}, feishuMsgId=${feishuMessageId}, deviceId=${deviceId}, threadId=${threadId}, pendingNewThread=${pendingNewThread}`);
196
208
  this.cancelImageReply(messageId);
197
209
  const previous = this.streamingMessages.get(messageId);
@@ -208,6 +220,8 @@ class RouterServer {
208
220
  threadId,
209
221
  threadName,
210
222
  pendingNewThread,
223
+ selectionFence: selectionIntent ?? this.selections.capture(openId, deviceId),
224
+ newThreadIntent: pendingNewThread ? selectionIntent : undefined,
211
225
  queueCardId,
212
226
  updatePending: false,
213
227
  finalizing: false,
@@ -217,50 +231,66 @@ class RouterServer {
217
231
  });
218
232
  // Populate cardThreadMap for parent_id-based routing
219
233
  if (feishuMessageId && threadId) {
220
- this.cardThreadMap.set(feishuMessageId, { threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
234
+ this.cardThreadMap.set(feishuMessageId, { threadId, deviceId, openId, epoch: selectionIntent?.epoch ?? this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
221
235
  }
222
236
  console.log(`[RouterServer] Total streaming sessions: ${this.streamingMessages.size}`);
223
237
  });
224
238
  // Register callback for thread resolution from Feishu parent_id
225
- this.feishuLongConnHandler.setOnResolveThread((feishuMessageId) => {
226
- const entry = this.cardThreadMap.get(feishuMessageId);
227
- if (!entry)
228
- return undefined;
229
- // Evict expired entries on read
230
- if (Date.now() > entry.expiresAt) {
231
- this.cardThreadMap.delete(feishuMessageId);
232
- return undefined;
233
- }
234
- return entry;
239
+ this.feishuLongConnHandler.setOnResolveThread(async (feishuMessageId, openId) => {
240
+ return this.resolveCardThread(feishuMessageId, openId);
235
241
  });
236
242
  // Register callback for resolving user's active thread (new top-level messages)
237
- this.feishuLongConnHandler.setOnResolveActiveThread((openId) => {
238
- return this.activeThreadMap.get(openId);
243
+ this.feishuLongConnHandler.setOnResolveActiveThread(async (openId, deviceId) => {
244
+ return this.selections.resolve(openId, deviceId);
239
245
  });
246
+ this.feishuLongConnHandler.onRecoverThreads = async (openId, deviceId) => {
247
+ const messageId = (0, crypto_1.randomUUID)();
248
+ const fence = this.selections.beginIntent(openId, deviceId);
249
+ const timer = setTimeout(() => {
250
+ if (!this.threadInventoryRequests.delete(messageId))
251
+ return;
252
+ void this.feishuLongConnHandler.sendMessage(openId, 'Could not refresh thread controls. Check the device connection and retry /thread list.');
253
+ }, 10_000);
254
+ timer.unref?.();
255
+ this.threadInventoryRequests.set(messageId, { openId, deviceId, fence, timer });
256
+ const sent = await this.connectionHub.sendToDevice(deviceId, { type: 'status', messageId, timestamp: Date.now() });
257
+ if (!sent) {
258
+ clearTimeout(timer);
259
+ this.threadInventoryRequests.delete(messageId);
260
+ await this.feishuLongConnHandler.sendMessage(openId, 'Could not refresh thread controls. Reconnect the device and retry /thread list.');
261
+ }
262
+ return true;
263
+ };
240
264
  // Register callback for card button thread switching
241
- this.feishuLongConnHandler.onCardSwitchThread = async (openId, threadId, threadName) => {
242
- this.activeThreadMap.set(openId, { threadId, threadName });
243
- console.log(`[RouterServer] Active thread set for ${openId}: ${threadName} (${threadId})`);
265
+ this.feishuLongConnHandler.onCardSwitchThread = async (openId, cardId, threadId, threadName) => {
266
+ const revision = this.selections.reserveIntent(openId);
267
+ const source = await this.requireCurrentCardDevice(cardId, openId);
268
+ const intent = this.selections.intent(openId, source.deviceId, revision);
269
+ const selected = await this.selections.select(openId, source.deviceId, threadId, threadName, intent);
270
+ if (selected !== 'selected')
271
+ throw new Error('This selection was superseded or the device changed. Use a fresh thread card.');
272
+ console.log(`[RouterServer] Durable thread selection saved for ${openId}: ${threadName} (${threadId})`);
244
273
  };
245
274
  // Register callback for creating a new thread via card button
246
- this.feishuLongConnHandler.onCardNewThread = async (openId) => {
275
+ this.feishuLongConnHandler.onCardNewThread = async (openId, cardId) => {
276
+ const revision = this.selections.reserveIntent(openId);
277
+ const source = await this.requireCurrentCardDevice(cardId, openId);
278
+ const intent = this.selections.intent(openId, source.deviceId, revision);
247
279
  console.log(`[RouterServer] Creating new thread for ${openId} via card button`);
248
- await this.feishuLongConnHandler.sendCommandFromCardAction(openId, '/thread new', true);
280
+ await this.feishuLongConnHandler.sendCommandFromCardAction(openId, '/thread new', true, source.deviceId, intent);
249
281
  };
250
282
  this.feishuLongConnHandler.onQueueAction = async (openId, action, queueId, threadId, cardMessageId) => {
251
283
  return this.feishuLongConnHandler.sendQueueActionFromCardAction(openId, action, queueId, threadId, cardMessageId);
252
284
  };
253
- // Register callback for device switch — clear thread state tied to the old device
254
- this.feishuLongConnHandler.onDeviceSwitch = (openId, oldDeviceId) => {
255
- // Clear the active thread so the next message goes to the new device's default thread
256
- this.activeThreadMap.delete(openId);
257
- console.log(`[RouterServer] Cleared activeThreadMap for ${openId} after device switch`);
258
- // Remove cardThreadMap entries that belonged to the old device to avoid stale thread lookups
285
+ this.feishuLongConnHandler.onDeviceSwitchIntent = (openId, newDeviceId) => {
286
+ this.selections.beginIntent(openId, newDeviceId);
287
+ };
288
+ // Device switches retain independent durable selections and invalidate older intents.
289
+ this.feishuLongConnHandler.onDeviceSwitch = (openId, oldDeviceId, newDeviceId) => {
259
290
  if (oldDeviceId) {
260
291
  for (const [feishuMessageId, entry] of this.cardThreadMap.entries()) {
261
- if (entry.deviceId === oldDeviceId) {
292
+ if (entry.deviceId === oldDeviceId)
262
293
  this.cardThreadMap.delete(feishuMessageId);
263
- }
264
294
  }
265
295
  console.log(`[RouterServer] Cleared cardThreadMap entries for old device ${oldDeviceId}`);
266
296
  }
@@ -268,6 +298,40 @@ class RouterServer {
268
298
  this.setupMiddleware();
269
299
  this.setupRoutes();
270
300
  }
301
+ expireDeviceCards(deviceId) {
302
+ for (const [cardId, entry] of this.cardThreadMap) {
303
+ if (entry.deviceId === deviceId)
304
+ this.cardThreadMap.delete(cardId);
305
+ }
306
+ }
307
+ async resolveCardThread(cardId, openId) {
308
+ const entry = this.cardThreadMap.get(cardId);
309
+ if (!entry)
310
+ return undefined;
311
+ if (Date.now() > entry.expiresAt) {
312
+ this.cardThreadMap.delete(cardId);
313
+ return undefined;
314
+ }
315
+ if (entry.openId !== openId || !this.selections.isOwnershipCurrent(openId, entry.deviceId, entry.epoch))
316
+ return undefined;
317
+ if ((await this.bindingManager.getDeviceBinding(entry.deviceId))?.openId !== openId
318
+ || this.cardThreadMap.get(cardId) !== entry
319
+ || !this.selections.isOwnershipCurrent(openId, entry.deviceId, entry.epoch))
320
+ return undefined;
321
+ return { threadId: entry.threadId, deviceId: entry.deviceId };
322
+ }
323
+ async requireCurrentCardDevice(cardId, openId) {
324
+ const entry = this.cardThreadMap.get(cardId);
325
+ const source = await this.resolveCardThread(cardId, openId);
326
+ if (!source)
327
+ throw new Error('This thread card has expired. Run /thread list for a fresh card.');
328
+ const active = await this.bindingManager.getActiveDevice(openId);
329
+ if (!active || active.deviceId !== source.deviceId || !entry || this.cardThreadMap.get(cardId) !== entry
330
+ || !this.selections.isOwnershipCurrent(openId, entry.deviceId, entry.epoch)) {
331
+ throw new Error('This card belongs to a different device. Switch back to that device or use a fresh card.');
332
+ }
333
+ return source;
334
+ }
271
335
  /**
272
336
  * Setup Koa middleware
273
337
  */
@@ -429,6 +493,10 @@ class RouterServer {
429
493
  return;
430
494
  // Update heartbeat on any message
431
495
  resetHeartbeat();
496
+ if (message.type === 'status' && this.threadInventoryRequests.has(message.messageId)) {
497
+ await this.handleThreadInventoryResponse(message, deviceId, ws);
498
+ return;
499
+ }
432
500
  if (message.type === 'file_status') {
433
501
  if (deviceId)
434
502
  await this.fileTransfers.handleStatus(deviceId, message);
@@ -472,6 +540,10 @@ class RouterServer {
472
540
  const imageDevice = deviceId;
473
541
  const imageCurrent = () => !socketClosed && ws.readyState === ws_1.WebSocket.OPEN
474
542
  && !!imageDevice && this.connectionHub.isCurrentConnection(imageDevice, ws);
543
+ if ([types_1.MessageType.RESPONSE, types_1.MessageType.NOTIFICATION, types_1.MessageType.TASK_NOTIFICATION,
544
+ 'task_resume', 'stream', 'stream_context', 'queue_started'].includes(message.type)
545
+ && !await this.authorizeRecipientOutput(message, imageDevice, imageCurrent))
546
+ return;
475
547
  // Establish routing before card creation awaits. Payload admission and
476
548
  // response closure must occur before waiting for earlier operations.
477
549
  if (imageDevice && taskRecoveryEnabled && message.type === 'task_resume') {
@@ -538,7 +610,7 @@ class RouterServer {
538
610
  case 'task_resume': {
539
611
  if (!taskRecoveryEnabled || !deviceId)
540
612
  break;
541
- const current = () => this.connectionHub.isCurrentConnection(deviceId, ws);
613
+ const current = imageCurrent;
542
614
  let success = false;
543
615
  try {
544
616
  success = await this.handleTaskResume(message, deviceId, current);
@@ -724,34 +796,46 @@ class RouterServer {
724
796
  : undefined;
725
797
  const settingsMenu = (candidateSettingsMenu?.kind === 'delegation' && !delegationCardsEnabled)
726
798
  || (candidateSettingsMenu?.kind === 'directory' && !directoryCardsEnabled) ? undefined : candidateSettingsMenu;
727
- // If CLI reported a threadId and there is a streaming session for this message,
728
- // ensure the cardThreadMap is up to date (in case the CLI-reported threadId differs).
729
- if (responseThreadId && responseMessageId) {
730
- const session = this.streamingMessages.get(responseMessageId);
731
- if (session) {
732
- if (session.feishuMessageId && session.threadId !== responseThreadId) {
733
- session.threadId = responseThreadId;
734
- this.cardThreadMap.set(session.feishuMessageId, { threadId: responseThreadId, deviceId: session.deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
799
+ const responseSession = responseMessageId ? this.streamingMessages.get(responseMessageId) : undefined;
800
+ const responseSuccess = message.success ?? message.data?.success;
801
+ let selectionWarning;
802
+ if (responseSession) {
803
+ if (responseThreadId) {
804
+ if (responseSession.feishuMessageId && responseSession.threadId !== responseThreadId) {
805
+ responseSession.threadId = responseThreadId;
806
+ this.cardThreadMap.set(responseSession.feishuMessageId, { threadId: responseThreadId, deviceId: responseSession.deviceId, openId: responseSession.openId, epoch: responseSession.selectionFence?.epoch ?? this.selections.capture(responseSession.openId, responseSession.deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
735
807
  }
736
- // Resolve thread name from the threads summary array
737
808
  if (responseThreads) {
738
809
  const match = responseThreads.find(t => t.id === responseThreadId);
739
810
  if (match)
740
- session.threadName = match.name;
741
- }
742
- // Store full threads list for button rendering
743
- if (responseThreads) {
744
- session.threads = responseThreads;
811
+ responseSession.threadName = match.name;
745
812
  }
746
- // When the "+ New" card button triggered this command, update activeThreadMap
747
- // so the user's next new message routes to the newly created thread.
748
- if (session.pendingNewThread && responseThreadId && responseThreads && responseOpenId) {
749
- const newThread = responseThreads.find(t => t.id === responseThreadId);
750
- if (newThread) {
751
- this.activeThreadMap.set(responseOpenId, { threadId: responseThreadId, threadName: newThread.name });
752
- console.log(`[RouterServer] activeThreadMap updated for ${responseOpenId} after new thread: ${newThread.name} (${responseThreadId})`);
813
+ }
814
+ if (responseThreads)
815
+ responseSession.threads = responseThreads;
816
+ if (responseSuccess === true && responseSession.pendingNewThread && responseSession.newThreadIntent) {
817
+ const newThread = responseThreadId && (0, ThreadSelectionManager_1.isCompleteThreadCatalog)(responseThreads)
818
+ ? responseThreads.find(t => t.id === responseThreadId)
819
+ : undefined;
820
+ if (newThread) {
821
+ try {
822
+ await this.selections.completeNew(responseSession.newThreadIntent, newThread.id, imageCurrent);
823
+ }
824
+ catch {
825
+ selectionWarning = 'Thread created, but its selection was not saved. Reply to the new thread card or select it explicitly.';
753
826
  }
754
827
  }
828
+ else {
829
+ selectionWarning = 'Thread created, but its selection could not be confirmed. Reply to the new thread card or select it explicitly.';
830
+ }
831
+ }
832
+ if (responseThreads && responseSession.selectionFence) {
833
+ await this.selections.observeCatalog(responseSession.openId, responseSession.deviceId, responseSession.selectionFence, responseThreads, imageCurrent);
834
+ }
835
+ const responseError = message.error ?? message.data?.error;
836
+ if (responseSuccess === false && !responseThreadId && !responseThreads && responseSession.threadId
837
+ && responseSession.selectionFence && responseError === `Thread not found: ${responseSession.threadId}`) {
838
+ await this.selections.handleMissingThread(responseSession.openId, responseSession.deviceId, responseSession.selectionFence, responseSession.threadId, imageCurrent);
755
839
  }
756
840
  }
757
841
  if (responseMessageId && responseOpenId) {
@@ -777,6 +861,9 @@ class RouterServer {
777
861
  }
778
862
  }
779
863
  }
864
+ if (selectionWarning) {
865
+ await this.feishuLongConnHandler.sendMessage(responseOpenId, selectionWarning);
866
+ }
780
867
  if (taskRecoveryEnabled && deviceId && this.connectionHub.isCurrentConnection(deviceId, ws)
781
868
  && responseOpenId && responseMessageId && !queueConfirmation
782
869
  && typeof (message.success ?? message.data?.success) === 'boolean') {
@@ -947,6 +1034,78 @@ class RouterServer {
947
1034
  lastStreamUpdateTime = new Map();
948
1035
  STREAM_UPDATE_INTERVAL_MS = 500; // Update at least every 500ms
949
1036
  STREAM_UPDATE_MIN_LENGTH = 10; // Update every 10 characters
1037
+ async authorizeRecipientOutput(message, deviceId, isCurrent) {
1038
+ const openId = message.openId || message.data?.openId;
1039
+ if (!deviceId || typeof openId !== 'string' || !openId || !isCurrent())
1040
+ return false;
1041
+ const messageId = typeof message.messageId === 'string' && message.messageId ? message.messageId : undefined;
1042
+ const originalStream = messageId ? this.streamingMessages.get(messageId) : undefined;
1043
+ const originalRoute = messageId ? this.imageReplies.get(messageId) : undefined;
1044
+ const binding = await this.bindingManager.getDeviceBinding(deviceId);
1045
+ // Registration alone is insufficient: a legacy device can bind or change
1046
+ // owners after connecting, and a replacement socket may win during lookup.
1047
+ if (!isCurrent() || binding?.openId !== openId)
1048
+ return false;
1049
+ if (messageId) {
1050
+ if (originalStream && this.streamingMessages.get(messageId) !== originalStream)
1051
+ return false;
1052
+ if (originalRoute && this.imageReplies.get(messageId) !== originalRoute)
1053
+ return false;
1054
+ const stream = this.streamingMessages.get(messageId);
1055
+ if (stream && (stream.deviceId !== deviceId || stream.openId !== openId))
1056
+ return false;
1057
+ const route = this.imageReplies.get(messageId);
1058
+ if (route && (route.deviceId !== deviceId || route.openId !== openId))
1059
+ return false;
1060
+ if (stream)
1061
+ stream.currentConnection = isCurrent;
1062
+ }
1063
+ return true;
1064
+ }
1065
+ async canDispatchStreamOutput(messageId, stream) {
1066
+ const current = stream.currentConnection;
1067
+ if (this.streamingMessages.get(messageId) !== stream || (current && !current()))
1068
+ return false;
1069
+ const binding = await this.bindingManager.getDeviceBinding(stream.deviceId);
1070
+ return this.streamingMessages.get(messageId) === stream && binding?.openId === stream.openId
1071
+ && (!current || current());
1072
+ }
1073
+ async handleThreadInventoryResponse(message, deviceId, ws) {
1074
+ const pending = this.threadInventoryRequests.get(message.messageId);
1075
+ if (!pending)
1076
+ return;
1077
+ const current = () => deviceId === pending.deviceId && this.connectionHub.isCurrentConnection(pending.deviceId, ws)
1078
+ && this.selections.isCurrent(pending.fence);
1079
+ if (!current())
1080
+ return;
1081
+ const binding = await this.bindingManager.getDeviceBinding(pending.deviceId);
1082
+ if (!current() || binding?.openId !== pending.openId)
1083
+ return;
1084
+ clearTimeout(pending.timer);
1085
+ this.threadInventoryRequests.delete(message.messageId);
1086
+ const threads = message.status?.threads;
1087
+ if (!(0, ThreadSelectionManager_1.isCompleteThreadCatalog)(threads)) {
1088
+ await this.feishuLongConnHandler.sendMessage(pending.openId, 'The device returned an invalid thread inventory. Retry /thread list.');
1089
+ return;
1090
+ }
1091
+ const defaultThread = threads.find((thread) => thread.name === 'default');
1092
+ try {
1093
+ const reconciled = await this.selections.observeCatalog(pending.openId, pending.deviceId, pending.fence, threads, current);
1094
+ if (reconciled === 'stale' || reconciled === 'failed' || !current())
1095
+ return;
1096
+ const cardId = await this.feishuLongConnHandler.sendStreamingStart(pending.openId, '🗂️ Thread controls refreshed. Choose a thread for future top-level messages.');
1097
+ if (!cardId || !current())
1098
+ return;
1099
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(cardId, [], undefined, pending.openId, undefined, 'Thread selection', threads, defaultThread.id);
1100
+ if (!finalized || !current())
1101
+ return;
1102
+ this.cardThreadMap.set(cardId, { threadId: defaultThread.id, deviceId: pending.deviceId,
1103
+ openId: pending.openId, epoch: pending.fence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1104
+ }
1105
+ catch {
1106
+ await this.feishuLongConnHandler.sendMessage(pending.openId, 'Could not create thread controls. Retry /thread list.');
1107
+ }
1108
+ }
950
1109
  matchesActivityStream(message, deviceId) {
951
1110
  if (!deviceId || typeof message.messageId !== 'string' || typeof message.openId !== 'string'
952
1111
  || typeof message.threadId !== 'string' || !message.threadId)
@@ -985,7 +1144,7 @@ class RouterServer {
985
1144
  stream.cwd = cwd;
986
1145
  if (stream.feishuMessageId) {
987
1146
  this.cardThreadMap.set(stream.feishuMessageId, {
988
- threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
1147
+ threadId, deviceId, openId: stream.openId, epoch: stream.selectionFence?.epoch ?? this.selections.capture(stream.openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
989
1148
  });
990
1149
  await this.updateStreamingText(messageId, openId, stream);
991
1150
  }
@@ -1672,7 +1831,7 @@ class RouterServer {
1672
1831
  previous.lastRenderedTextLength = textLength;
1673
1832
  this.lastStreamUpdateTime.set(messageId, Date.now());
1674
1833
  }
1675
- this.cardThreadMap.set(previous.feishuMessageId, { threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1834
+ this.cardThreadMap.set(previous.feishuMessageId, { threadId, deviceId, openId, epoch: previous.selectionFence?.epoch ?? this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1676
1835
  }
1677
1836
  else {
1678
1837
  const escape = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -1693,7 +1852,7 @@ class RouterServer {
1693
1852
  toolCalls: new Map(),
1694
1853
  recoveryId: info.recoveryId, recoveryPlainText: true, recoveryCwd: info.cwd,
1695
1854
  });
1696
- this.cardThreadMap.set(cardId, { threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1855
+ this.cardThreadMap.set(cardId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1697
1856
  }
1698
1857
  this.bindImageStream(messageId);
1699
1858
  if (info.state !== 'running') {
@@ -1768,7 +1927,7 @@ class RouterServer {
1768
1927
  this.bindImageStream(messageId);
1769
1928
  if (cardId || fallbackCardId) {
1770
1929
  this.cardThreadMap.set((cardId || fallbackCardId), {
1771
- threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
1930
+ threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
1772
1931
  });
1773
1932
  }
1774
1933
  if (cardId) {
@@ -1822,13 +1981,29 @@ class RouterServer {
1822
1981
  const elements = (0, ToolFormatter_1.createTaskNotificationElement)(info, threadLabel);
1823
1982
  const feishuMessageId = await this.feishuLongConnHandler.sendTaskNotificationCard(openId, elements);
1824
1983
  if (feishuMessageId && threadId && deviceId) {
1825
- this.cardThreadMap.set(feishuMessageId, { threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1984
+ this.cardThreadMap.set(feishuMessageId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1826
1985
  console.log(`[RouterServer] Registered task notification card ${feishuMessageId} for thread ${threadId}`);
1827
1986
  }
1828
1987
  }
1829
1988
  /**
1830
1989
  * Finalize streaming message
1831
1990
  */
1991
+ registerDeliveredThreadCards(messageId, streamData, cardIds) {
1992
+ if (!streamData.threadId || this.streamingMessages.get(messageId) !== streamData)
1993
+ return;
1994
+ const fence = streamData.selectionFence;
1995
+ if (streamData.currentConnection && !streamData.currentConnection())
1996
+ return;
1997
+ const epoch = fence?.epoch ?? this.selections.capture(streamData.openId, streamData.deviceId).epoch;
1998
+ if (!this.selections.isOwnershipCurrent(streamData.openId, streamData.deviceId, epoch))
1999
+ return;
2000
+ for (const cardId of cardIds) {
2001
+ if (typeof cardId !== 'string' || !cardId)
2002
+ continue;
2003
+ this.cardThreadMap.set(cardId, { threadId: streamData.threadId, deviceId: streamData.deviceId,
2004
+ openId: streamData.openId, epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
2005
+ }
2006
+ }
1832
2007
  async finalizeStreamingMessage(messageId, success, output, error, sessionAbbr, cwd, queueConfirmation, executionMetadata, settingsMenu) {
1833
2008
  const streamData = this.streamingMessages.get(messageId);
1834
2009
  if (!streamData)
@@ -1851,6 +2026,8 @@ class RouterServer {
1851
2026
  streamData.updatePending = false;
1852
2027
  this.clearDelegationProgressTimers(streamData);
1853
2028
  await streamData.updateInFlight;
2029
+ if (!await this.canDispatchStreamOutput(messageId, streamData))
2030
+ return;
1854
2031
  const { feishuMessageId, openId } = streamData;
1855
2032
  if (feishuMessageId) {
1856
2033
  // Flush any remaining text content
@@ -1874,13 +2051,15 @@ class RouterServer {
1874
2051
  const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, prepared.elements, undefined, openId, cwd, streamData.threadName, undefined, streamData.threadId, undefined, undefined, true, { bare: true, onDelivered: cardIds => prepared.deliver(cardIds) });
1875
2052
  if (!finalized) {
1876
2053
  prepared.discard();
2054
+ if (!await this.canDispatchStreamOutput(messageId, streamData))
2055
+ return;
1877
2056
  const delivered = await this.feishuLongConnHandler.sendMessage(openId, output || '⚙️ Settings are unavailable as a card. Use the text command.');
1878
2057
  if (delivered === false)
1879
2058
  throw new Error('Failed to deliver settings result');
1880
2059
  }
1881
2060
  }
1882
2061
  else if (success) {
1883
- const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, streamData.elements, sessionAbbr, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata);
2062
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, streamData.elements, sessionAbbr, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata, true, { onDelivered: cardIds => this.registerDeliveredThreadCards(messageId, streamData, cardIds) });
1884
2063
  if (finalized === false)
1885
2064
  throw new Error('Failed to finalize task card');
1886
2065
  }
@@ -1891,7 +2070,7 @@ class RouterServer {
1891
2070
  const errorMsg = error || 'Command failed';
1892
2071
  finalElements.push((0, ToolFormatter_1.createMarkdownElement)(`\n\n❌ **Error:** ${errorMsg}`));
1893
2072
  }
1894
- const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, finalElements, undefined, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata, false);
2073
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, finalElements, undefined, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata, false, { onDelivered: cardIds => this.registerDeliveredThreadCards(messageId, streamData, cardIds) });
1895
2074
  if (finalized === false)
1896
2075
  throw new Error('Failed to finalize task card');
1897
2076
  }
@@ -1994,7 +2173,25 @@ class RouterServer {
1994
2173
  */
1995
2174
  async stop() {
1996
2175
  console.log('Stopping router server...');
1997
- await this.tips.stop();
2176
+ let firstError;
2177
+ let failed = false;
2178
+ const attempt = async (label, operation) => {
2179
+ try {
2180
+ await operation();
2181
+ }
2182
+ catch (error) {
2183
+ failed = true;
2184
+ firstError ??= error;
2185
+ console.error(`${label}:`, error);
2186
+ }
2187
+ };
2188
+ // Drain accepted binding writes before any slow card or transfer cleanup.
2189
+ // A failure must not skip the remaining resource cleanup or be hidden.
2190
+ for (const pending of this.threadInventoryRequests.values())
2191
+ clearTimeout(pending.timer);
2192
+ this.threadInventoryRequests.clear();
2193
+ await attempt('Error flushing bindings during shutdown', () => this.store.flush());
2194
+ await attempt('Error stopping Tips scheduler', () => this.tips.stop());
1998
2195
  for (const id of this.imageReplies.keys())
1999
2196
  this.cancelImageReply(id);
2000
2197
  this.approvalCards.destroy();
@@ -2004,15 +2201,11 @@ class RouterServer {
2004
2201
  this.settingsConnections.clear();
2005
2202
  this.maintenanceCards.destroy();
2006
2203
  this.maintenanceConnections.clear();
2007
- await this.fileTransfers.destroy();
2008
- // Stop cleanup interval
2204
+ await attempt('Error destroying file transfers', () => this.fileTransfers.destroy());
2009
2205
  if (this.cleanupInterval) {
2010
2206
  clearInterval(this.cleanupInterval);
2011
2207
  this.cleanupInterval = null;
2012
2208
  }
2013
- // Finalize in-flight streaming cards before losing the Feishu connection,
2014
- // so a graceful restart does not leave users with permanently unfinished
2015
- // cards. (A hard crash still cannot do this.)
2016
2209
  for (const [messageId, session] of Array.from(this.streamingMessages.entries())) {
2017
2210
  this.clearDelegationProgressTimers(session);
2018
2211
  if (session.finalizing)
@@ -2021,41 +2214,43 @@ class RouterServer {
2021
2214
  await this.finalizeStreamingMessage(messageId, false, undefined, 'Router server is restarting — task was interrupted.');
2022
2215
  }
2023
2216
  catch (error) {
2217
+ failed = true;
2218
+ firstError ??= error;
2024
2219
  console.error(`[RouterServer] Failed to finalize streaming card ${messageId} during shutdown:`, error);
2025
2220
  }
2026
2221
  }
2027
2222
  this.streamingMessages.clear();
2028
2223
  this.lastStreamUpdateTime.clear();
2029
- // Stop Feishu long connection
2030
- try {
2031
- await this.feishuLongConnHandler.stop();
2032
- }
2033
- catch (error) {
2034
- console.error('Error stopping Feishu long connection:', error);
2035
- }
2036
- // Close all WebSocket connections
2037
- this.connectionHub.closeAllConnections();
2038
- // Close WebSocket server
2224
+ await attempt('Error stopping Feishu long connection', () => this.feishuLongConnHandler.stop());
2225
+ await attempt('Error closing WebSocket connections', () => this.connectionHub.closeAllConnections());
2039
2226
  if (this.wss) {
2040
- this.wss.close();
2227
+ const wss = this.wss;
2041
2228
  this.wss = null;
2229
+ await attempt('Error closing WebSocket server', () => wss.close());
2042
2230
  }
2043
- // Close HTTP server — with a 3s timeout so lingering sockets don't block shutdown
2044
2231
  if (this.httpServer) {
2232
+ const httpServer = this.httpServer;
2233
+ this.httpServer = null;
2045
2234
  await new Promise((resolve) => {
2046
2235
  const timer = setTimeout(() => {
2047
2236
  console.warn('HTTP server close timed out, forcing shutdown');
2237
+ failed = true;
2238
+ firstError ??= new Error('HTTP server close timed out');
2048
2239
  resolve();
2049
2240
  }, 3000);
2050
- this.httpServer.close((err) => {
2241
+ httpServer.close((err) => {
2051
2242
  clearTimeout(timer);
2052
- if (err)
2243
+ if (err) {
2244
+ failed = true;
2245
+ firstError ??= err;
2053
2246
  console.error('HTTP server close error:', err);
2247
+ }
2054
2248
  resolve();
2055
2249
  });
2056
2250
  });
2057
- this.httpServer = null;
2058
2251
  }
2252
+ if (failed)
2253
+ throw firstError;
2059
2254
  console.log('✅ Router server stopped');
2060
2255
  }
2061
2256
  /**