@yu_robotics/remote-cli-router 1.6.139 → 1.6.145

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/README.md CHANGED
@@ -4,6 +4,19 @@ Router server for [remote-cli](https://www.npmjs.com/package/@yu_robotics/remote
4
4
 
5
5
  Backend executable discovery is local-client behavior. CLI 1.6.119 supplements Linux/macOS startup PATH and honors configured backend commands across detection and execution, preserving ZCode's native unset/empty-command lookup. Upgrade and restart the client to obtain this fix; upgrading only the Router does not repair an older client's environment. Valid client services need no reinstallation. The Router runtime, wire protocol, and existing compatibility requirements are unchanged. See [Backend Executable Discovery](../../README.md#backend-executable-discovery).
6
6
 
7
+ ## Public Activity
8
+
9
+ From Router 1.6.145, a foreground tool result updates its original collapsed tool row rather than adding a second disclosure. Input, output, and per-file diff previews remain inside; later text and worker slots stay stable. Unknown IDs and orphan results are not guessed into another call. Existing CLI peers are compatible, and worker cards and approvals are unchanged. See [Code Change Previews](../../README.md#code-change-previews).
10
+
11
+ CLI and Router 1.6.144 negotiate optional `activityProgress` without a protocol
12
+ version bump. One mutable status row sits at the tail of the newest active main
13
+ card, after tools and workers, and moves when the reply paginates. Historical
14
+ pages do not retain a live Running row. Each worker shows its own bounded activity
15
+ below its identity. Input requests and final results win over progress; completion
16
+ preserves the terminal status, model/effort note, and thread controls. Raw thinking
17
+ is not displayed as activity and progress is not a percentage. Older clients keep
18
+ their existing cards. See [Public Activity](../../README.md#public-activity).
19
+
7
20
  ## Maintenance Notices
8
21
 
9
22
  From CLI and Router 1.6.127, upgrade notices use concise Chinese summaries from `RELEASE_NOTES_ZH.md`, with one short title and bounded user-visible changes per release. `CHANGELOG.md` remains the English technical record. The CLI build requires matching current-version entries in both documents and bundles both, without online translation or model calls. New Routers show summaries directly and collapse technical details. Earlier maintenance-capable Routers show the summary in their existing collapsed panels; new Routers keep older CLI notes collapsed when no technical-details field is present. Cumulative ranges, silent first adoption, delivery acknowledgements, and protocol version 1 are unchanged.
@@ -32,7 +45,7 @@ The router server acts as a bridge between Feishu messaging and developer machin
32
45
  - **Image message forwarding** for Feishu images to supported backends, plus Codex native image output and local image files returned by any backend
33
46
  - **Client service management** is handled by the local CLI; the Router remains a separate long-running server process
34
47
  - **Queued task cards** appear at execution time for capable clients, with the thread, workspace, task preview, and remaining queue count; older clients retain waiting cards
35
- - **Delegated task progress** uses the existing reply and approval cards. With a supporting local CLI, Claude Code, Codex, Pi, AGY, OpenCode, Kimi Code, ZCode, and DSH can work within the selected thread; the Router does not run or select workers. From CLI 1.6.95, managed delegation accepts only a different backend. An unrestricted coordinator launches unrestricted workers; sandboxed coordinators have no eligible workers until cross-backend sandbox translation is supported. Native backend task/subagent tools are unchanged. Other backend approval options still apply. This policy is enforced on the local CLI and requires upgrading it. See [Cross-backend Delegation](../../README.md#cross-backend-delegation).
48
+ - **Delegated task progress** uses the existing reply and approval cards. With a supporting local CLI, Claude Code, Codex, Pi, AGY, OpenCode, Kimi Code, ZCode, and DSH can work within the selected thread; the Router does not run or select workers. From CLI 1.6.142, managed delegation accepts any eligible installed backend, including the coordinator backend through independent worker sessions. An unrestricted coordinator launches unrestricted workers; sandboxed coordinators have no eligible workers, including on the same backend, until scope-aware worker sandbox preservation is supported. Native backend task/subagent tools are unchanged. Other backend approval options still apply. This policy is enforced on the local CLI and requires upgrading it; the wire protocol remains unchanged. See [Cross-backend Delegation](../../README.md#cross-backend-delegation).
36
49
  - **WebSocket connections** from local clients
37
50
  - **Feishu long connection** for receiving and sending messages
38
51
  - **Task recovery** with compatible clients: resume output on a usable surviving card or create a new one, with an independent gap notice and plain-text handling of resumed fragments; failed card creation or recovery-notice updates are not acknowledged as successful recovery
@@ -72,7 +85,7 @@ old Routers remain compatible and old CLIs keep their existing behavior. The
72
85
  Other overlapping requests are rejected rather than globally queued. This does
73
86
  not add peer communication or modify native backends or Router execution.
74
87
  Sibling results are not explicitly forwarded; a reused same-backend lane retains
75
- its own earlier task context. Uncertain setup or cleanup retains the occupied
88
+ its own earlier task context. Uncertain native startup or exit retains the occupied
76
89
  global slot until the local CLI restarts.
77
90
 
78
91
  From CLI 1.6.139, Git delegation has no fixed repository size or file-count
@@ -81,6 +94,33 @@ command deadlines and buffered-output limits still apply. Path, ownership,
81
94
  artifact-integrity, and unknown-file checks remain in place. This is local CLI
82
95
  behavior; upgrading only the Router does not remove an older CLI's limits.
83
96
 
97
+ From CLI 1.6.141, local initialized submodules and embedded repositories also
98
+ contribute staged, unstaged, and nonignored working files. Their Git metadata and
99
+ history are not copied into the worker; explicit integration preserves every
100
+ source HEAD, index, and gitlink. Uninitialized submodule paths stay empty without
101
+ fetching a remote. Worker-created nested repositories or changes to those empty
102
+ paths require manual recovery and explicit retention, even with unchanged files.
103
+ Nested worktrees sharing an ancestor, external metadata pointers, partial clones,
104
+ and nested-local filter commands require recovery or exclusion. System/global
105
+ Git configuration remains trusted; the existing Git transfer deadline still applies.
106
+ A hard kill can leave a transfer quarantine requiring manual cleanup after its
107
+ processes exit. Tracked submodules also matched by outer ignore rules currently
108
+ fail admission; reconcile those rules before delegating.
109
+
110
+ From CLI 1.6.140, managed Git preparation, repository-lock waits, and artifact
111
+ collection are awaited separately from native startup/stop deadlines. Slots and
112
+ source reservations remain held until owned operations settle, even on cancellation;
113
+ no late worker is launched. Failed collection after confirmed exit preserves only
114
+ the affected lane and files for recovery rather than quarantining the source.
115
+ Individual Git command deadlines remain; cancellation may wait for Git to settle.
116
+ Slow launch/cancel tools return the accepted task ID and a pending status before
117
+ the adapter timeout; poll that ID with `remote_cli_result`, not a new delegation.
118
+ The response does not claim cancellation cleanup or workspace release is complete.
119
+ Checkpoints reject `assume-unchanged` and `skip-worktree` entries rather than
120
+ omitting hidden edits or treating missing sparse files as deletions. Resolve those
121
+ flags and sparse checkouts explicitly; the source index is never modified.
122
+ These changes require a CLI upgrade; Router protocol and native backends are unchanged.
123
+
84
124
  From CLI 1.6.135, the local CLI automatically reclaims verified successful
85
125
  no-change or successfully applied worker checkout directories and recreates them
86
126
  at their stable lane paths when needed. Conversation pointers and artifact refs
@@ -1,7 +1,7 @@
1
1
  import { BindingManager } from '../binding/BindingManager';
2
2
  import { ConnectionHub } from '../websocket/ConnectionHub';
3
3
  import { ThreadSummary, QueueConfirmationInfo } from '../types';
4
- import type { ExecutionMetadata } from '../types';
4
+ import type { ExecutionMetadata, ActivityProgressInfo } from '../types';
5
5
  import { JsonStore } from '../storage/JsonStore';
6
6
  import { Readable } from 'stream';
7
7
  import type { FileInput } from '../files/FileTransfers';
@@ -37,6 +37,9 @@ export declare class FeishuLongConnHandler {
37
37
  private threadSwitchStateCleanupTimer;
38
38
  private cardContentHashes;
39
39
  private plainTextCards;
40
+ /** Remember delivered tool ownership and non-tool content, never another copy of tool previews. */
41
+ private toolPageRemainders;
42
+ private activityShells;
40
43
  private messageLocks;
41
44
  private queueCardDecisions;
42
45
  private queueActionStates;
@@ -291,7 +294,7 @@ export declare class FeishuLongConnHandler {
291
294
  * @param openId User's open_id for creating continuation messages
292
295
  * @param threadName Thread name shown in continuation card headers
293
296
  */
294
- updateStreamingMessage(messageId: string, elements: any[], openId?: string, threadName?: string, cwd?: string): Promise<boolean>;
297
+ updateStreamingMessage(messageId: string, elements: any[], openId?: string, threadName?: string, cwd?: string, activity?: ActivityProgressInfo): Promise<boolean>;
295
298
  private _updateStreamingMessage;
296
299
  /**
297
300
  * Finalize streaming message
@@ -303,7 +306,7 @@ export declare class FeishuLongConnHandler {
303
306
  * @param openId User's open_id for creating continuation messages
304
307
  * @param replyThreadId Thread that produced the reply, independent of the selected thread
305
308
  */
306
- finalizeStreamingMessage(messageId: string, elements: any[], sessionAbbr?: string, openId?: string, cwd?: string, threadName?: string, threads?: ThreadSummary[], replyThreadId?: string, queueConfirmation?: QueueConfirmationInfo, executionMetadata?: ExecutionMetadata): Promise<boolean>;
309
+ finalizeStreamingMessage(messageId: string, elements: any[], sessionAbbr?: string, openId?: string, cwd?: string, threadName?: string, threads?: ThreadSummary[], replyThreadId?: string, queueConfirmation?: QueueConfirmationInfo, executionMetadata?: ExecutionMetadata, success?: boolean): Promise<boolean>;
307
310
  private _finalizeStreamingMessage;
308
311
  /**
309
312
  * Create Feishu Card 2.0 elements for thread switching buttons.
@@ -1 +1 @@
1
- {"version":3,"file":"FeishuLongConnHandler.d.ts","sourceRoot":"","sources":["../../src/feishu/FeishuLongConnHandler.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAA4B,aAAa,EAAc,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACtG,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAKjD,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG/D;;GAEG;AACH,MAAM,WAAW,2BAA2B;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,SAAS,CAAC;CAClB;AAED;;;GAGG;AACH,qBAAa,qBAAqB;IAChC,cAAc,CAAC,EAAE,kBAAkB,CAAC;IACpC,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,QAAQ,CAA8B;IAC9C,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,aAAa,CAA8B;IACnD,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,SAAS,CAAS;IAE1B,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAQ;IAI7C,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAO;IAC1C,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAW;IAChD,O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,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,GAAG,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,mBAAmB,CAAC;IAoDnL,yEAAyE;IACnE,oBAAoB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAahE,OAAO,CAAC,8BAA8B;YASxB,2BAA2B;IAsBzC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA4C5B;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IA+B3B;;OAEG;IACH,iBAAiB,IAAI,cAAc;CAGpC"}
@@ -38,6 +38,8 @@ const lark = __importStar(require("@larksuiteoapi/node-sdk"));
38
38
  const uuid_1 = require("uuid");
39
39
  const BindingManager_1 = require("../binding/BindingManager");
40
40
  const types_1 = require("../types");
41
+ const ActivityProgress_1 = require("../utils/ActivityProgress");
42
+ const ToolFormatter_1 = require("../utils/ToolFormatter");
41
43
  const ExecutionMetadata_1 = require("../utils/ExecutionMetadata");
42
44
  const fs = __importStar(require("fs"));
43
45
  const os = __importStar(require("os"));
@@ -75,6 +77,9 @@ class FeishuLongConnHandler {
75
77
  // Remember successful card payloads without retaining another copy of the content.
76
78
  cardContentHashes = new Map();
77
79
  plainTextCards = new Map();
80
+ /** Remember delivered tool ownership and non-tool content, never another copy of tool previews. */
81
+ toolPageRemainders = new Map();
82
+ activityShells = new Map();
78
83
  // Per-message serialization locks to prevent concurrent updates from creating duplicates
79
84
  messageLocks = new Map();
80
85
  queueCardDecisions = new Map();
@@ -998,17 +1003,17 @@ Examples:
998
1003
  * @param trailingElements Final panel elements that must remain together
999
1004
  * @returns Array of element chunks, each satisfying Feishu's limits
1000
1005
  */
1001
- splitElementsIntoChunks(elements, continuationHeaderElements = [], trailingElements = []) {
1006
+ splitElementsIntoChunks(elements, continuationHeaderElements = [], trailingElements = [], activityTail) {
1002
1007
  // If empty or very small, return as-is
1003
1008
  if (elements.length === 0) {
1004
- return [elements];
1009
+ return [activityTail ? [activityTail] : elements];
1005
1010
  }
1006
1011
  elements = (0, CardTables_1.prepareTableElements)(elements);
1007
1012
  // Check if we need to split at all
1008
- const needsSplitting = this.checkIfElementsNeedSplitting(elements);
1013
+ const needsSplitting = this.checkIfElementsNeedSplitting(activityTail ? [...elements, activityTail] : elements);
1009
1014
  console.log(`[FeishuHandler] Elements check: count=${elements.length}, needsSplitting=${needsSplitting}`);
1010
1015
  if (!needsSplitting) {
1011
- return [elements];
1016
+ return [activityTail ? [...elements, activityTail] : elements];
1012
1017
  }
1013
1018
  const chunks = [];
1014
1019
  let currentChunk = [];
@@ -1019,8 +1024,9 @@ Examples:
1019
1024
  // Reserve space for continuation indicators and the repeated card header.
1020
1025
  const continuationHeaderSize = JSON.stringify(continuationHeaderElements).length;
1021
1026
  const continuationHeaderTaggedNodes = continuationHeaderElements.reduce((total, element) => total + this.countTaggedNodes(element), 0);
1022
- const continuationIndicatorSize = 200 + continuationHeaderSize;
1023
- const continuationIndicatorCount = 2 + continuationHeaderTaggedNodes;
1027
+ // Reserve the bounded tail while packing so it never displaces content onto an activity-only page.
1028
+ const continuationIndicatorSize = 200 + continuationHeaderSize + (activityTail ? JSON.stringify(activityTail).length : 0);
1029
+ const continuationIndicatorCount = 2 + continuationHeaderTaggedNodes + (activityTail ? this.countTaggedNodes(activityTail) : 0);
1024
1030
  for (let i = 0; i < elements.length; i++) {
1025
1031
  const element = elements[i];
1026
1032
  const elementSize = JSON.stringify(element).length;
@@ -1083,6 +1089,8 @@ Examples:
1083
1089
  }
1084
1090
  }
1085
1091
  }
1092
+ if (activityTail)
1093
+ chunks[chunks.length - 1].push(activityTail);
1086
1094
  return chunks;
1087
1095
  }
1088
1096
  /**
@@ -1261,9 +1269,22 @@ Examples:
1261
1269
  * @param openId User's open_id for creating continuation messages
1262
1270
  * @param threadName Thread name shown in continuation card headers
1263
1271
  */
1264
- async updateStreamingMessage(messageId, elements, openId, threadName, cwd) {
1272
+ async updateStreamingMessage(messageId, elements, openId, threadName, cwd, activity) {
1265
1273
  const headerElements = this.createResponseHeaderElements(threadName || 'Resolving thread...', cwd);
1266
- return this.withMessageLock(messageId, () => this._updateStreamingMessage(messageId, [...headerElements, ...elements], openId, headerElements));
1274
+ return this.withMessageLock(messageId, () => {
1275
+ const shell = this.activityShells.get(messageId);
1276
+ // A delayed tool/image/text patch must not reopen a completed activity-bearing card.
1277
+ if (shell?.finishedAt !== undefined)
1278
+ return Promise.resolve(false);
1279
+ const normalized = (0, ActivityProgress_1.parseActivityProgress)(activity);
1280
+ if (normalized) {
1281
+ if (shell)
1282
+ shell.activity = normalized;
1283
+ else
1284
+ this.activityShells.set(messageId, { activity: normalized });
1285
+ }
1286
+ return this._updateStreamingMessage(messageId, [...headerElements, ...elements], openId, headerElements);
1287
+ });
1267
1288
  }
1268
1289
  async _updateStreamingMessage(messageId, elements, openId, continuationHeaderElements = [], trailingElements = []) {
1269
1290
  let updatingMessageId = messageId;
@@ -1276,7 +1297,10 @@ Examples:
1276
1297
  this.messageChains.set(messageId, chain);
1277
1298
  }
1278
1299
  // Split elements into chunks based on Feishu Card 2.0 limits
1279
- const chunks = this.splitElementsIntoChunks(elements, continuationHeaderElements, trailingElements);
1300
+ const shell = this.activityShells.get(messageId);
1301
+ const activityTail = shell && shell.finishedAt === undefined ? (0, ActivityProgress_1.createActivityElement)(shell.activity) : undefined;
1302
+ const chunks = this.splitElementsIntoChunks(elements, continuationHeaderElements, trailingElements, activityTail);
1303
+ const tailIndex = activityTail ? chunks.length - 1 : -1;
1280
1304
  console.log(`[FeishuHandler] Need ${chunks.length} card(s), currently have ${chain.length} card(s)`);
1281
1305
  let hashes = this.cardContentHashes.get(messageId);
1282
1306
  if (!hashes) {
@@ -1288,6 +1312,59 @@ Examples:
1288
1312
  fallbackCards = new Set();
1289
1313
  this.plainTextCards.set(messageId, fallbackCards);
1290
1314
  }
1315
+ const remainders = this.toolPageRemainders.get(messageId) ?? new Map();
1316
+ const isTool = (element) => element.tag === 'collapsible_panel'
1317
+ && typeof element.element_id === 'string' && element.element_id.startsWith(ToolFormatter_1.TOOL_CALL_ELEMENT_PREFIX);
1318
+ const nextToolIds = chunks.map(chunk => new Set(chunk.filter(isTool).map(element => element.element_id)));
1319
+ const clearDeliveredPage = async (index, elements) => {
1320
+ const cardId = chain[index];
1321
+ updatingMessageId = cardId;
1322
+ updatingCardIndex = index;
1323
+ const fallback = fallbackCards.has(index);
1324
+ const content = JSON.stringify({ schema: '2.0', body: { elements: fallback ? (0, CardTables_1.plainTextCard)(elements) : elements } });
1325
+ await this.sendCardRequest(content, async (body) => {
1326
+ const result = await this.client.im.message.patch({ path: { message_id: cardId }, data: { content: body } });
1327
+ if (!result?.code)
1328
+ this.workerContexts?.remember(cardId, messageId, body);
1329
+ return result;
1330
+ }, () => fallbackCards.add(index), !fallback);
1331
+ hashes[index] = '';
1332
+ };
1333
+ // Remove previous owners before publishing moved tools, including still-active
1334
+ // source pages. Failed cleanup keeps its receipt and cannot acknowledge the update.
1335
+ for (const [index, remainder] of remainders) {
1336
+ if ([...remainder.ids].every(id => nextToolIds[index]?.has(id)))
1337
+ continue;
1338
+ await clearDeliveredPage(index, remainder.elements);
1339
+ remainders.delete(index);
1340
+ if (shell?.tail?.index === index)
1341
+ shell.tail = undefined;
1342
+ }
1343
+ // Clear the actual previously delivered tail before moving it, including a
1344
+ // surplus page after content shrinks. Preserve its worker controls/content.
1345
+ if (shell?.tail && shell.tail.index !== tailIndex) {
1346
+ const previous = shell.tail;
1347
+ const cardId = chain[previous.index];
1348
+ if (cardId) {
1349
+ // A later ordinary patch must remain eligible after fallback or control decoration.
1350
+ await clearDeliveredPage(previous.index, previous.elements);
1351
+ }
1352
+ shell.tail = undefined;
1353
+ }
1354
+ const rememberPage = (index) => {
1355
+ if (nextToolIds[index].size) {
1356
+ remainders.set(index, { ids: nextToolIds[index], elements: [
1357
+ ...chunks[index].filter(element => !isTool(element) && element.element_id !== ActivityProgress_1.ACTIVITY_ELEMENT_ID),
1358
+ { tag: 'markdown', text_size: 'notation', content: 'Tool details moved to another card.' },
1359
+ ] });
1360
+ this.toolPageRemainders.set(messageId, remainders);
1361
+ }
1362
+ else
1363
+ remainders.delete(index);
1364
+ if (shell && index === tailIndex)
1365
+ shell.tail = { index,
1366
+ elements: chunks[index].filter(element => element.element_id !== ActivityProgress_1.ACTIVITY_ELEMENT_ID) };
1367
+ };
1291
1368
  const payloadFor = (index) => JSON.stringify({ schema: '2.0',
1292
1369
  body: { elements: fallbackCards.has(index) ? (0, CardTables_1.plainTextCard)(chunks[index]) : chunks[index] } });
1293
1370
  const payloads = chunks.map((_, index) => payloadFor(index));
@@ -1310,11 +1387,12 @@ Examples:
1310
1387
  }, () => usePlainText(index), !fallbackCards.has(index));
1311
1388
  // Failed requests must remain eligible for retry.
1312
1389
  hashes[index] = nextHashes[index];
1390
+ rememberPage(index);
1313
1391
  };
1314
1392
  await patchCard(0);
1315
1393
  // Handle continuation chunks: only create new cards, never delete during streaming.
1316
1394
  // Deleting a card causes Feishu UI to show "message retracted" which is confusing.
1317
- // Any excess continuation cards are left with stale content until finalize cleans them up.
1395
+ // Surplus cards retain non-tool content; obsolete paired tool rows were cleared above.
1318
1396
  if (chunks.length > 1 && openId) {
1319
1397
  const existingContinuationCards = chain.slice(1);
1320
1398
  const neededContinuationCards = chunks.length - 1;
@@ -1332,6 +1410,7 @@ Examples:
1332
1410
  if (newMessageId) {
1333
1411
  chain.push(newMessageId);
1334
1412
  hashes[chunkIndex] = nextHashes[chunkIndex];
1413
+ rememberPage(chunkIndex);
1335
1414
  }
1336
1415
  else {
1337
1416
  // Keep card indices aligned so the missing chunk can be retried.
@@ -1364,13 +1443,16 @@ Examples:
1364
1443
  * @param openId User's open_id for creating continuation messages
1365
1444
  * @param replyThreadId Thread that produced the reply, independent of the selected thread
1366
1445
  */
1367
- async finalizeStreamingMessage(messageId, elements, sessionAbbr, openId, cwd, threadName, threads, replyThreadId, queueConfirmation, executionMetadata) {
1368
- return this.withMessageLock(messageId, () => this._finalizeStreamingMessage(messageId, elements, sessionAbbr, openId, cwd, threadName, threads, replyThreadId, queueConfirmation, executionMetadata));
1446
+ async finalizeStreamingMessage(messageId, elements, sessionAbbr, openId, cwd, threadName, threads, replyThreadId, queueConfirmation, executionMetadata, success = true) {
1447
+ return this.withMessageLock(messageId, () => this._finalizeStreamingMessage(messageId, elements, sessionAbbr, openId, cwd, threadName, threads, replyThreadId, queueConfirmation, executionMetadata, success));
1369
1448
  }
1370
- async _finalizeStreamingMessage(messageId, elements, sessionAbbr, openId, cwd, threadName, threads, replyThreadId, queueConfirmation, executionMetadata) {
1449
+ async _finalizeStreamingMessage(messageId, elements, sessionAbbr, openId, cwd, threadName, threads, replyThreadId, queueConfirmation, executionMetadata, success = true) {
1371
1450
  try {
1451
+ const shell = this.activityShells.get(messageId);
1452
+ if (shell)
1453
+ shell.finishedAt = Date.now();
1372
1454
  // Build completion note
1373
- let noteContent = queueConfirmation ? '⏳ Awaiting queue confirmation' : '✅ Completed';
1455
+ let noteContent = queueConfirmation ? '⏳ Awaiting queue confirmation' : success ? '✅ Completed' : '❌ Failed';
1374
1456
  if (sessionAbbr) {
1375
1457
  noteContent += ` · Session: ${sessionAbbr}`;
1376
1458
  }
@@ -1400,7 +1482,7 @@ Examples:
1400
1482
  finalElements.push(...threadSwitchElements);
1401
1483
  }
1402
1484
  // Reuse streaming update logic: only create cards, never delete.
1403
- // Whatever layout was built during streaming stays as-is.
1485
+ // Repack changed previews and clear obsolete tool copies without retracting messages.
1404
1486
  const trailingElements = metadataElement && !queueConfirmation ? [...footerElements, ...threadSwitchElements] : threadSwitchElements;
1405
1487
  const updated = await this._updateStreamingMessage(messageId, finalElements, openId, headerElements, trailingElements);
1406
1488
  if (!updated) {
@@ -1427,6 +1509,7 @@ Examples:
1427
1509
  this.messageChains.delete(messageId);
1428
1510
  this.cardContentHashes.delete(messageId);
1429
1511
  this.plainTextCards.delete(messageId);
1512
+ this.toolPageRemainders.delete(messageId);
1430
1513
  return true;
1431
1514
  }
1432
1515
  catch (error) {
@@ -1843,6 +1926,10 @@ Examples:
1843
1926
  this.threadSwitchCardState.delete(id);
1844
1927
  }
1845
1928
  }
1929
+ for (const [id, state] of this.activityShells) {
1930
+ if (state.finishedAt !== undefined && state.finishedAt < cutoff)
1931
+ this.activityShells.delete(id);
1932
+ }
1846
1933
  }, 60 * 60 * 1000); // every hour
1847
1934
  }
1848
1935
  catch (error) {
@@ -1873,6 +1960,8 @@ Examples:
1873
1960
  this.threadSwitchStateCleanupTimer = null;
1874
1961
  }
1875
1962
  await this.bindingManager.close();
1963
+ this.activityShells.clear();
1964
+ this.toolPageRemainders.clear();
1876
1965
  console.log('✅ Feishu WebSocket connection stopped');
1877
1966
  }
1878
1967
  catch (error) {