@yu_robotics/remote-cli-router 1.6.216 → 1.6.219

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
@@ -25,6 +25,7 @@ const koa_1 = __importDefault(require("koa"));
25
25
  const koa_bodyparser_1 = __importDefault(require("koa-bodyparser"));
26
26
  const router_1 = __importDefault(require("@koa/router"));
27
27
  const ws_1 = require("ws");
28
+ const CardThreadState_1 = require("./storage/CardThreadState");
28
29
  const FeishuLongConnHandler_1 = require("./feishu/FeishuLongConnHandler");
29
30
  const ConnectionHub_1 = require("./websocket/ConnectionHub");
30
31
  const BindingManager_1 = require("./binding/BindingManager");
@@ -72,12 +73,7 @@ class RouterServer {
72
73
  imageReplies = new Map();
73
74
  STREAMING_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes timeout
74
75
  DELEGATION_PROGRESS_HEARTBEAT_MS = 30 * 1000;
75
- // TTL for cardThreadMap entries: 7 days (allows users to reply to old cards)
76
- CARD_THREAD_MAP_TTL_MS = 7 * 24 * 60 * 60 * 1000;
77
- // Map from Feishu card message_id to threadId for parent_id-based routing.
78
- // Entries are NOT removed on finalize so users can reply to completed cards.
79
- // Each entry carries an expiresAt timestamp for TTL-based eviction.
80
- cardThreadMap = new Map();
76
+ CARD_THREAD_MAP_TTL_MS = CardThreadState_1.CARD_THREAD_TTL_MS;
81
77
  selections;
82
78
  threadInventoryRequests = new Map();
83
79
  deviceAuth;
@@ -152,18 +148,18 @@ class RouterServer {
152
148
  this.feishuLongConnHandler.onApproveDeviceKey = async (openId, deviceId, publicKey) => {
153
149
  if ((await this.bindingManager.getDeviceBinding(deviceId))?.openId !== openId)
154
150
  throw new Error('Device ownership changed.');
151
+ await this.selections.invalidateDevice(openId, deviceId);
155
152
  await this.deviceAuth.enroll(deviceId, openId, publicKey);
156
- this.selections.invalidateDevice(openId, deviceId);
157
- this.expireDeviceCards(deviceId);
153
+ this.cancelThreadInventories(deviceId);
158
154
  this.connectionHub.disconnectDevice(deviceId);
159
155
  this.fileTransfers.disconnect(deviceId);
160
156
  };
161
157
  this.feishuLongConnHandler.onRevokeDevice = async (deviceId) => {
162
158
  const owner = await this.bindingManager.getDeviceBinding(deviceId);
163
159
  if (owner?.openId)
164
- this.selections.invalidateDevice(owner.openId, deviceId);
165
- this.expireDeviceCards(deviceId);
160
+ await this.selections.invalidateDevice(owner.openId, deviceId);
166
161
  await this.deviceAuth.revoke(deviceId);
162
+ this.cancelThreadInventories(deviceId);
167
163
  this.connectionHub.disconnectDevice(deviceId);
168
164
  this.fileTransfers.disconnect(deviceId);
169
165
  };
@@ -172,8 +168,12 @@ class RouterServer {
172
168
  sendToDevice: (deviceId, message) => this.connectionHub.sendToDevice(deviceId, message),
173
169
  create: (openId, elements, header) => this.feishuLongConnHandler.sendTaskNotificationCard(openId, elements, header),
174
170
  update: (cardId, elements, header) => this.feishuLongConnHandler.updateApprovalCard(cardId, elements, header),
175
- registerReplyRoute: (cardId, threadId, deviceId, openId) => {
176
- this.cardThreadMap.set(cardId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
171
+ registerReplyRoute: async (cardId, threadId, deviceId, openId, current) => {
172
+ await this.registerCardThread(cardId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, current);
173
+ },
174
+ captureReplyRoute: (openId, deviceId) => {
175
+ const fence = this.selections.capture(openId, deviceId);
176
+ return () => this.selections.isOwnershipCurrent(openId, deviceId, fence.epoch);
177
177
  },
178
178
  });
179
179
  this.feishuLongConnHandler.onApprovalAction = (openId, requestId, cardId, decision) => this.approvalCards.click(openId, requestId, cardId, decision);
@@ -207,7 +207,7 @@ class RouterServer {
207
207
  // Register callback for streaming message start
208
208
  this.feishuLongConnHandler.setOnCaptureSelection((openId, deviceId) => this.selections.capture(openId, deviceId));
209
209
  this.feishuLongConnHandler.setOnValidateSelection(fence => this.selections.isCurrent(fence));
210
- this.feishuLongConnHandler.setOnStartStreaming((messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName, selectionIntent) => {
210
+ this.feishuLongConnHandler.setOnStartStreaming(async (messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName, selectionIntent) => {
211
211
  console.log(`[RouterServer] Registering streaming session: msgId=${messageId}, feishuMsgId=${feishuMessageId}, deviceId=${deviceId}, threadId=${threadId}, pendingNewThread=${pendingNewThread}`);
212
212
  this.cancelImageReply(messageId);
213
213
  const previous = this.streamingMessages.get(messageId);
@@ -233,9 +233,9 @@ class RouterServer {
233
233
  delegationProgress: new Map(),
234
234
  toolCalls: new Map(),
235
235
  });
236
- // Populate cardThreadMap for parent_id-based routing
236
+ // Populate card associations for parent_id-based routing
237
237
  if (feishuMessageId && threadId) {
238
- 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 });
238
+ await this.registerCardThread(feishuMessageId, { threadId, deviceId, openId, epoch: selectionIntent?.epoch ?? this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, () => this.streamingMessages.get(messageId)?.feishuMessageId === feishuMessageId);
239
239
  }
240
240
  console.log(`[RouterServer] Total streaming sessions: ${this.streamingMessages.size}`);
241
241
  });
@@ -248,6 +248,10 @@ class RouterServer {
248
248
  return this.selections.resolve(openId, deviceId);
249
249
  });
250
250
  this.feishuLongConnHandler.onRecoverThreads = async (openId, deviceId) => {
251
+ if (this.stopping || this.threadInventoryRequests.size >= 100) {
252
+ await this.feishuLongConnHandler.sendMessage(openId, 'Thread controls are busy. Retry shortly.');
253
+ return true;
254
+ }
251
255
  const messageId = (0, crypto_1.randomUUID)();
252
256
  const fence = this.selections.beginIntent(openId, deviceId);
253
257
  const timer = setTimeout(() => {
@@ -266,20 +270,35 @@ class RouterServer {
266
270
  return true;
267
271
  };
268
272
  // Register callback for card button thread switching
269
- this.feishuLongConnHandler.onCardSwitchThread = async (openId, cardId, threadId, threadName) => {
273
+ this.feishuLongConnHandler.onCardSwitchThread = async (openId, cardId, threadId) => {
270
274
  const revision = this.selections.reserveIntent(openId);
271
275
  const source = await this.requireCurrentCardDevice(cardId, openId);
272
- const intent = this.selections.intent(openId, source.deviceId, revision);
273
- const selected = await this.selections.select(openId, source.deviceId, threadId, threadName, intent);
274
- if (selected !== 'selected')
275
- throw new Error('This selection was superseded or the device changed. Use a fresh thread card.');
276
- console.log(`[RouterServer] Durable thread selection saved for ${openId}: ${threadName} (${threadId})`);
276
+ const fence = { ...this.selections.intent(openId, source.deviceId, revision), epoch: source.epoch };
277
+ if (!this.selections.isCurrent(fence))
278
+ throw new Error('This selection was superseded. Use a fresh thread card.');
279
+ if (typeof threadId !== 'string' || !threadId || threadId.length > 200)
280
+ throw new Error('Invalid target thread.');
281
+ if (this.stopping || this.threadInventoryRequests.size >= 100)
282
+ throw new Error('Thread controls are busy. Retry shortly.');
283
+ const messageId = (0, crypto_1.randomUUID)();
284
+ return new Promise((resolve, reject) => {
285
+ const fail = () => {
286
+ this.cancelThreadInventory(messageId, new Error('Could not verify the target thread. Reconnect the device and retry /thread list.'));
287
+ };
288
+ const timer = setTimeout(fail, 2000);
289
+ timer.unref?.();
290
+ this.threadInventoryRequests.set(messageId, { openId, deviceId: source.deviceId, fence, timer,
291
+ selection: { cardId, threadId, resolve, reject } });
292
+ void this.connectionHub.sendToDevice(source.deviceId, { type: 'status', messageId, timestamp: Date.now() })
293
+ .then(sent => { if (!sent)
294
+ fail(); }, fail);
295
+ });
277
296
  };
278
297
  // Register callback for creating a new thread via card button
279
298
  this.feishuLongConnHandler.onCardNewThread = async (openId, cardId) => {
280
299
  const revision = this.selections.reserveIntent(openId);
281
300
  const source = await this.requireCurrentCardDevice(cardId, openId);
282
- const intent = this.selections.intent(openId, source.deviceId, revision);
301
+ const intent = { ...this.selections.intent(openId, source.deviceId, revision), epoch: source.epoch };
283
302
  console.log(`[RouterServer] Creating new thread for ${openId} via card button`);
284
303
  await this.feishuLongConnHandler.sendCommandFromCardAction(openId, '/thread new', true, source.deviceId, intent);
285
304
  };
@@ -289,52 +308,38 @@ class RouterServer {
289
308
  this.feishuLongConnHandler.onDeviceSwitchIntent = (openId, newDeviceId) => {
290
309
  this.selections.beginIntent(openId, newDeviceId);
291
310
  };
292
- // Device switches retain independent durable selections and invalidate older intents.
293
- this.feishuLongConnHandler.onDeviceSwitch = (openId, oldDeviceId, newDeviceId) => {
294
- if (oldDeviceId) {
295
- for (const [feishuMessageId, entry] of this.cardThreadMap.entries()) {
296
- if (entry.deviceId === oldDeviceId)
297
- this.cardThreadMap.delete(feishuMessageId);
298
- }
299
- console.log(`[RouterServer] Cleared cardThreadMap entries for old device ${oldDeviceId}`);
300
- }
301
- };
311
+ // JsonStore invalidates both devices atomically with the binding switch. Do not
312
+ // invalidate again in an asynchronous notification: a later switch may have won.
302
313
  this.setupMiddleware();
303
314
  this.setupRoutes();
304
315
  }
305
- expireDeviceCards(deviceId) {
306
- for (const [cardId, entry] of this.cardThreadMap) {
307
- if (entry.deviceId === deviceId)
308
- this.cardThreadMap.delete(cardId);
309
- }
316
+ async registerCardThread(cardId, entry, current = () => true) {
317
+ await this.store.setCardThread(cardId, entry, () => current()
318
+ && this.selections.isOwnershipCurrent(entry.openId, entry.deviceId, entry.epoch));
310
319
  }
311
320
  async resolveCardThread(cardId, openId) {
312
- const entry = this.cardThreadMap.get(cardId);
321
+ const entry = this.store.getCardThread(cardId);
313
322
  if (!entry)
314
323
  return undefined;
315
- if (Date.now() > entry.expiresAt) {
316
- this.cardThreadMap.delete(cardId);
317
- return undefined;
318
- }
319
324
  if (entry.openId !== openId || !this.selections.isOwnershipCurrent(openId, entry.deviceId, entry.epoch))
320
325
  return undefined;
321
326
  if ((await this.bindingManager.getDeviceBinding(entry.deviceId))?.openId !== openId
322
- || this.cardThreadMap.get(cardId) !== entry
327
+ || this.store.getCardThread(cardId) !== entry
323
328
  || !this.selections.isOwnershipCurrent(openId, entry.deviceId, entry.epoch))
324
329
  return undefined;
325
330
  return { threadId: entry.threadId, deviceId: entry.deviceId };
326
331
  }
327
332
  async requireCurrentCardDevice(cardId, openId) {
328
- const entry = this.cardThreadMap.get(cardId);
333
+ const entry = this.store.getCardThread(cardId);
329
334
  const source = await this.resolveCardThread(cardId, openId);
330
335
  if (!source)
331
336
  throw new Error('This thread card has expired. Run /thread list for a fresh card.');
332
337
  const active = await this.bindingManager.getActiveDevice(openId);
333
- if (!active || active.deviceId !== source.deviceId || !entry || this.cardThreadMap.get(cardId) !== entry
338
+ if (!active || active.deviceId !== source.deviceId || !entry || this.store.getCardThread(cardId) !== entry
334
339
  || !this.selections.isOwnershipCurrent(openId, entry.deviceId, entry.epoch)) {
335
340
  throw new Error('This card belongs to a different device. Switch back to that device or use a fresh card.');
336
341
  }
337
- return source;
342
+ return { ...source, epoch: entry.epoch };
338
343
  }
339
344
  /**
340
345
  * Setup Koa middleware
@@ -757,6 +762,8 @@ class RouterServer {
757
762
  this.approvalCards.disconnect(deviceId);
758
763
  this.maintenanceCards.disconnect(deviceId);
759
764
  this.settingsCards.disconnect(deviceId);
765
+ if (!this.connectionHub.isCurrentConnection(deviceId, ws))
766
+ this.cancelThreadInventories(deviceId);
760
767
  if (message.data.capabilities?.queueStarted === true) {
761
768
  this.connectionHub.registerConnection(deviceId, ws, { queueStarted: true });
762
769
  }
@@ -871,7 +878,7 @@ class RouterServer {
871
878
  if (responseThreadId) {
872
879
  if (responseSession.feishuMessageId && responseSession.threadId !== responseThreadId) {
873
880
  responseSession.threadId = responseThreadId;
874
- 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 });
881
+ await this.registerCardThread(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 }, () => this.streamingMessages.get(responseMessageId) === responseSession && imageCurrent());
875
882
  }
876
883
  if (responseThreads) {
877
884
  const match = responseThreads.find(t => t.id === responseThreadId);
@@ -1016,7 +1023,7 @@ class RouterServer {
1016
1023
  // Background task terminal-state event (Claude Code 2.x).
1017
1024
  // Not tied to any streaming session — rendered as a standalone card.
1018
1025
  if (message.openId && message.taskNotification) {
1019
- await this.handleTaskNotification(message.openId, message.taskNotification, message.threadId, deviceId, message.threadName);
1026
+ await this.handleTaskNotification(message.openId, message.taskNotification, message.threadId, deviceId, message.threadName, imageCurrent);
1020
1027
  }
1021
1028
  else {
1022
1029
  console.log('[RouterServer] Ignoring task_notification with missing openId or payload');
@@ -1063,7 +1070,7 @@ class RouterServer {
1063
1070
  this.settingsConnections.delete(deviceId);
1064
1071
  this.maintenanceConnections.delete(deviceId);
1065
1072
  this.workerContextConnections.delete(deviceId);
1066
- this.cleanupStreamingSessionsForDevice(deviceId);
1073
+ void this.cleanupStreamingSessionsForDevice(deviceId).catch(() => console.error('Failed to expire disconnected streaming cards.'));
1067
1074
  console.log('Device disconnected:', deviceId);
1068
1075
  }
1069
1076
  });
@@ -1113,7 +1120,7 @@ class RouterServer {
1113
1120
  // Cleanup connections that haven't sent heartbeat in 3x interval
1114
1121
  this.connectionHub.cleanupStaleConnections(heartbeatInterval * 3);
1115
1122
  // Cleanup stale streaming sessions
1116
- this.cleanupStaleStreamingSessions();
1123
+ void this.cleanupStaleStreamingSessions().catch(() => console.error('Failed to expire stale streaming cards.'));
1117
1124
  }, heartbeatInterval);
1118
1125
  console.log(`\n🚀 Router server started successfully!`);
1119
1126
  console.log(` HTTP: http://${host}:${port}`);
@@ -1161,40 +1168,124 @@ class RouterServer {
1161
1168
  return this.streamingMessages.get(messageId) === stream && binding?.openId === stream.openId
1162
1169
  && (!current || current());
1163
1170
  }
1164
- async handleThreadInventoryResponse(message, deviceId, ws) {
1165
- const pending = this.threadInventoryRequests.get(message.messageId);
1171
+ /** Cancellation is definitive only before the storage FIFO admits the guarded draft. */
1172
+ cancelThreadInventory(id, error) {
1173
+ const pending = this.threadInventoryRequests.get(id);
1166
1174
  if (!pending)
1167
1175
  return;
1168
- const current = () => deviceId === pending.deviceId && this.connectionHub.isCurrentConnection(pending.deviceId, ws)
1169
- && this.selections.isCurrent(pending.fence);
1170
- if (!current())
1171
- return;
1172
- const binding = await this.bindingManager.getDeviceBinding(pending.deviceId);
1173
- if (!current() || binding?.openId !== pending.openId)
1174
- return;
1175
1176
  clearTimeout(pending.timer);
1176
- this.threadInventoryRequests.delete(message.messageId);
1177
- const threads = message.status?.threads;
1178
- if (!(0, ThreadSelectionManager_1.isCompleteThreadCatalog)(threads)) {
1179
- await this.feishuLongConnHandler.sendMessage(pending.openId, 'The device returned an invalid thread inventory. Retry /thread list.');
1177
+ if (pending.selection?.commitAdmitted) {
1178
+ pending.selection.acknowledgedPending = true;
1179
+ pending.selection.resolve({ notice: 'The thread selection is still being saved. Do not retry; wait for confirmation or check /thread list after Router recovery.' });
1180
+ // Retain the bounded request slot and its completion handler until I/O settles.
1180
1181
  return;
1181
1182
  }
1182
- const defaultThread = threads.find((thread) => thread.name === 'default');
1183
+ this.threadInventoryRequests.delete(id);
1184
+ pending.selection?.reject(error);
1185
+ }
1186
+ cancelThreadInventories(deviceId) {
1187
+ for (const [id, pending] of this.threadInventoryRequests) {
1188
+ if (pending.deviceId === deviceId)
1189
+ this.cancelThreadInventory(id, new Error('Device connection changed. Retry /thread list.'));
1190
+ }
1191
+ }
1192
+ async sendSelectionOutcome(openId, message) {
1193
+ try {
1194
+ await this.feishuLongConnHandler.sendMessage(openId, message);
1195
+ }
1196
+ catch {
1197
+ console.error('Could not deliver the thread selection outcome notice.');
1198
+ }
1199
+ }
1200
+ async handleThreadInventoryResponse(message, deviceId, ws) {
1201
+ const pending = this.threadInventoryRequests.get(message.messageId);
1202
+ if (!pending || pending.processing || deviceId !== pending.deviceId
1203
+ || !this.connectionHub.isCurrentConnection(pending.deviceId, ws))
1204
+ return;
1205
+ pending.processing = true;
1206
+ const current = () => !this.stopping && this.threadInventoryRequests.get(message.messageId) === pending
1207
+ && this.connectionHub.isCurrentConnection(pending.deviceId, ws) && this.selections.isCurrent(pending.fence);
1183
1208
  try {
1184
- const reconciled = await this.selections.observeCatalog(pending.openId, pending.deviceId, pending.fence, threads, current);
1185
- if (reconciled === 'stale' || reconciled === 'failed' || !current())
1209
+ if (pending.selection) {
1210
+ const { selection } = pending;
1211
+ try {
1212
+ if (!current())
1213
+ throw new Error('This selection was superseded or the device changed.');
1214
+ await this.requireCurrentCardDevice(selection.cardId, pending.openId);
1215
+ const entry = this.store.getCardThread(selection.cardId);
1216
+ const threads = message.status?.threads;
1217
+ if (!(0, ThreadSelectionManager_1.isCompleteThreadCatalog)(threads))
1218
+ throw new Error('The device returned an invalid thread inventory. Retry /thread list.');
1219
+ const target = threads.find(thread => thread.id === selection.threadId);
1220
+ if (!target) {
1221
+ await this.selections.observeCatalog(pending.openId, pending.deviceId, pending.fence, threads, current);
1222
+ throw new Error('This thread no longer exists. Run /thread list for a fresh card.');
1223
+ }
1224
+ const selected = await this.selections.select(pending.openId, pending.deviceId, target.id, target.name, pending.fence, () => current() && !!entry && this.store.getCardThread(selection.cardId) === entry, () => { selection.commitAdmitted = true; });
1225
+ // A stale post-write guard cannot undo a committed snapshot. Report the
1226
+ // historical save without claiming it is still the user's active choice.
1227
+ if (selection.commitAdmitted) {
1228
+ const notice = `Thread preference was saved: ${target.name}. Check /thread list before sending work if the connection or selection changed.`;
1229
+ if (selection.acknowledgedPending)
1230
+ await this.sendSelectionOutcome(pending.openId, notice);
1231
+ else if (selected !== 'selected' || !current())
1232
+ selection.resolve({ notice });
1233
+ else
1234
+ selection.resolve(target.name);
1235
+ }
1236
+ else {
1237
+ if (selected !== 'selected')
1238
+ throw new Error('This selection was superseded or the device changed.');
1239
+ selection.resolve(target.name);
1240
+ }
1241
+ }
1242
+ catch (error) {
1243
+ if (selection.acknowledgedPending)
1244
+ await this.sendSelectionOutcome(pending.openId, 'The thread selection could not be confirmed durably. Do not assume it changed or remained unchanged. Check /thread list after Router storage recovers; no action was replayed.');
1245
+ else
1246
+ selection.reject(error instanceof Error ? error : new Error('Could not save the thread selection.'));
1247
+ }
1248
+ return;
1249
+ }
1250
+ if (!current())
1186
1251
  return;
1187
- const cardId = await this.feishuLongConnHandler.sendStreamingStart(pending.openId, '🗂️ Thread controls refreshed. Choose a thread for future top-level messages.');
1188
- if (!cardId || !current())
1252
+ const binding = await this.bindingManager.getDeviceBinding(pending.deviceId);
1253
+ if (!current() || binding?.openId !== pending.openId)
1189
1254
  return;
1190
- const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(cardId, [], undefined, pending.openId, undefined, 'Thread selection', threads, defaultThread.id);
1191
- if (!finalized || !current())
1255
+ const threads = message.status?.threads;
1256
+ if (!(0, ThreadSelectionManager_1.isCompleteThreadCatalog)(threads)) {
1257
+ await this.feishuLongConnHandler.sendMessage(pending.openId, 'The device returned an invalid thread inventory. Retry /thread list.');
1192
1258
  return;
1193
- this.cardThreadMap.set(cardId, { threadId: defaultThread.id, deviceId: pending.deviceId,
1194
- openId: pending.openId, epoch: pending.fence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1259
+ }
1260
+ const defaultThread = threads.find((thread) => thread.name === 'default');
1261
+ try {
1262
+ const reconciled = await this.selections.observeCatalog(pending.openId, pending.deviceId, pending.fence, threads, current);
1263
+ if (reconciled === 'stale' || reconciled === 'failed' || !current())
1264
+ return;
1265
+ const cardId = await this.feishuLongConnHandler.sendStreamingStart(pending.openId, '🗂️ Thread controls refreshed. Choose a thread for future top-level messages.');
1266
+ if (!cardId || !current())
1267
+ return;
1268
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(cardId, [], undefined, pending.openId, undefined, 'Thread selection', threads, defaultThread.id, undefined, undefined, true, { onDelivered: async (cardIds) => {
1269
+ for (const deliveredId of cardIds)
1270
+ await this.registerCardThread(deliveredId, {
1271
+ threadId: defaultThread.id, deviceId: pending.deviceId, openId: pending.openId,
1272
+ epoch: pending.fence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
1273
+ }, current);
1274
+ } });
1275
+ if (!finalized || !current())
1276
+ return;
1277
+ await this.registerCardThread(cardId, { threadId: defaultThread.id, deviceId: pending.deviceId,
1278
+ openId: pending.openId, epoch: pending.fence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, current);
1279
+ }
1280
+ catch {
1281
+ if (current())
1282
+ await this.feishuLongConnHandler.sendMessage(pending.openId, 'Could not create thread controls. Retry /thread list.');
1283
+ }
1195
1284
  }
1196
- catch {
1197
- await this.feishuLongConnHandler.sendMessage(pending.openId, 'Could not create thread controls. Retry /thread list.');
1285
+ finally {
1286
+ clearTimeout(pending.timer);
1287
+ if (this.threadInventoryRequests.get(message.messageId) === pending)
1288
+ this.threadInventoryRequests.delete(message.messageId);
1198
1289
  }
1199
1290
  }
1200
1291
  matchesActivityStream(message, deviceId) {
@@ -1234,9 +1325,9 @@ class RouterServer {
1234
1325
  stream.threadName = threadName;
1235
1326
  stream.cwd = cwd;
1236
1327
  if (stream.feishuMessageId) {
1237
- this.cardThreadMap.set(stream.feishuMessageId, {
1328
+ await this.registerCardThread(stream.feishuMessageId, {
1238
1329
  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,
1239
- });
1330
+ }, () => this.streamingMessages.get(messageId) === stream);
1240
1331
  await this.updateStreamingText(messageId, openId, stream);
1241
1332
  }
1242
1333
  }
@@ -1878,6 +1969,7 @@ class RouterServer {
1878
1969
  return false;
1879
1970
  if (this.isCompletedTask(messageId, deviceId))
1880
1971
  return true;
1972
+ const selectionFence = this.selections.capture(openId, deviceId);
1881
1973
  const previous = this.streamingMessages.get(messageId);
1882
1974
  if (previous && (previous.deviceId !== deviceId || previous.openId !== openId
1883
1975
  || (previous.threadId && previous.threadId !== threadId)))
@@ -1922,7 +2014,7 @@ class RouterServer {
1922
2014
  previous.lastRenderedTextLength = textLength;
1923
2015
  this.lastStreamUpdateTime.set(messageId, Date.now());
1924
2016
  }
1925
- 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 });
2017
+ await this.registerCardThread(previous.feishuMessageId, { threadId, deviceId, openId, epoch: previous.selectionFence?.epoch ?? this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, () => isCurrent() && this.streamingMessages.get(messageId) === previous);
1926
2018
  }
1927
2019
  else {
1928
2020
  const escape = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -1941,9 +2033,9 @@ class RouterServer {
1941
2033
  createdAt: Date.now(), updatePending: false, finalizing: false, lastRenderedTextLength: 0,
1942
2034
  delegationProgress: new Map(),
1943
2035
  toolCalls: new Map(),
1944
- recoveryId: info.recoveryId, recoveryPlainText: true, recoveryCwd: info.cwd,
2036
+ recoveryId: info.recoveryId, recoveryPlainText: true, recoveryCwd: info.cwd, selectionFence,
1945
2037
  });
1946
- this.cardThreadMap.set(cardId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
2038
+ await this.registerCardThread(cardId, { threadId, deviceId, openId, epoch: selectionFence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, isCurrent);
1947
2039
  }
1948
2040
  this.bindImageStream(messageId);
1949
2041
  if (info.state !== 'running') {
@@ -1964,6 +2056,7 @@ class RouterServer {
1964
2056
  || typeof info.cwd !== 'string' || typeof info.preview !== 'string'
1965
2057
  || !Number.isInteger(info.remainingCount) || info.remainingCount < 0)
1966
2058
  return;
2059
+ const selectionFence = this.selections.capture(openId, deviceId);
1967
2060
  const previous = this.streamingMessages.get(messageId);
1968
2061
  if (previous && (previous.deviceId !== deviceId || previous.openId !== openId
1969
2062
  || (previous.threadId && previous.threadId !== threadId)))
@@ -2013,13 +2106,14 @@ class RouterServer {
2013
2106
  delegationProgress: new Map(),
2014
2107
  toolCalls: new Map(),
2015
2108
  queueStarted: info,
2109
+ selectionFence,
2016
2110
  threads: Array.isArray(message.threads) ? message.threads : undefined,
2017
2111
  });
2018
2112
  this.bindImageStream(messageId);
2019
2113
  if (cardId || fallbackCardId) {
2020
- this.cardThreadMap.set((cardId || fallbackCardId), {
2021
- threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
2022
- });
2114
+ await this.registerCardThread((cardId || fallbackCardId), {
2115
+ threadId, deviceId, openId, epoch: selectionFence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS,
2116
+ }, isCurrent);
2023
2117
  }
2024
2118
  if (cardId) {
2025
2119
  const oldCards = new Set([previous?.queueCardId, previous?.feishuMessageId]);
@@ -2054,10 +2148,10 @@ class RouterServer {
2054
2148
  * Sent as a standalone one-shot card — the event may arrive while no
2055
2149
  * streaming session exists (the originating command's card is often
2056
2150
  * already finalized), so it deliberately never touches streamingMessages.
2057
- * The new card is registered in cardThreadMap so the user can reply to it
2151
+ * The new card has a durable association so the user can reply to it
2058
2152
  * to continue working in the originating thread.
2059
2153
  */
2060
- async handleTaskNotification(openId, info, threadId, deviceId, threadName) {
2154
+ async handleTaskNotification(openId, info, threadId, deviceId, threadName, current = () => true) {
2061
2155
  // Boundary validation — the WS message is external data, never trust it.
2062
2156
  // Required for rendering: a non-empty taskId and a string summary.
2063
2157
  // Unknown status values are allowed through (forward compatibility);
@@ -2069,17 +2163,18 @@ class RouterServer {
2069
2163
  console.log(`[RouterServer] Task notification for ${openId}: task=${info.taskId} status=${info.status} thread=${threadId || 'default'}`);
2070
2164
  const threadLabel = typeof threadName === 'string' && threadName.trim()
2071
2165
  ? threadName : typeof threadId === 'string' && threadId.trim() ? threadId : undefined;
2166
+ const selectionFence = deviceId ? this.selections.capture(openId, deviceId) : undefined;
2072
2167
  const elements = (0, ToolFormatter_1.createTaskNotificationElement)(info, threadLabel);
2073
2168
  const feishuMessageId = await this.feishuLongConnHandler.sendTaskNotificationCard(openId, elements);
2074
- if (feishuMessageId && threadId && deviceId) {
2075
- this.cardThreadMap.set(feishuMessageId, { threadId, deviceId, openId, epoch: this.selections.capture(openId, deviceId).epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
2169
+ if (feishuMessageId && threadId && deviceId && selectionFence) {
2170
+ await this.registerCardThread(feishuMessageId, { threadId, deviceId, openId, epoch: selectionFence.epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, current);
2076
2171
  console.log(`[RouterServer] Registered task notification card ${feishuMessageId} for thread ${threadId}`);
2077
2172
  }
2078
2173
  }
2079
2174
  /**
2080
2175
  * Finalize streaming message
2081
2176
  */
2082
- registerDeliveredThreadCards(messageId, streamData, cardIds) {
2177
+ async registerDeliveredThreadCards(messageId, streamData, cardIds) {
2083
2178
  if (!streamData.threadId || this.streamingMessages.get(messageId) !== streamData)
2084
2179
  return;
2085
2180
  const fence = streamData.selectionFence;
@@ -2088,11 +2183,14 @@ class RouterServer {
2088
2183
  const epoch = fence?.epoch ?? this.selections.capture(streamData.openId, streamData.deviceId).epoch;
2089
2184
  if (!this.selections.isOwnershipCurrent(streamData.openId, streamData.deviceId, epoch))
2090
2185
  return;
2091
- for (const cardId of cardIds) {
2092
- if (typeof cardId !== 'string' || !cardId)
2093
- continue;
2094
- this.cardThreadMap.set(cardId, { threadId: streamData.threadId, deviceId: streamData.deviceId,
2095
- openId: streamData.openId, epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
2186
+ const delivered = cardIds.filter(id => typeof id === 'string' && id.length > 0);
2187
+ streamData.deliveredCardIds ??= new Set();
2188
+ // Track the whole batch before disk I/O so interruption revokes pending writes too.
2189
+ for (const cardId of delivered)
2190
+ streamData.deliveredCardIds.add(cardId);
2191
+ for (const cardId of delivered) {
2192
+ await this.registerCardThread(cardId, { threadId: streamData.threadId, deviceId: streamData.deviceId,
2193
+ openId: streamData.openId, epoch, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS }, () => this.streamingMessages.get(messageId) === streamData && (!streamData.currentConnection || streamData.currentConnection()));
2096
2194
  }
2097
2195
  }
2098
2196
  async finalizeStreamingMessage(messageId, success, output, error, sessionAbbr, cwd, queueConfirmation, executionMetadata, settingsMenu) {
@@ -2179,20 +2277,23 @@ class RouterServer {
2179
2277
  if (delivered === false)
2180
2278
  throw new Error('Failed to deliver task result');
2181
2279
  }
2182
- // Clean up streaming session state (but NOT cardThreadMap — keep it alive
2183
- // so users can reply to the completed card and route to the same thread).
2280
+ // Keep durable card associations after removing the completed streaming session.
2184
2281
  if (this.streamingMessages.get(messageId) === streamData) {
2185
2282
  this.streamingMessages.delete(messageId);
2186
2283
  this.lastStreamUpdateTime.delete(messageId);
2187
2284
  }
2188
2285
  }
2189
- /**
2190
- * Cleanup stale streaming sessions that have timed out
2191
- * This prevents memory leaks when devices disconnect without sending a response
2192
- */
2193
- cleanupStaleStreamingSessions() {
2286
+ removeActiveCardRoutes(session) {
2287
+ const ids = new Set(session.deliveredCardIds);
2288
+ if (session.feishuMessageId)
2289
+ ids.add(session.feishuMessageId);
2290
+ return [...ids].map(id => this.store.removeCardThread(id));
2291
+ }
2292
+ /** Clean up timed-out executions without discarding completed card routes. */
2293
+ async cleanupStaleStreamingSessions() {
2194
2294
  const now = Date.now();
2195
2295
  let cleanedCount = 0;
2296
+ const removals = [];
2196
2297
  for (const [messageId, route] of this.imageReplies) {
2197
2298
  if (!route.current() || (!this.streamingMessages.has(messageId)
2198
2299
  && now - route.createdAt > this.STREAMING_SESSION_TIMEOUT_MS))
@@ -2201,14 +2302,12 @@ class RouterServer {
2201
2302
  for (const [messageId, session] of this.streamingMessages.entries()) {
2202
2303
  if (now - session.createdAt > this.STREAMING_SESSION_TIMEOUT_MS) {
2203
2304
  console.log(`[RouterServer] Cleaning up stale streaming session: ${messageId}`);
2204
- // Stale in-flight sessions have their cardThreadMap entry removed;
2305
+ // Stale in-flight sessions lose their card association;
2205
2306
  // completed sessions deliberately keep theirs (see finalizeStreamingMessage).
2206
- if (session.feishuMessageId) {
2207
- this.cardThreadMap.delete(session.feishuMessageId);
2208
- }
2307
+ this.streamingMessages.delete(messageId);
2308
+ removals.push(...this.removeActiveCardRoutes(session));
2209
2309
  this.clearDelegationProgressTimers(session);
2210
2310
  this.cancelImageReply(messageId);
2211
- this.streamingMessages.delete(messageId);
2212
2311
  this.lastStreamUpdateTime.delete(messageId);
2213
2312
  cleanedCount++;
2214
2313
  }
@@ -2218,12 +2317,11 @@ class RouterServer {
2218
2317
  this.startedQueueMessages.delete(messageId);
2219
2318
  }
2220
2319
  }
2221
- // Evict expired cardThreadMap entries (TTL-based, independent of streaming sessions)
2222
- for (const [feishuMessageId, entry] of this.cardThreadMap.entries()) {
2223
- if (now > entry.expiresAt) {
2224
- this.cardThreadMap.delete(feishuMessageId);
2225
- }
2226
- }
2320
+ const results = await Promise.allSettled(removals);
2321
+ await this.store.pruneCardThreads();
2322
+ const failed = results.find(result => result.status === 'rejected');
2323
+ if (failed?.status === 'rejected')
2324
+ throw failed.reason;
2227
2325
  if (cleanedCount > 0) {
2228
2326
  console.log(`[RouterServer] Cleaned up ${cleanedCount} stale streaming sessions, remaining: ${this.streamingMessages.size}`);
2229
2327
  }
@@ -2232,29 +2330,28 @@ class RouterServer {
2232
2330
  * Cleanup streaming sessions for a specific device when it disconnects
2233
2331
  * @param deviceId Device ID that disconnected
2234
2332
  */
2235
- cleanupStreamingSessionsForDevice(deviceId) {
2333
+ async cleanupStreamingSessionsForDevice(deviceId) {
2334
+ this.cancelThreadInventories(deviceId);
2236
2335
  this.cancelDeviceImages(deviceId);
2237
2336
  let cleanedCount = 0;
2337
+ const removals = [];
2238
2338
  for (const [messageId, session] of this.streamingMessages.entries()) {
2239
2339
  if (session.deviceId === deviceId) {
2240
2340
  console.log(`[RouterServer] Cleaning up streaming session for disconnected device: ${messageId}`);
2241
- // Also clean up any cardThreadMap entries associated with this session's feishuMessageId
2242
- if (session.feishuMessageId) {
2243
- this.cardThreadMap.delete(session.feishuMessageId);
2244
- }
2341
+ // Remove the session identity before awaiting durable card removal.
2342
+ this.streamingMessages.delete(messageId);
2343
+ removals.push(...this.removeActiveCardRoutes(session));
2245
2344
  this.clearDelegationProgressTimers(session);
2246
2345
  this.cancelImageReply(messageId);
2247
- this.streamingMessages.delete(messageId);
2248
2346
  this.lastStreamUpdateTime.delete(messageId);
2249
2347
  cleanedCount++;
2250
2348
  }
2251
2349
  }
2252
- // Clean up any orphaned cardThreadMap entries for this device
2253
- for (const [feishuMessageId, entry] of this.cardThreadMap.entries()) {
2254
- if (entry.deviceId === deviceId) {
2255
- this.cardThreadMap.delete(feishuMessageId);
2256
- }
2257
- }
2350
+ // Completed cards survive ordinary disconnects and Router shutdown.
2351
+ const results = await Promise.allSettled(removals);
2352
+ const failed = results.find(result => result.status === 'rejected');
2353
+ if (failed?.status === 'rejected')
2354
+ throw failed.reason;
2258
2355
  if (cleanedCount > 0) {
2259
2356
  console.log(`[RouterServer] Cleaned up ${cleanedCount} streaming sessions for device ${deviceId}, remaining: ${this.streamingMessages.size}`);
2260
2357
  }
@@ -2283,9 +2380,9 @@ class RouterServer {
2283
2380
  };
2284
2381
  // Drain accepted binding writes before any slow card or transfer cleanup.
2285
2382
  // A failure must not skip the remaining resource cleanup or be hidden.
2286
- for (const pending of this.threadInventoryRequests.values())
2287
- clearTimeout(pending.timer);
2288
- this.threadInventoryRequests.clear();
2383
+ for (const id of this.threadInventoryRequests.keys()) {
2384
+ this.cancelThreadInventory(id, new Error('Router is stopping. Retry the thread selection.'));
2385
+ }
2289
2386
  await attempt('Error flushing bindings during shutdown', () => this.store.flush());
2290
2387
  await attempt('Error stopping Tips scheduler', () => this.tips.stop());
2291
2388
  for (const id of this.imageReplies.keys())
@@ -2345,6 +2442,7 @@ class RouterServer {
2345
2442
  });
2346
2443
  });
2347
2444
  }
2445
+ await attempt('Error flushing card routes during shutdown', () => this.store.flush());
2348
2446
  if (failed)
2349
2447
  throw firstError;
2350
2448
  console.log('✅ Router server stopped');