@yu_robotics/remote-cli-router 1.6.187 → 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);
@@ -728,34 +796,46 @@ class RouterServer {
728
796
  : undefined;
729
797
  const settingsMenu = (candidateSettingsMenu?.kind === 'delegation' && !delegationCardsEnabled)
730
798
  || (candidateSettingsMenu?.kind === 'directory' && !directoryCardsEnabled) ? undefined : candidateSettingsMenu;
731
- // If CLI reported a threadId and there is a streaming session for this message,
732
- // ensure the cardThreadMap is up to date (in case the CLI-reported threadId differs).
733
- if (responseThreadId && responseMessageId) {
734
- const session = this.streamingMessages.get(responseMessageId);
735
- if (session) {
736
- if (session.feishuMessageId && session.threadId !== responseThreadId) {
737
- session.threadId = responseThreadId;
738
- 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 });
739
807
  }
740
- // Resolve thread name from the threads summary array
741
808
  if (responseThreads) {
742
809
  const match = responseThreads.find(t => t.id === responseThreadId);
743
810
  if (match)
744
- session.threadName = match.name;
745
- }
746
- // Store full threads list for button rendering
747
- if (responseThreads) {
748
- session.threads = responseThreads;
811
+ responseSession.threadName = match.name;
749
812
  }
750
- // When the "+ New" card button triggered this command, update activeThreadMap
751
- // so the user's next new message routes to the newly created thread.
752
- if (session.pendingNewThread && responseThreadId && responseThreads && responseOpenId) {
753
- const newThread = responseThreads.find(t => t.id === responseThreadId);
754
- if (newThread) {
755
- this.activeThreadMap.set(responseOpenId, { threadId: responseThreadId, threadName: newThread.name });
756
- 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.';
757
826
  }
758
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);
759
839
  }
760
840
  }
761
841
  if (responseMessageId && responseOpenId) {
@@ -781,6 +861,9 @@ class RouterServer {
781
861
  }
782
862
  }
783
863
  }
864
+ if (selectionWarning) {
865
+ await this.feishuLongConnHandler.sendMessage(responseOpenId, selectionWarning);
866
+ }
784
867
  if (taskRecoveryEnabled && deviceId && this.connectionHub.isCurrentConnection(deviceId, ws)
785
868
  && responseOpenId && responseMessageId && !queueConfirmation
786
869
  && typeof (message.success ?? message.data?.success) === 'boolean') {
@@ -987,6 +1070,42 @@ class RouterServer {
987
1070
  return this.streamingMessages.get(messageId) === stream && binding?.openId === stream.openId
988
1071
  && (!current || current());
989
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
+ }
990
1109
  matchesActivityStream(message, deviceId) {
991
1110
  if (!deviceId || typeof message.messageId !== 'string' || typeof message.openId !== 'string'
992
1111
  || typeof message.threadId !== 'string' || !message.threadId)
@@ -1025,7 +1144,7 @@ class RouterServer {
1025
1144
  stream.cwd = cwd;
1026
1145
  if (stream.feishuMessageId) {
1027
1146
  this.cardThreadMap.set(stream.feishuMessageId, {
1028
- 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,
1029
1148
  });
1030
1149
  await this.updateStreamingText(messageId, openId, stream);
1031
1150
  }
@@ -1712,7 +1831,7 @@ class RouterServer {
1712
1831
  previous.lastRenderedTextLength = textLength;
1713
1832
  this.lastStreamUpdateTime.set(messageId, Date.now());
1714
1833
  }
1715
- 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 });
1716
1835
  }
1717
1836
  else {
1718
1837
  const escape = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -1733,7 +1852,7 @@ class RouterServer {
1733
1852
  toolCalls: new Map(),
1734
1853
  recoveryId: info.recoveryId, recoveryPlainText: true, recoveryCwd: info.cwd,
1735
1854
  });
1736
- 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 });
1737
1856
  }
1738
1857
  this.bindImageStream(messageId);
1739
1858
  if (info.state !== 'running') {
@@ -1808,7 +1927,7 @@ class RouterServer {
1808
1927
  this.bindImageStream(messageId);
1809
1928
  if (cardId || fallbackCardId) {
1810
1929
  this.cardThreadMap.set((cardId || fallbackCardId), {
1811
- 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,
1812
1931
  });
1813
1932
  }
1814
1933
  if (cardId) {
@@ -1862,13 +1981,29 @@ class RouterServer {
1862
1981
  const elements = (0, ToolFormatter_1.createTaskNotificationElement)(info, threadLabel);
1863
1982
  const feishuMessageId = await this.feishuLongConnHandler.sendTaskNotificationCard(openId, elements);
1864
1983
  if (feishuMessageId && threadId && deviceId) {
1865
- 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 });
1866
1985
  console.log(`[RouterServer] Registered task notification card ${feishuMessageId} for thread ${threadId}`);
1867
1986
  }
1868
1987
  }
1869
1988
  /**
1870
1989
  * Finalize streaming message
1871
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
+ }
1872
2007
  async finalizeStreamingMessage(messageId, success, output, error, sessionAbbr, cwd, queueConfirmation, executionMetadata, settingsMenu) {
1873
2008
  const streamData = this.streamingMessages.get(messageId);
1874
2009
  if (!streamData)
@@ -1924,7 +2059,7 @@ class RouterServer {
1924
2059
  }
1925
2060
  }
1926
2061
  else if (success) {
1927
- 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) });
1928
2063
  if (finalized === false)
1929
2064
  throw new Error('Failed to finalize task card');
1930
2065
  }
@@ -1935,7 +2070,7 @@ class RouterServer {
1935
2070
  const errorMsg = error || 'Command failed';
1936
2071
  finalElements.push((0, ToolFormatter_1.createMarkdownElement)(`\n\nāŒ **Error:** ${errorMsg}`));
1937
2072
  }
1938
- 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) });
1939
2074
  if (finalized === false)
1940
2075
  throw new Error('Failed to finalize task card');
1941
2076
  }
@@ -2052,6 +2187,9 @@ class RouterServer {
2052
2187
  };
2053
2188
  // Drain accepted binding writes before any slow card or transfer cleanup.
2054
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();
2055
2193
  await attempt('Error flushing bindings during shutdown', () => this.store.flush());
2056
2194
  await attempt('Error stopping Tips scheduler', () => this.tips.stop());
2057
2195
  for (const id of this.imageReplies.keys())