dsh-leader-agent 0.10.0 → 0.10.1

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/lib/client.js CHANGED
@@ -407,14 +407,11 @@ function newCardIds(previous, next) {
407
407
  }
408
408
 
409
409
  // src/client/slot-retain.js
410
- function retainTargetOf(sessions, sessionId, fatherSessionId) {
411
- const address = typeof sessions.subagentAddress === "function" ? sessions.subagentAddress(sessionId) : void 0;
412
- if (address !== void 0) return address;
413
- if (typeof fatherSessionId !== "string" || fatherSessionId === "") return void 0;
414
- return { parentSessionId: fatherSessionId, childSessionId: sessionId, mode: "unknown" };
415
- }
410
+ var UNKNOWN_SESSION_PREFIX = "sessions.retain: unknown session ";
411
+ var DEFAULT_RETRY_DELAY_MS = 2e3;
412
+ var DEFAULT_RETRY_ATTEMPTS = 3;
416
413
  function isUnknownSessionError(error) {
417
- return error instanceof Error && error.message.startsWith("sessions.retain: unknown session ");
414
+ return error instanceof Error && error.message.startsWith(UNKNOWN_SESSION_PREFIX);
418
415
  }
419
416
  var SlotRetention = class {
420
417
  /**
@@ -425,14 +422,27 @@ var SlotRetention = class {
425
422
  * 快照时的回调
426
423
  * @param {(sessionId: string) => void} options.onDrop - 会话不再被保留时的回调
427
424
  * @param {(message: string) => void} [options.onError] - 保留失败时的报告出口
425
+ * @param {number} [options.retryDelayMs] - 未知会话的重试间隔
426
+ * @param {number} [options.retryAttempts] - 未知会话的重试次数(不含首次)
428
427
  */
429
- constructor({ retain, onState, onDrop, onError }) {
428
+ constructor({
429
+ retain,
430
+ onState,
431
+ onDrop,
432
+ onError,
433
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS,
434
+ retryAttempts = DEFAULT_RETRY_ATTEMPTS
435
+ }) {
430
436
  this.retain = retain;
431
437
  this.onState = onState;
432
438
  this.onDrop = onDrop;
433
439
  this.onError = onError ?? ((message) => console.warn(message));
440
+ this.retryDelayMs = retryDelayMs;
441
+ this.retryAttempts = retryAttempts;
434
442
  this.entries = /* @__PURE__ */ new Map();
435
443
  this.reported = /* @__PURE__ */ new Set();
444
+ this.timers = /* @__PURE__ */ new Map();
445
+ this.retries = /* @__PURE__ */ new Map();
436
446
  this.disposed = false;
437
447
  }
438
448
  /**
@@ -448,28 +458,37 @@ var SlotRetention = class {
448
458
  if (needed.has(sessionId)) continue;
449
459
  this.drop(sessionId, entry);
450
460
  }
461
+ for (const sessionId of this.timers.keys()) {
462
+ if (!needed.has(sessionId)) this.cancelRetry(sessionId);
463
+ }
451
464
  for (const sessionId of needed) {
452
- if (this.entries.has(sessionId)) continue;
465
+ if (this.entries.has(sessionId) || this.timers.has(sessionId)) continue;
453
466
  this.hold(sessionId);
454
467
  }
455
468
  }
456
469
  /**
457
470
  * 保留一个会话。
458
471
  *
459
- * 宿主不认识这个会话 id 时同步抛错——状态保持未知,不谎称空闲。
472
+ * 宿主还不认识这个会话 id 时不放弃:冷启动时宿主会话目录常比看板晚一拍,
473
+ * 按 `retryDelayMs` 重试有限次,用尽才报「状态未知」。宿主明确拒绝的其它错误
474
+ * 同步抛出。
460
475
  *
461
476
  * @param {string} sessionId - 会话 id
462
477
  */
463
478
  hold(sessionId) {
464
- if (this.disposed) return;
479
+ if (this.disposed || this.entries.has(sessionId) || this.timers.has(sessionId)) return;
465
480
  let reference;
466
481
  try {
467
482
  reference = this.retain(sessionId);
468
483
  } catch (error) {
469
- if (!isUnknownSessionError(error)) throw error;
470
- this.report(sessionId, `\u770B\u677F\u65E0\u6CD5\u4FDD\u7559\u4F1A\u8BDD ${sessionId}\uFF0C\u69FD\u4F4D\u72B6\u6001\u672A\u77E5\uFF1A${error.message}`);
484
+ if (isUnknownSessionError(error)) {
485
+ this.scheduleRetry(sessionId, error);
486
+ return;
487
+ }
488
+ this.report(sessionId, `\u770B\u677F\u65E0\u6CD5\u4FDD\u7559\u4F1A\u8BDD ${sessionId}\uFF0C\u69FD\u4F4D\u72B6\u6001\u672A\u77E5\uFF1A${error instanceof Error ? error.message : String(error)}`);
471
489
  return;
472
490
  }
491
+ this.retries.delete(sessionId);
473
492
  const entry = { reference, unsubscribe: void 0 };
474
493
  this.entries.set(sessionId, entry);
475
494
  reference.ready.then((binding) => {
@@ -487,6 +506,41 @@ var SlotRetention = class {
487
506
  this.report(sessionId, `\u770B\u677F\u6253\u5F00\u4F1A\u8BDD ${sessionId} \u5931\u8D25\uFF0C\u69FD\u4F4D\u72B6\u6001\u672A\u77E5\uFF1A${error instanceof Error ? error.message : String(error)}`);
488
507
  });
489
508
  }
509
+ /**
510
+ * 安排一次未知会话重试;次数用尽时报告一次并放弃。
511
+ *
512
+ * @param {string} sessionId - 会话 id
513
+ * @param {Error} error - 宿主抛出的未知会话错误
514
+ */
515
+ scheduleRetry(sessionId, error) {
516
+ const used = this.retries.get(sessionId) ?? 0;
517
+ if (used >= this.retryAttempts) {
518
+ this.retries.delete(sessionId);
519
+ this.report(sessionId, `\u770B\u677F\u65E0\u6CD5\u4FDD\u7559\u4F1A\u8BDD ${sessionId}\uFF0C\u69FD\u4F4D\u72B6\u6001\u672A\u77E5\uFF1A${error.message}`);
520
+ return;
521
+ }
522
+ this.retries.set(sessionId, used + 1);
523
+ const timer = setTimeout(() => {
524
+ this.timers.delete(sessionId);
525
+ if (this.disposed) return;
526
+ this.hold(sessionId);
527
+ }, this.retryDelayMs);
528
+ timer.unref?.();
529
+ this.timers.set(sessionId, timer);
530
+ }
531
+ /**
532
+ * 取消一个会话待跑的重试并清掉计数。
533
+ *
534
+ * @param {string} sessionId - 会话 id
535
+ */
536
+ cancelRetry(sessionId) {
537
+ const timer = this.timers.get(sessionId);
538
+ if (timer !== void 0) {
539
+ clearTimeout(timer);
540
+ this.timers.delete(sessionId);
541
+ }
542
+ this.retries.delete(sessionId);
543
+ }
490
544
  /**
491
545
  * 报告一次保留失败,同一个会话只报一次。
492
546
  * @param {string} sessionId - 会话 id
@@ -504,6 +558,7 @@ var SlotRetention = class {
504
558
  * @param {object} [entry] - 该会话的记录,缺省时取当前记录
505
559
  */
506
560
  drop(sessionId, entry = this.entries.get(sessionId)) {
561
+ this.cancelRetry(sessionId);
507
562
  if (entry === void 0) return;
508
563
  if (this.entries.get(sessionId) === entry) this.entries.delete(sessionId);
509
564
  entry.unsubscribe?.();
@@ -518,6 +573,8 @@ var SlotRetention = class {
518
573
  dispose() {
519
574
  if (this.disposed) return;
520
575
  this.disposed = true;
576
+ for (const sessionId of this.timers.keys()) this.cancelRetry(sessionId);
577
+ this.retries.clear();
521
578
  for (const entry of this.entries.values()) {
522
579
  entry.unsubscribe?.();
523
580
  entry.reference.release();
@@ -735,7 +792,9 @@ var LOCALE_UI = Object.freeze({
735
792
  "project.expandSessions": "Sitzungen ausklappen",
736
793
  "project.label": "Projekte",
737
794
  "project.leaderDeleted": "Die Leader-Sitzung des Projekts \u201E{name}\u201C wurde gel\xF6scht. Ersetzen Sie den Leader.",
795
+ "project.leaderLoading": "Die Leader-Sitzung wird noch geladen; neuer Versuch \u2026",
738
796
  "project.leaderMissing": "Das Projekt \u201E{name}\u201C hat keine Leader-Sitzung zum \xD6ffnen. Ersetzen Sie den Leader.",
797
+ "project.leaderOpenFailed": "Leader-Sitzung des Projekts \u201E{name}\u201C konnte nicht ge\xF6ffnet werden: {message}",
739
798
  "project.more": "Mehr",
740
799
  "project.name.empty": "Der Projektname darf nicht leer sein",
741
800
  "project.name.tooLong": "Der Projektname ist zu lang (h\xF6chstens {max} Zeichen)",
@@ -896,7 +955,9 @@ var LOCALE_UI = Object.freeze({
896
955
  "project.expandSessions": "Expand sessions",
897
956
  "project.label": "Projects",
898
957
  "project.leaderDeleted": 'The Leader session for project "{name}" has been deleted. Replace its Leader.',
958
+ "project.leaderLoading": "The Leader session is still loading; retrying\u2026",
899
959
  "project.leaderMissing": 'Project "{name}" has no Leader session to open. Replace its Leader.',
960
+ "project.leaderOpenFailed": 'Could not open the Leader session for project "{name}": {message}',
900
961
  "project.more": "More",
901
962
  "project.name.empty": "Project name cannot be empty",
902
963
  "project.name.tooLong": "Project name is too long (at most {max} characters)",
@@ -1057,7 +1118,9 @@ var LOCALE_UI = Object.freeze({
1057
1118
  "project.expandSessions": "Expandir sesiones",
1058
1119
  "project.label": "Proyectos",
1059
1120
  "project.leaderDeleted": "La sesi\xF3n del Leader del proyecto \xAB{name}\xBB se ha eliminado. Reemplace su Leader.",
1121
+ "project.leaderLoading": "La sesi\xF3n del Leader a\xFAn se est\xE1 cargando; reintentando\u2026",
1060
1122
  "project.leaderMissing": "El proyecto \xAB{name}\xBB no tiene una sesi\xF3n del Leader disponible para abrir. Reemplace su Leader.",
1123
+ "project.leaderOpenFailed": "No se pudo abrir la sesi\xF3n del Leader del proyecto \xAB{name}\xBB: {message}",
1061
1124
  "project.more": "M\xE1s",
1062
1125
  "project.name.empty": "El nombre del proyecto no puede estar vac\xEDo",
1063
1126
  "project.name.tooLong": "El nombre del proyecto es demasiado largo (m\xE1ximo {max} caracteres)",
@@ -1218,7 +1281,9 @@ var LOCALE_UI = Object.freeze({
1218
1281
  "project.expandSessions": "D\xE9velopper les sessions",
1219
1282
  "project.label": "Projets",
1220
1283
  "project.leaderDeleted": "La session Leader du projet \xAB {name} \xBB a \xE9t\xE9 supprim\xE9e. Remplacez son Leader.",
1284
+ "project.leaderLoading": "La session Leader est encore en cours de chargement ; nouvelle tentative\u2026",
1221
1285
  "project.leaderMissing": "Le projet \xAB {name} \xBB n'a aucune session Leader \xE0 ouvrir. Remplacez son Leader.",
1286
+ "project.leaderOpenFailed": "Impossible d'ouvrir la session Leader du projet \xAB {name} \xBB : {message}",
1222
1287
  "project.more": "Plus",
1223
1288
  "project.name.empty": "Le nom du projet ne peut pas \xEAtre vide",
1224
1289
  "project.name.tooLong": "Le nom du projet est trop long ({max} caract\xE8res maximum)",
@@ -1379,7 +1444,9 @@ var LOCALE_UI = Object.freeze({
1379
1444
  "project.expandSessions": "\u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u5C55\u958B",
1380
1445
  "project.label": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8",
1381
1446
  "project.leaderDeleted": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u300C{name}\u300D\u306E Leader \u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u524A\u9664\u3055\u308C\u307E\u3057\u305F\u3002Leader \u3092\u4EA4\u4EE3\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
1447
+ "project.leaderLoading": "Leader \u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u8AAD\u307F\u8FBC\u307F\u4E2D\u3067\u3059\u3002\u518D\u8A66\u884C\u3057\u3066\u3044\u307E\u3059\u2026",
1382
1448
  "project.leaderMissing": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u300C{name}\u300D\u306B\u306F\u958B\u3051\u308B Leader \u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u3042\u308A\u307E\u305B\u3093\u3002Leader \u3092\u4EA4\u4EE3\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
1449
+ "project.leaderOpenFailed": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u300C{name}\u300D\u306E Leader \u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u958B\u3051\u307E\u305B\u3093\u3067\u3057\u305F\uFF1A{message}",
1383
1450
  "project.more": "\u305D\u306E\u4ED6",
1384
1451
  "project.name.empty": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u540D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044",
1385
1452
  "project.name.tooLong": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u540D\u304C\u9577\u3059\u304E\u307E\u3059\uFF08\u6700\u5927 {max} \u6587\u5B57\uFF09",
@@ -1540,7 +1607,9 @@ var LOCALE_UI = Object.freeze({
1540
1607
  "project.expandSessions": "Expandir sess\xF5es",
1541
1608
  "project.label": "Projetos",
1542
1609
  "project.leaderDeleted": "A sess\xE3o do Leader do projeto \u201C{name}\u201D foi exclu\xEDda. Substitua o Leader do projeto.",
1610
+ "project.leaderLoading": "A sess\xE3o do Leader ainda est\xE1 carregando; tentando novamente\u2026",
1543
1611
  "project.leaderMissing": "O projeto \u201C{name}\u201D n\xE3o tem nenhuma sess\xE3o do Leader para abrir. Substitua o Leader do projeto.",
1612
+ "project.leaderOpenFailed": "N\xE3o foi poss\xEDvel abrir a sess\xE3o do Leader do projeto \u201C{name}\u201D: {message}",
1544
1613
  "project.more": "Mais",
1545
1614
  "project.name.empty": "O nome do projeto n\xE3o pode ficar vazio",
1546
1615
  "project.name.tooLong": "O nome do projeto \xE9 muito longo (no m\xE1ximo {max} caracteres)",
@@ -1701,7 +1770,9 @@ var LOCALE_UI = Object.freeze({
1701
1770
  "project.expandSessions": "\u0420\u0430\u0437\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0441\u0435\u0430\u043D\u0441\u044B",
1702
1771
  "project.label": "\u041F\u0440\u043E\u0435\u043A\u0442\u044B",
1703
1772
  "project.leaderDeleted": "\u0421\u0435\u0430\u043D\u0441 Leader \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \xAB{name}\xBB \u0443\u0434\u0430\u043B\u0451\u043D. \u0417\u0430\u043C\u0435\u043D\u0438\u0442\u0435 Leader \u043F\u0440\u043E\u0435\u043A\u0442\u0430.",
1773
+ "project.leaderLoading": "\u0421\u0435\u0430\u043D\u0441 Leader \u0435\u0449\u0451 \u0437\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u0442\u0441\u044F; \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u0430\u044F \u043F\u043E\u043F\u044B\u0442\u043A\u0430\u2026",
1704
1774
  "project.leaderMissing": "\u0423 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \xAB{name}\xBB \u043D\u0435\u0442 \u0441\u0435\u0430\u043D\u0441\u0430 Leader, \u043A\u043E\u0442\u043E\u0440\u044B\u0439 \u043C\u043E\u0436\u043D\u043E \u043E\u0442\u043A\u0440\u044B\u0442\u044C. \u0417\u0430\u043C\u0435\u043D\u0438\u0442\u0435 Leader \u043F\u0440\u043E\u0435\u043A\u0442\u0430.",
1775
+ "project.leaderOpenFailed": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0442\u043A\u0440\u044B\u0442\u044C \u0441\u0435\u0430\u043D\u0441 Leader \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \xAB{name}\xBB: {message}",
1705
1776
  "project.more": "\u0415\u0449\u0451",
1706
1777
  "project.name.empty": "\u041D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C",
1707
1778
  "project.name.tooLong": "\u041D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0434\u043B\u0438\u043D\u043D\u043E\u0435 (\u043D\u0435 \u0431\u043E\u043B\u0435\u0435 {max} \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432)",
@@ -1862,7 +1933,9 @@ var LOCALE_UI = Object.freeze({
1862
1933
  "project.expandSessions": "\u5C55\u5F00\u4F1A\u8BDD",
1863
1934
  "project.label": "\u9879\u76EE",
1864
1935
  "project.leaderDeleted": "\u9879\u76EE\u300C{name}\u300D\u7684 leader \u4F1A\u8BDD\u5DF2\u88AB\u5220\u9664\uFF0C\u8BF7\u6362\u65B0 Leader\u3002",
1936
+ "project.leaderLoading": "Leader \u4F1A\u8BDD\u8FD8\u5728\u52A0\u8F7D\uFF0C\u6B63\u5728\u91CD\u8BD5\u2026",
1865
1937
  "project.leaderMissing": "\u9879\u76EE\u300C{name}\u300D\u6CA1\u6709\u53EF\u6253\u5F00\u7684 leader \u4F1A\u8BDD\uFF0C\u8BF7\u6362\u65B0 Leader\u3002",
1938
+ "project.leaderOpenFailed": "\u6253\u5F00\u9879\u76EE\u300C{name}\u300D\u7684 Leader \u4F1A\u8BDD\u5931\u8D25\uFF1A{message}",
1866
1939
  "project.more": "\u66F4\u591A",
1867
1940
  "project.name.empty": "\u9879\u76EE\u540D\u4E0D\u80FD\u4E3A\u7A7A",
1868
1941
  "project.name.tooLong": "\u9879\u76EE\u540D\u8FC7\u957F\uFF08\u4E0A\u9650 {max} \u5B57\uFF09",
@@ -5414,22 +5487,15 @@ function useSlotStates(cards, getSessions, useSessionStatus) {
5414
5487
  const retention = (0, import_react9.useRef)(void 0);
5415
5488
  const latest = (0, import_react9.useRef)(getSessions);
5416
5489
  latest.current = getSessions;
5417
- const parentsNow = (0, import_react9.useMemo)(() => {
5418
- const table = /* @__PURE__ */ new Map();
5490
+ const neededKey = (0, import_react9.useMemo)(() => {
5491
+ const ids = /* @__PURE__ */ new Set();
5419
5492
  for (const card of cards) {
5420
- const creator = typeof card.createdBy === "string" && card.createdBy !== "" ? card.createdBy : void 0;
5421
5493
  for (const binding of slotBindingsOf(card)) {
5422
- if (binding.sessionId === "") continue;
5423
- if (!table.has(binding.sessionId) || table.get(binding.sessionId) === void 0 && creator !== void 0) {
5424
- table.set(binding.sessionId, creator);
5425
- }
5494
+ if (binding.sessionId !== "") ids.add(binding.sessionId);
5426
5495
  }
5427
5496
  }
5428
- return table;
5497
+ return [...ids].sort().join("\n");
5429
5498
  }, [cards]);
5430
- const parents = (0, import_react9.useRef)(parentsNow);
5431
- parents.current = parentsNow;
5432
- const neededKey = (0, import_react9.useMemo)(() => [...parentsNow.keys()].sort().join("\n"), [parentsNow]);
5433
5499
  const needed = (0, import_react9.useMemo)(
5434
5500
  () => new Set(neededKey === "" ? [] : neededKey.split("\n")),
5435
5501
  [neededKey]
@@ -5451,18 +5517,7 @@ function useSlotStates(cards, getSessions, useSessionStatus) {
5451
5517
  retain: (sessionId) => {
5452
5518
  const sessions = latest.current();
5453
5519
  if (sessions === void 0 || sessions === null) throw new Error("\u4F1A\u8BDD\u670D\u52A1\u4E0D\u53EF\u7528");
5454
- const options = { source: "dshLeaderBoard" };
5455
- try {
5456
- return sessions.retain(sessionId, options);
5457
- } catch (error) {
5458
- const target = retainTargetOf(sessions, sessionId, parents.current.get(sessionId));
5459
- if (target === void 0) throw error;
5460
- try {
5461
- return sessions.retain(target, options);
5462
- } catch {
5463
- throw error;
5464
- }
5465
- }
5520
+ return sessions.retain(sessionId, { source: "dshLeaderBoard" });
5466
5521
  },
5467
5522
  onState: (sessionId, state) => {
5468
5523
  setSnapshots((previous) => {
@@ -6416,6 +6471,39 @@ var import_react_dom2 = require("react-dom");
6416
6471
  var import_dsh_client_ui_primitives2 = require("@deepseek-ai/dsh-client-ui-primitives");
6417
6472
 
6418
6473
  // src/client/project-panel-logic.js
6474
+ var OPEN_RETRY_DELAYS_MS = [200, 500, 1e3];
6475
+ function waitForRetry(ms) {
6476
+ return new Promise((resolve) => {
6477
+ setTimeout(resolve, ms);
6478
+ });
6479
+ }
6480
+ function createInFlightGuard() {
6481
+ const active = /* @__PURE__ */ new Set();
6482
+ return {
6483
+ /**
6484
+ * @param {string} key - 项目 id
6485
+ * @returns {boolean} 是否拿到锁;已在飞时返回 false
6486
+ */
6487
+ begin(key) {
6488
+ if (active.has(key)) return false;
6489
+ active.add(key);
6490
+ return true;
6491
+ },
6492
+ /**
6493
+ * @param {string} key - 项目 id
6494
+ */
6495
+ end(key) {
6496
+ active.delete(key);
6497
+ },
6498
+ /**
6499
+ * @param {string} key - 项目 id
6500
+ * @returns {boolean} 当前是否在飞
6501
+ */
6502
+ has(key) {
6503
+ return active.has(key);
6504
+ }
6505
+ };
6506
+ }
6419
6507
  function basenameOf(path) {
6420
6508
  const trimmed = path.replace(/[\\/]+$/, "");
6421
6509
  const index = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
@@ -6531,13 +6619,31 @@ function isArchiveActiveRefusal(reason) {
6531
6619
  const code = reason.rpcError?.code;
6532
6620
  return code === "workspace/session-active";
6533
6621
  }
6534
- function openLeaderSession({ project, openSession, t }) {
6622
+ async function openLeaderSession({
6623
+ project,
6624
+ openSession,
6625
+ t,
6626
+ wait = waitForRetry,
6627
+ retryDelaysMs = OPEN_RETRY_DELAYS_MS,
6628
+ onRetry = () => {
6629
+ }
6630
+ }) {
6535
6631
  const sessionId = project?.leaderSessionId;
6536
6632
  if (typeof sessionId !== "string" || sessionId === "") {
6537
6633
  return { ok: false, message: t("project.leaderMissing", { name: project?.name ?? "" }) };
6538
6634
  }
6539
- openSession(sessionId);
6540
- return { ok: true };
6635
+ for (let attempt = 0; ; attempt += 1) {
6636
+ try {
6637
+ openSession(sessionId);
6638
+ return { ok: true };
6639
+ } catch (error) {
6640
+ if (!isUnknownSessionError(error)) throw error;
6641
+ if (attempt >= retryDelaysMs.length) throw error;
6642
+ const delayMs = retryDelaysMs[attempt];
6643
+ onRetry(attempt + 1, delayMs);
6644
+ await wait(delayMs);
6645
+ }
6646
+ }
6541
6647
  }
6542
6648
  function buildProjectMenuItems(project, handlers, t) {
6543
6649
  const items = [];
@@ -8581,6 +8687,7 @@ function ProjectPanel(props) {
8581
8687
  }), [refresh, refreshSessionIndex]);
8582
8688
  const sessionsRef = (0, import_react14.useRef)(getSessions);
8583
8689
  sessionsRef.current = getSessions;
8690
+ const openingProjects = (0, import_react14.useRef)(createInFlightGuard());
8584
8691
  const refreshIndexRef = (0, import_react14.useRef)(refreshSessionIndex);
8585
8692
  refreshIndexRef.current = refreshSessionIndex;
8586
8693
  (0, import_react14.useEffect)(() => {
@@ -8816,12 +8923,25 @@ function ProjectPanel(props) {
8816
8923
  showToast(t("project.error.navigation"));
8817
8924
  return;
8818
8925
  }
8819
- const result = openLeaderSession({
8820
- project,
8821
- openSession: (sessionId) => uiWorkspace.openSession(sessionId),
8822
- t
8823
- });
8824
- if (result.ok !== true) showToast(result.message);
8926
+ if (!openingProjects.current.begin(project.id)) return;
8927
+ try {
8928
+ const result = await openLeaderSession({
8929
+ project,
8930
+ openSession: (sessionId) => uiWorkspace.openSession(sessionId),
8931
+ t,
8932
+ onRetry: () => showToast(t("project.leaderLoading", { name: project.name }))
8933
+ });
8934
+ if (result.ok !== true) showToast(result.message);
8935
+ } catch (error) {
8936
+ const message = t("project.leaderOpenFailed", {
8937
+ name: project.name,
8938
+ message: error instanceof Error ? error.message : String(error)
8939
+ });
8940
+ console.error(message, error);
8941
+ showToast(message);
8942
+ } finally {
8943
+ openingProjects.current.end(project.id);
8944
+ }
8825
8945
  }, [getUiWorkspace, t]);
8826
8946
  const renameProject = (0, import_react14.useCallback)(async (project, name) => {
8827
8947
  if (busy) return;
package/locale/de.json CHANGED
@@ -135,7 +135,9 @@
135
135
  "project.expandSessions": "Sitzungen ausklappen",
136
136
  "project.label": "Projekte",
137
137
  "project.leaderDeleted": "Die Leader-Sitzung des Projekts „{name}“ wurde gelöscht. Ersetzen Sie den Leader.",
138
+ "project.leaderLoading": "Die Leader-Sitzung wird noch geladen; neuer Versuch …",
138
139
  "project.leaderMissing": "Das Projekt „{name}“ hat keine Leader-Sitzung zum Öffnen. Ersetzen Sie den Leader.",
140
+ "project.leaderOpenFailed": "Leader-Sitzung des Projekts „{name}“ konnte nicht geöffnet werden: {message}",
139
141
  "project.more": "Mehr",
140
142
  "project.name.empty": "Der Projektname darf nicht leer sein",
141
143
  "project.name.tooLong": "Der Projektname ist zu lang (höchstens {max} Zeichen)",
package/locale/en.json CHANGED
@@ -135,7 +135,9 @@
135
135
  "project.expandSessions": "Expand sessions",
136
136
  "project.label": "Projects",
137
137
  "project.leaderDeleted": "The Leader session for project \"{name}\" has been deleted. Replace its Leader.",
138
+ "project.leaderLoading": "The Leader session is still loading; retrying…",
138
139
  "project.leaderMissing": "Project \"{name}\" has no Leader session to open. Replace its Leader.",
140
+ "project.leaderOpenFailed": "Could not open the Leader session for project \"{name}\": {message}",
139
141
  "project.more": "More",
140
142
  "project.name.empty": "Project name cannot be empty",
141
143
  "project.name.tooLong": "Project name is too long (at most {max} characters)",
package/locale/es.json CHANGED
@@ -135,7 +135,9 @@
135
135
  "project.expandSessions": "Expandir sesiones",
136
136
  "project.label": "Proyectos",
137
137
  "project.leaderDeleted": "La sesión del Leader del proyecto «{name}» se ha eliminado. Reemplace su Leader.",
138
+ "project.leaderLoading": "La sesión del Leader aún se está cargando; reintentando…",
138
139
  "project.leaderMissing": "El proyecto «{name}» no tiene una sesión del Leader disponible para abrir. Reemplace su Leader.",
140
+ "project.leaderOpenFailed": "No se pudo abrir la sesión del Leader del proyecto «{name}»: {message}",
139
141
  "project.more": "Más",
140
142
  "project.name.empty": "El nombre del proyecto no puede estar vacío",
141
143
  "project.name.tooLong": "El nombre del proyecto es demasiado largo (máximo {max} caracteres)",
package/locale/fr.json CHANGED
@@ -135,7 +135,9 @@
135
135
  "project.expandSessions": "Développer les sessions",
136
136
  "project.label": "Projets",
137
137
  "project.leaderDeleted": "La session Leader du projet « {name} » a été supprimée. Remplacez son Leader.",
138
+ "project.leaderLoading": "La session Leader est encore en cours de chargement ; nouvelle tentative…",
138
139
  "project.leaderMissing": "Le projet « {name} » n'a aucune session Leader à ouvrir. Remplacez son Leader.",
140
+ "project.leaderOpenFailed": "Impossible d'ouvrir la session Leader du projet « {name} » : {message}",
139
141
  "project.more": "Plus",
140
142
  "project.name.empty": "Le nom du projet ne peut pas être vide",
141
143
  "project.name.tooLong": "Le nom du projet est trop long ({max} caractères maximum)",
package/locale/ja.json CHANGED
@@ -135,7 +135,9 @@
135
135
  "project.expandSessions": "セッションを展開",
136
136
  "project.label": "プロジェクト",
137
137
  "project.leaderDeleted": "プロジェクト「{name}」の Leader セッションが削除されました。Leader を交代してください。",
138
+ "project.leaderLoading": "Leader セッションを読み込み中です。再試行しています…",
138
139
  "project.leaderMissing": "プロジェクト「{name}」には開ける Leader セッションがありません。Leader を交代してください。",
140
+ "project.leaderOpenFailed": "プロジェクト「{name}」の Leader セッションを開けませんでした:{message}",
139
141
  "project.more": "その他",
140
142
  "project.name.empty": "プロジェクト名を入力してください",
141
143
  "project.name.tooLong": "プロジェクト名が長すぎます(最大 {max} 文字)",
package/locale/pt.json CHANGED
@@ -135,7 +135,9 @@
135
135
  "project.expandSessions": "Expandir sessões",
136
136
  "project.label": "Projetos",
137
137
  "project.leaderDeleted": "A sessão do Leader do projeto “{name}” foi excluída. Substitua o Leader do projeto.",
138
+ "project.leaderLoading": "A sessão do Leader ainda está carregando; tentando novamente…",
138
139
  "project.leaderMissing": "O projeto “{name}” não tem nenhuma sessão do Leader para abrir. Substitua o Leader do projeto.",
140
+ "project.leaderOpenFailed": "Não foi possível abrir a sessão do Leader do projeto “{name}”: {message}",
139
141
  "project.more": "Mais",
140
142
  "project.name.empty": "O nome do projeto não pode ficar vazio",
141
143
  "project.name.tooLong": "O nome do projeto é muito longo (no máximo {max} caracteres)",
package/locale/ru.json CHANGED
@@ -135,7 +135,9 @@
135
135
  "project.expandSessions": "Развернуть сеансы",
136
136
  "project.label": "Проекты",
137
137
  "project.leaderDeleted": "Сеанс Leader проекта «{name}» удалён. Замените Leader проекта.",
138
+ "project.leaderLoading": "Сеанс Leader ещё загружается; повторная попытка…",
138
139
  "project.leaderMissing": "У проекта «{name}» нет сеанса Leader, который можно открыть. Замените Leader проекта.",
140
+ "project.leaderOpenFailed": "Не удалось открыть сеанс Leader проекта «{name}»: {message}",
139
141
  "project.more": "Ещё",
140
142
  "project.name.empty": "Название проекта не может быть пустым",
141
143
  "project.name.tooLong": "Название проекта слишком длинное (не более {max} символов)",
package/locale/zh.json CHANGED
@@ -135,7 +135,9 @@
135
135
  "project.expandSessions": "展开会话",
136
136
  "project.label": "项目",
137
137
  "project.leaderDeleted": "项目「{name}」的 leader 会话已被删除,请换新 Leader。",
138
+ "project.leaderLoading": "Leader 会话还在加载,正在重试…",
138
139
  "project.leaderMissing": "项目「{name}」没有可打开的 leader 会话,请换新 Leader。",
140
+ "project.leaderOpenFailed": "打开项目「{name}」的 Leader 会话失败:{message}",
139
141
  "project.more": "更多",
140
142
  "project.name.empty": "项目名不能为空",
141
143
  "project.name.tooLong": "项目名过长(上限 {max} 字)",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-leader-agent",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
4
4
  "description": "Leader-driven dispatch for DeepSeek Harness: protocol skills, project bootstrap, and a delivery board.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -44,7 +44,7 @@ import {
44
44
  resolveBoardAccess,
45
45
  sameProjectSummary,
46
46
  } from './project-board-data.js'
47
- import { SlotRetention, retainTargetOf } from './slot-retain.js'
47
+ import { SlotRetention } from './slot-retain.js'
48
48
  import { BoardCard } from './board-card.js'
49
49
  import { CardDetail } from './card-detail.js'
50
50
  import { describeCardRemoval } from './card-detail-view.js'
@@ -343,31 +343,18 @@ function useSlotStates(cards, getSessions, useSessionStatus) {
343
343
  const retention = useRef(undefined)
344
344
  const latest = useRef(getSessions)
345
345
  latest.current = getSessions
346
- // 建卡会话表:子代理槽位的地址要用真正的父会话,卡片自己记着 `createdBy`。
347
- // 表必须按 `cards` 记忆(每次渲染新建会连带 `needed` 变化,把同步效果拖成每
348
- // 帧跑一次),保留器的闭包经 ref 读最新值。
349
- const parentsNow = useMemo(() => {
350
- const table = new Map()
346
+ // 依赖用 id 排序串而不是 Set 本身:卡片每 2 秒轮询都会换一个新数组,用 Set
347
+ // 当依赖会让同步效果每 2 秒跑一次——保留失败的槽位不在账本里,每次都会再
348
+ // retain 一遍,日志被去重挡住但底层调用没停。
349
+ const neededKey = useMemo(() => {
350
+ const ids = new Set()
351
351
  for (const card of cards) {
352
- const creator = typeof card.createdBy === 'string' && card.createdBy !== '' ? card.createdBy : undefined
353
352
  for (const binding of slotBindingsOf(card)) {
354
- if (binding.sessionId === '') continue
355
- // 同一个会话可能绑在多张卡上:优先留记了建卡会话的那一张,存量卡没有
356
- // `createdBy`,拿它当父会话会让地址挂到看板会话上。
357
- if (!table.has(binding.sessionId) || (table.get(binding.sessionId) === undefined && creator !== undefined)) {
358
- table.set(binding.sessionId, creator)
359
- }
353
+ if (binding.sessionId !== '') ids.add(binding.sessionId)
360
354
  }
361
355
  }
362
- return table
356
+ return [...ids].sort().join('\n')
363
357
  }, [cards])
364
- const parents = useRef(parentsNow)
365
- parents.current = parentsNow
366
-
367
- // 依赖用 id 排序串而不是 Map 本身:卡片每 2 秒轮询都会换一个新数组,用 Map
368
- // 当依赖会让 `needed` 每轮都是新 Set,同步效果跟着每 2 秒跑一次——保留失败的
369
- // 槽位不在账本里,每次都会再 retain 一遍,日志被去重挡住但底层调用没停。
370
- const neededKey = useMemo(() => [...parentsNow.keys()].sort().join('\n'), [parentsNow])
371
358
  const needed = useMemo(
372
359
  () => new Set(neededKey === '' ? [] : neededKey.split('\n')),
373
360
  [neededKey],
@@ -393,24 +380,10 @@ function useSlotStates(cards, getSessions, useSessionStatus) {
393
380
  retain: (sessionId) => {
394
381
  const sessions = latest.current()
395
382
  if (sessions === undefined || sessions === null) throw new Error('会话服务不可用')
396
- const options = { source: 'dshLeaderBoard' }
397
- try {
398
- return sessions.retain(sessionId, options)
399
- } catch (error) {
400
- // 有些会话在客户端会话目录里没有独立条目(如历史 subagent 时代的
401
- // worker),裸 id 认不出来。这类会话要靠
402
- // `{ parentSessionId, childSessionId }` 地址才找得到——父会话只能是建
403
- // 这张卡的会话。看板当前挂在哪个会话上(尤其切到 worker 后)不是父子
404
- // 关系,拿它兜底会得到宿主不认的地址;宁可把原错误抛回去,由保留器
405
- // 记下「未知」,也不编造父会话。
406
- const target = retainTargetOf(sessions, sessionId, parents.current.get(sessionId))
407
- if (target === undefined) throw error
408
- try {
409
- return sessions.retain(target, options)
410
- } catch {
411
- throw error
412
- }
413
- }
383
+ // 只按裸 id 保留:worker 是根会话,宿主认不认得由它自己判。编造
384
+ // `{ parentSessionId, childSessionId }` 地址会让宿主把根会话投影成子代理,
385
+ // 之后每次读历史都按子代理校验,一律 `subagent/unauthorized`。
386
+ return sessions.retain(sessionId, { source: 'dshLeaderBoard' })
414
387
  },
415
388
  onState: (sessionId, state) => {
416
389
  setSnapshots((previous) => {
@@ -133,7 +133,9 @@ export const LOCALE_UI = Object.freeze({
133
133
  "project.expandSessions": "Sitzungen ausklappen",
134
134
  "project.label": "Projekte",
135
135
  "project.leaderDeleted": "Die Leader-Sitzung des Projekts „{name}“ wurde gelöscht. Ersetzen Sie den Leader.",
136
+ "project.leaderLoading": "Die Leader-Sitzung wird noch geladen; neuer Versuch …",
136
137
  "project.leaderMissing": "Das Projekt „{name}“ hat keine Leader-Sitzung zum Öffnen. Ersetzen Sie den Leader.",
138
+ "project.leaderOpenFailed": "Leader-Sitzung des Projekts „{name}“ konnte nicht geöffnet werden: {message}",
137
139
  "project.more": "Mehr",
138
140
  "project.name.empty": "Der Projektname darf nicht leer sein",
139
141
  "project.name.tooLong": "Der Projektname ist zu lang (höchstens {max} Zeichen)",
@@ -294,7 +296,9 @@ export const LOCALE_UI = Object.freeze({
294
296
  "project.expandSessions": "Expand sessions",
295
297
  "project.label": "Projects",
296
298
  "project.leaderDeleted": "The Leader session for project \"{name}\" has been deleted. Replace its Leader.",
299
+ "project.leaderLoading": "The Leader session is still loading; retrying…",
297
300
  "project.leaderMissing": "Project \"{name}\" has no Leader session to open. Replace its Leader.",
301
+ "project.leaderOpenFailed": "Could not open the Leader session for project \"{name}\": {message}",
298
302
  "project.more": "More",
299
303
  "project.name.empty": "Project name cannot be empty",
300
304
  "project.name.tooLong": "Project name is too long (at most {max} characters)",
@@ -455,7 +459,9 @@ export const LOCALE_UI = Object.freeze({
455
459
  "project.expandSessions": "Expandir sesiones",
456
460
  "project.label": "Proyectos",
457
461
  "project.leaderDeleted": "La sesión del Leader del proyecto «{name}» se ha eliminado. Reemplace su Leader.",
462
+ "project.leaderLoading": "La sesión del Leader aún se está cargando; reintentando…",
458
463
  "project.leaderMissing": "El proyecto «{name}» no tiene una sesión del Leader disponible para abrir. Reemplace su Leader.",
464
+ "project.leaderOpenFailed": "No se pudo abrir la sesión del Leader del proyecto «{name}»: {message}",
459
465
  "project.more": "Más",
460
466
  "project.name.empty": "El nombre del proyecto no puede estar vacío",
461
467
  "project.name.tooLong": "El nombre del proyecto es demasiado largo (máximo {max} caracteres)",
@@ -616,7 +622,9 @@ export const LOCALE_UI = Object.freeze({
616
622
  "project.expandSessions": "Développer les sessions",
617
623
  "project.label": "Projets",
618
624
  "project.leaderDeleted": "La session Leader du projet « {name} » a été supprimée. Remplacez son Leader.",
625
+ "project.leaderLoading": "La session Leader est encore en cours de chargement ; nouvelle tentative…",
619
626
  "project.leaderMissing": "Le projet « {name} » n'a aucune session Leader à ouvrir. Remplacez son Leader.",
627
+ "project.leaderOpenFailed": "Impossible d'ouvrir la session Leader du projet « {name} » : {message}",
620
628
  "project.more": "Plus",
621
629
  "project.name.empty": "Le nom du projet ne peut pas être vide",
622
630
  "project.name.tooLong": "Le nom du projet est trop long ({max} caractères maximum)",
@@ -777,7 +785,9 @@ export const LOCALE_UI = Object.freeze({
777
785
  "project.expandSessions": "セッションを展開",
778
786
  "project.label": "プロジェクト",
779
787
  "project.leaderDeleted": "プロジェクト「{name}」の Leader セッションが削除されました。Leader を交代してください。",
788
+ "project.leaderLoading": "Leader セッションを読み込み中です。再試行しています…",
780
789
  "project.leaderMissing": "プロジェクト「{name}」には開ける Leader セッションがありません。Leader を交代してください。",
790
+ "project.leaderOpenFailed": "プロジェクト「{name}」の Leader セッションを開けませんでした:{message}",
781
791
  "project.more": "その他",
782
792
  "project.name.empty": "プロジェクト名を入力してください",
783
793
  "project.name.tooLong": "プロジェクト名が長すぎます(最大 {max} 文字)",
@@ -938,7 +948,9 @@ export const LOCALE_UI = Object.freeze({
938
948
  "project.expandSessions": "Expandir sessões",
939
949
  "project.label": "Projetos",
940
950
  "project.leaderDeleted": "A sessão do Leader do projeto “{name}” foi excluída. Substitua o Leader do projeto.",
951
+ "project.leaderLoading": "A sessão do Leader ainda está carregando; tentando novamente…",
941
952
  "project.leaderMissing": "O projeto “{name}” não tem nenhuma sessão do Leader para abrir. Substitua o Leader do projeto.",
953
+ "project.leaderOpenFailed": "Não foi possível abrir a sessão do Leader do projeto “{name}”: {message}",
942
954
  "project.more": "Mais",
943
955
  "project.name.empty": "O nome do projeto não pode ficar vazio",
944
956
  "project.name.tooLong": "O nome do projeto é muito longo (no máximo {max} caracteres)",
@@ -1099,7 +1111,9 @@ export const LOCALE_UI = Object.freeze({
1099
1111
  "project.expandSessions": "Развернуть сеансы",
1100
1112
  "project.label": "Проекты",
1101
1113
  "project.leaderDeleted": "Сеанс Leader проекта «{name}» удалён. Замените Leader проекта.",
1114
+ "project.leaderLoading": "Сеанс Leader ещё загружается; повторная попытка…",
1102
1115
  "project.leaderMissing": "У проекта «{name}» нет сеанса Leader, который можно открыть. Замените Leader проекта.",
1116
+ "project.leaderOpenFailed": "Не удалось открыть сеанс Leader проекта «{name}»: {message}",
1103
1117
  "project.more": "Ещё",
1104
1118
  "project.name.empty": "Название проекта не может быть пустым",
1105
1119
  "project.name.tooLong": "Название проекта слишком длинное (не более {max} символов)",
@@ -1260,7 +1274,9 @@ export const LOCALE_UI = Object.freeze({
1260
1274
  "project.expandSessions": "展开会话",
1261
1275
  "project.label": "项目",
1262
1276
  "project.leaderDeleted": "项目「{name}」的 leader 会话已被删除,请换新 Leader。",
1277
+ "project.leaderLoading": "Leader 会话还在加载,正在重试…",
1263
1278
  "project.leaderMissing": "项目「{name}」没有可打开的 leader 会话,请换新 Leader。",
1279
+ "project.leaderOpenFailed": "打开项目「{name}」的 Leader 会话失败:{message}",
1264
1280
  "project.more": "更多",
1265
1281
  "project.name.empty": "项目名不能为空",
1266
1282
  "project.name.tooLong": "项目名过长(上限 {max} 字)",
@@ -9,6 +9,51 @@
9
9
 
10
10
  import { MAX_PROJECT_NAME_LENGTH } from '../shared/projects.js'
11
11
  import { isRetiredLeaderSession } from './project-board-data.js'
12
+ import { isUnknownSessionError } from './slot-retain.js'
13
+
14
+ /** 宿主 catalog 未就绪时的递增重试间隔;3 次重试、4 次尝试。 */
15
+ const OPEN_RETRY_DELAYS_MS = [200, 500, 1000]
16
+
17
+ /** 默认延迟实现;测试传 `wait` 注入,避免真等。 */
18
+ function waitForRetry(ms) {
19
+ return new Promise((resolve) => { setTimeout(resolve, ms) })
20
+ }
21
+
22
+ /**
23
+ * 按 key 防重入的打开锁。
24
+ *
25
+ * 同一个项目连点时只能有一条重试链;否则两组 unknown 重试叠加,后一组失败还会
26
+ * 在成功之后弹失败 toast。锁由调用方在 finally 释放。
27
+ *
28
+ * @returns {{ begin: (key: string) => boolean, end: (key: string) => void, has: (key: string) => boolean }}
29
+ */
30
+ export function createInFlightGuard() {
31
+ const active = new Set()
32
+ return {
33
+ /**
34
+ * @param {string} key - 项目 id
35
+ * @returns {boolean} 是否拿到锁;已在飞时返回 false
36
+ */
37
+ begin(key) {
38
+ if (active.has(key)) return false
39
+ active.add(key)
40
+ return true
41
+ },
42
+ /**
43
+ * @param {string} key - 项目 id
44
+ */
45
+ end(key) {
46
+ active.delete(key)
47
+ },
48
+ /**
49
+ * @param {string} key - 项目 id
50
+ * @returns {boolean} 当前是否在飞
51
+ */
52
+ has(key) {
53
+ return active.has(key)
54
+ },
55
+ }
56
+ }
12
57
 
13
58
  export { MAX_PROJECT_NAME_LENGTH }
14
59
 
@@ -328,15 +373,37 @@ export function isArchiveActiveRefusal(reason) {
328
373
  * @param {object} options.project - 项目
329
374
  * @param {(sessionId: string) => void} options.openSession - 打开会话
330
375
  * @param {(key: string, params?: Record<string, unknown>) => string} options.t - 当前语言的翻译函数
331
- * @returns {{ok: boolean, message?: string}} 打开结果
376
+ * @param {(ms: number) => Promise<void>} [options.wait] - 延迟函数,测试可注入
377
+ * @param {number[]} [options.retryDelaysMs] - 未知会话的递增重试间隔,默认 200/500/1000ms
378
+ * @param {(attempt: number, delayMs: number) => void} [options.onRetry] - 每次重试前的 UI 通知
379
+ * @returns {Promise<{ok: boolean, message?: string}>} 打开结果
332
380
  */
333
- export function openLeaderSession({ project, openSession, t }) {
381
+ export async function openLeaderSession({
382
+ project,
383
+ openSession,
384
+ t,
385
+ wait = waitForRetry,
386
+ retryDelaysMs = OPEN_RETRY_DELAYS_MS,
387
+ onRetry = () => {},
388
+ }) {
334
389
  const sessionId = project?.leaderSessionId
335
390
  if (typeof sessionId !== 'string' || sessionId === '') {
336
391
  return { ok: false, message: t('project.leaderMissing', { name: project?.name ?? '' }) }
337
392
  }
338
- openSession(sessionId)
339
- return { ok: true }
393
+ for (let attempt = 0; ; attempt += 1) {
394
+ try {
395
+ openSession(sessionId)
396
+ return { ok: true }
397
+ } catch (error) {
398
+ // 宿主 session catalog 还在加载时 openSession 会同步抛 unknown;负载下这个
399
+ // 窗口会变长,重试到目录就绪,别的错误仍然直接暴露。
400
+ if (!isUnknownSessionError(error)) throw error
401
+ if (attempt >= retryDelaysMs.length) throw error
402
+ const delayMs = retryDelaysMs[attempt]
403
+ onRetry(attempt + 1, delayMs)
404
+ await wait(delayMs)
405
+ }
406
+ }
340
407
  }
341
408
 
342
409
  /**
@@ -38,6 +38,7 @@ import { productIcon } from './icons.js'
38
38
  import {
39
39
  classifyDeletionResult,
40
40
  collectExcludedSessionIds,
41
+ createInFlightGuard,
41
42
  createWriteQueue,
42
43
  currentSessionIdOf,
43
44
  defaultProjectName,
@@ -204,6 +205,7 @@ export function ProjectPanel(props) {
204
205
  // 被反复重置。经 ref 解引用:订阅只在挂载时建立一次,取值永远走最新一份。
205
206
  const sessionsRef = useRef(getSessions)
206
207
  sessionsRef.current = getSessions
208
+ const openingProjects = useRef(createInFlightGuard())
207
209
  const refreshIndexRef = useRef(refreshSessionIndex)
208
210
  refreshIndexRef.current = refreshSessionIndex
209
211
 
@@ -521,13 +523,28 @@ export function ProjectPanel(props) {
521
523
  showToast(t('project.error.navigation'))
522
524
  return
523
525
  }
524
- // 项目不碰 dsh 工作区:点项目行只是打开那条会话,不给它分组、也不改用户的工作区。
525
- const result = openLeaderSession({
526
- project,
527
- openSession: (sessionId) => uiWorkspace.openSession(sessionId),
528
- t,
529
- })
530
- if (result.ok !== true) showToast(result.message)
526
+ if (!openingProjects.current.begin(project.id)) return
527
+ try {
528
+ // 项目不碰 dsh 工作区:点项目行只是打开那条会话,不给它分组、也不改用户的工作区。
529
+ const result = await openLeaderSession({
530
+ project,
531
+ openSession: (sessionId) => uiWorkspace.openSession(sessionId),
532
+ t,
533
+ onRetry: () => showToast(t('project.leaderLoading', { name: project.name })),
534
+ })
535
+ if (result.ok !== true) showToast(result.message)
536
+ } catch (error) {
537
+ // 重试用尽或非 unknown 的宿主错误:用户要看见失败原因,不能点完没反应;
538
+ // console.error 同时让 e2e 的 watchProblems 保持 fail-loud。
539
+ const message = t('project.leaderOpenFailed', {
540
+ name: project.name,
541
+ message: error instanceof Error ? error.message : String(error),
542
+ })
543
+ console.error(message, error)
544
+ showToast(message)
545
+ } finally {
546
+ openingProjects.current.end(project.id)
547
+ }
531
548
  }, [getUiWorkspace, t])
532
549
 
533
550
  const renameProject = useCallback(async (project, name) => {
@@ -8,45 +8,31 @@
8
8
  * 这里把生命周期从 React 里拆出来,是为了能对配对关系直接断言——面板组件只负责
9
9
  * 把状态读数交给宿主,保留与释放的账本由本模块记。
10
10
  *
11
+ * 保留目标只接受宿主自己解析出的地址(`sessions.retain(id)` 或宿主给出的
12
+ * 子代理地址)。本模块**不构造**父子地址:编出来的地址会被宿主当成子代理,
13
+ * 之后每次读历史都按子代理校验,根会话一律被拒(`subagent/unauthorized`)。
14
+ *
11
15
  * @module dsh-leader-agent/client/slot-retain
12
16
  */
13
17
 
14
- /**
15
- * 槽位会话的保留目标。
16
- *
17
- * 有些会话在客户端会话目录里没有独立条目,裸 id 认不出来,要靠
18
- * `{ parentSessionId, childSessionId }` 地址才找得到——历史 subagent 时代的
19
- * worker 就是这一类(现在的 worker 是普通根会话,通常有独立条目)。宿主给了地址
20
- * 就用它;没给时用建卡会话兜一个 `unknown` 模式的地址——模式只影响宿主怎么配置
21
- * 子代理,不影响能不能认出这个会话。
22
- *
23
- * 两者都拿不到时返回 `undefined`,调用方据此把原始错误抛回去,不要静默降级。
24
- *
25
- * @param {object} sessions - 会话服务
26
- * @param {string} sessionId - 槽位绑定的会话 id
27
- * @param {string} fatherSessionId - 建卡会话 id,作为父会话兜底
28
- * @returns {object | undefined} `SubagentAddress` 或 `undefined`
29
- */
30
- export function retainTargetOf(sessions, sessionId, fatherSessionId) {
31
- const address = typeof sessions.subagentAddress === 'function'
32
- ? sessions.subagentAddress(sessionId)
33
- : undefined
34
- if (address !== undefined) return address
35
- if (typeof fatherSessionId !== 'string' || fatherSessionId === '') return undefined
36
- return { parentSessionId: fatherSessionId, childSessionId: sessionId, mode: 'unknown' }
37
- }
18
+ /** 宿主对「客户端目录里还没有这个会话」的固定错误前缀。 */
19
+ const UNKNOWN_SESSION_PREFIX = 'sessions.retain: unknown session '
20
+
21
+ /** 冷启动时宿主会话目录可能比看板晚就绪,未知会话默认再等几拍。 */
22
+ const DEFAULT_RETRY_DELAY_MS = 2000
23
+ const DEFAULT_RETRY_ATTEMPTS = 3
38
24
 
39
25
  /**
40
26
  * 宿主认不出会话 id 时的固定错误。
41
27
  *
42
- * 只吞这一类:已删除、从未存在或地址解析不出的会话。其它错误照抛,保留器的
43
- * 同步调用在 React effect 里,吞掉全部异常会把真正的宿主故障藏成空心圈。
28
+ * 只吞这一类:已删除、从未存在或客户端目录尚未就绪的会话。其它错误照抛,
29
+ * 保留器的同步调用在 React effect 里,吞掉全部异常会把真正的宿主故障藏成空心圈。
44
30
  *
45
31
  * @param {unknown} error - 捕获到的异常
46
32
  * @returns {boolean} 是否宿主「未知会话」错误
47
33
  */
48
34
  export function isUnknownSessionError(error) {
49
- return error instanceof Error && error.message.startsWith('sessions.retain: unknown session ')
35
+ return error instanceof Error && error.message.startsWith(UNKNOWN_SESSION_PREFIX)
50
36
  }
51
37
 
52
38
  export class SlotRetention {
@@ -58,16 +44,31 @@ export class SlotRetention {
58
44
  * 快照时的回调
59
45
  * @param {(sessionId: string) => void} options.onDrop - 会话不再被保留时的回调
60
46
  * @param {(message: string) => void} [options.onError] - 保留失败时的报告出口
47
+ * @param {number} [options.retryDelayMs] - 未知会话的重试间隔
48
+ * @param {number} [options.retryAttempts] - 未知会话的重试次数(不含首次)
61
49
  */
62
- constructor({ retain, onState, onDrop, onError }) {
50
+ constructor({
51
+ retain,
52
+ onState,
53
+ onDrop,
54
+ onError,
55
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS,
56
+ retryAttempts = DEFAULT_RETRY_ATTEMPTS,
57
+ }) {
63
58
  this.retain = retain
64
59
  this.onState = onState
65
60
  this.onDrop = onDrop
66
61
  this.onError = onError ?? ((message) => console.warn(message))
62
+ this.retryDelayMs = retryDelayMs
63
+ this.retryAttempts = retryAttempts
67
64
  /** @type {Map<string, { reference: object, unsubscribe?: () => void }>} */
68
65
  this.entries = new Map()
69
66
  /** 已报告过的失败:同一个槽位只报一次,不随每次同步重复刷。 */
70
67
  this.reported = new Set()
68
+ /** @type {Map<string, ReturnType<typeof setTimeout>>} 待跑的未知会话重试。 */
69
+ this.timers = new Map()
70
+ /** @type {Map<string, number>} 每个会话已用掉的未知会话重试次数。 */
71
+ this.retries = new Map()
71
72
  /** 卸载后即使迟到的 effect 再同步,也不能重新保留会话。 */
72
73
  this.disposed = false
73
74
  }
@@ -85,8 +86,11 @@ export class SlotRetention {
85
86
  if (needed.has(sessionId)) continue
86
87
  this.drop(sessionId, entry)
87
88
  }
89
+ for (const sessionId of this.timers.keys()) {
90
+ if (!needed.has(sessionId)) this.cancelRetry(sessionId)
91
+ }
88
92
  for (const sessionId of needed) {
89
- if (this.entries.has(sessionId)) continue
93
+ if (this.entries.has(sessionId) || this.timers.has(sessionId)) continue
90
94
  this.hold(sessionId)
91
95
  }
92
96
  }
@@ -94,23 +98,29 @@ export class SlotRetention {
94
98
  /**
95
99
  * 保留一个会话。
96
100
  *
97
- * 宿主不认识这个会话 id 时同步抛错——状态保持未知,不谎称空闲。
101
+ * 宿主还不认识这个会话 id 时不放弃:冷启动时宿主会话目录常比看板晚一拍,
102
+ * 按 `retryDelayMs` 重试有限次,用尽才报「状态未知」。宿主明确拒绝的其它错误
103
+ * 同步抛出。
98
104
  *
99
105
  * @param {string} sessionId - 会话 id
100
106
  */
101
107
  hold(sessionId) {
102
- if (this.disposed) return
108
+ if (this.disposed || this.entries.has(sessionId) || this.timers.has(sessionId)) return
103
109
  let reference
104
110
  try {
105
111
  reference = this.retain(sessionId)
106
112
  } catch (error) {
107
- // 只接住宿主认不出会话这一类;关闭标签后的迟到同步也可能撞上它。
108
- if (!isUnknownSessionError(error)) throw error
109
- // 宿主不认识这个会话(已删、从未存在、或地址解析不出):状态保持未知,
110
- // 不谎称空闲。这条要说出来——槽位上只表现为一个空心圈,没有日志就查不到。
111
- this.report(sessionId, `看板无法保留会话 ${sessionId},槽位状态未知:${error.message}`)
113
+ // 单个槽位的保留失败不能把整块看板从 React effect 里抛掉:宿主拒一条
114
+ // 地址(例如热更前残留的旧子代理地址)会让所有卡片一起消失。真实故障
115
+ // 仍经 onError 报出来,不静默。未知会话是宿主目录还没就绪,按次重试。
116
+ if (isUnknownSessionError(error)) {
117
+ this.scheduleRetry(sessionId, error)
118
+ return
119
+ }
120
+ this.report(sessionId, `看板无法保留会话 ${sessionId},槽位状态未知:${error instanceof Error ? error.message : String(error)}`)
112
121
  return
113
122
  }
123
+ this.retries.delete(sessionId)
114
124
  const entry = { reference, unsubscribe: undefined }
115
125
  this.entries.set(sessionId, entry)
116
126
  reference.ready
@@ -133,6 +143,46 @@ export class SlotRetention {
133
143
  })
134
144
  }
135
145
 
146
+ /**
147
+ * 安排一次未知会话重试;次数用尽时报告一次并放弃。
148
+ *
149
+ * @param {string} sessionId - 会话 id
150
+ * @param {Error} error - 宿主抛出的未知会话错误
151
+ */
152
+ scheduleRetry(sessionId, error) {
153
+ const used = this.retries.get(sessionId) ?? 0
154
+ if (used >= this.retryAttempts) {
155
+ this.retries.delete(sessionId)
156
+ // 宿主不认识这个会话(已删、从未存在、或地址解析不出):状态保持未知,
157
+ // 不谎称空闲。这条要说出来——槽位上只表现为一个空心圈,没有日志就查不到。
158
+ this.report(sessionId, `看板无法保留会话 ${sessionId},槽位状态未知:${error.message}`)
159
+ return
160
+ }
161
+ this.retries.set(sessionId, used + 1)
162
+ const timer = setTimeout(() => {
163
+ this.timers.delete(sessionId)
164
+ if (this.disposed) return
165
+ this.hold(sessionId)
166
+ }, this.retryDelayMs)
167
+ // 定时器不应该单独把宿主进程吊住(Node 侧单测与 headless 场景)。
168
+ timer.unref?.()
169
+ this.timers.set(sessionId, timer)
170
+ }
171
+
172
+ /**
173
+ * 取消一个会话待跑的重试并清掉计数。
174
+ *
175
+ * @param {string} sessionId - 会话 id
176
+ */
177
+ cancelRetry(sessionId) {
178
+ const timer = this.timers.get(sessionId)
179
+ if (timer !== undefined) {
180
+ clearTimeout(timer)
181
+ this.timers.delete(sessionId)
182
+ }
183
+ this.retries.delete(sessionId)
184
+ }
185
+
136
186
  /**
137
187
  * 报告一次保留失败,同一个会话只报一次。
138
188
  * @param {string} sessionId - 会话 id
@@ -151,6 +201,7 @@ export class SlotRetention {
151
201
  * @param {object} [entry] - 该会话的记录,缺省时取当前记录
152
202
  */
153
203
  drop(sessionId, entry = this.entries.get(sessionId)) {
204
+ this.cancelRetry(sessionId)
154
205
  if (entry === undefined) return
155
206
  if (this.entries.get(sessionId) === entry) this.entries.delete(sessionId)
156
207
  entry.unsubscribe?.()
@@ -166,6 +217,8 @@ export class SlotRetention {
166
217
  dispose() {
167
218
  if (this.disposed) return
168
219
  this.disposed = true
220
+ for (const sessionId of this.timers.keys()) this.cancelRetry(sessionId)
221
+ this.retries.clear()
169
222
  for (const entry of this.entries.values()) {
170
223
  entry.unsubscribe?.()
171
224
  entry.reference.release()