sessionsIndexStore.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. /* eslint-disable max-lines -- index projection、applied-base 与 recovery flight 必须由同一原子 store 裁决。 */
  2. // sessions-index topic 的 renderer 只读 store:
  3. // snapshot 帧全量替换;delta 帧仅在区间衔接(frame.fromSeq === watermark)时 apply,
  4. // 断档不猜、不缓存补偿——重订阅交由服务端裁决续传或全量(与 ConversationProjectionStore 同策略)。
  5. import {
  6. isDeterministicContentFault,
  7. PROTOCOL_V4_LIMITS,
  8. SUBSCRIPTION_CONTENT_REJECTED,
  9. type SessionSummary,
  10. type SessionsIndexTopicFrame,
  11. type TopicFrameDeliveryKind,
  12. } from "@zcode/shared/zcode-protocol-v4";
  13. import { isZCodeFileLockTimeoutError } from "@zcode/shared";
  14. import { ZCODE_AGENT_RUNTIME_UNAVAILABLE_CODE } from "@zcode/services";
  15. import { logger } from "@/logger.js";
  16. import type { SessionsIndexTransport } from "@/v4/agentSessionsIndexTransport.js";
  17. export interface SessionsIndexState {
  18. /** workspaceId → 已知;null = 尚无 snapshot。 */
  19. workspaceId: string | null;
  20. logEpoch: string | null;
  21. /** 帧区间水位(= 最近一帧 toSeq)。 */
  22. seq: number;
  23. /** 会话摘要,按 sessionId 索引(conflated)。 */
  24. sessions: Map<string, SessionSummary>;
  25. }
  26. export const EMPTY_SESSIONS_INDEX_STATE: SessionsIndexState = {
  27. workspaceId: null,
  28. logEpoch: null,
  29. seq: 0,
  30. sessions: new Map(),
  31. };
  32. export type SessionsIndexStoreStatus = "idle" | "dormant" | "connecting" | "live" | "error";
  33. const RUNTIME_RESTART_RECONNECT_BASE_DELAY_MS = 100;
  34. const RUNTIME_RESTART_RECONNECT_MAX_DELAY_MS = 5_000;
  35. const RUNTIME_RESTART_BURST_RESET_MS = 30_000;
  36. const TRANSIENT_SUBSCRIBE_RETRY_DELAYS_MS = [250, 1_000, 3_000] as const;
  37. const ERROR_RECOVERY_RETRY_DELAYS_MS = [5_000, 15_000, 60_000] as const;
  38. function isTransientSubscribeError(error: unknown): boolean {
  39. if (isZCodeFileLockTimeoutError(error)) {
  40. return true;
  41. }
  42. const code =
  43. typeof error === "object" && error !== null && "code" in error
  44. ? String((error as { code?: unknown }).code ?? "")
  45. : "";
  46. const message = error instanceof Error ? error.message : String(error);
  47. if (["EBUSY", "EMFILE", "ENFILE"].includes(code)) {
  48. return true;
  49. }
  50. if (code === "EEXIST" && message.includes("config.json.lock")) {
  51. return true;
  52. }
  53. return /\b(?:EBUSY|EMFILE|ENFILE)\b/.test(message) || message.includes("config.json.lock");
  54. }
  55. function isRuntimeUnavailableError(error: unknown): boolean {
  56. return (
  57. typeof error === "object" &&
  58. error !== null &&
  59. "code" in error &&
  60. (error as { code?: unknown }).code === ZCODE_AGENT_RUNTIME_UNAVAILABLE_CODE
  61. );
  62. }
  63. async function unsubscribeIgnoringFailure(
  64. transport: SessionsIndexTransport,
  65. subscriptionId: string,
  66. ): Promise<void> {
  67. try {
  68. await transport.unsubscribe(subscriptionId);
  69. } catch (error) {
  70. // service proxy 换代后旧 store cleanup 仍会命中已断开的 RPC。
  71. // cleanup 失败不能变成 unhandled rejection,也不能影响新一代 registry entry。
  72. logger.warn(
  73. `[v4-sessions-index] unsubscribe ${subscriptionId} 失败(忽略): ${
  74. error instanceof Error ? error.message : String(error)
  75. }`,
  76. );
  77. }
  78. }
  79. export interface ApplySessionsIndexResult {
  80. state: SessionsIndexState;
  81. /** true = 帧区间断档(fromSeq 与水位不衔接),调用方应重订阅。 */
  82. gap: boolean;
  83. }
  84. /** 纯 apply:snapshot 全量替换;deltas 仅在衔接时逐条 upsert/remove。 */
  85. export function applySessionsIndexFrame(
  86. current: SessionsIndexState,
  87. frame: SessionsIndexTopicFrame,
  88. ): ApplySessionsIndexResult {
  89. if (frame.payload.kind === "snapshot") {
  90. const snapshot = frame.payload.snapshot;
  91. const sessions = new Map<string, SessionSummary>();
  92. for (const session of snapshot.sessions) {
  93. sessions.set(session.sessionId, session);
  94. }
  95. return {
  96. gap: false,
  97. state: {
  98. workspaceId: snapshot.workspaceId,
  99. logEpoch: snapshot.logEpoch,
  100. seq: frame.toSeq,
  101. sessions,
  102. },
  103. };
  104. }
  105. if (frame.toSeq <= current.seq) {
  106. return { state: current, gap: false };
  107. }
  108. // deltas:区间必须衔接(fromSeq === 当前水位),否则断档。
  109. if (frame.fromSeq !== current.seq) {
  110. return { state: current, gap: true };
  111. }
  112. const sessions = new Map(current.sessions);
  113. for (const delta of frame.payload.deltas) {
  114. if (delta.op === "session.upserted") {
  115. sessions.set(delta.session.sessionId, delta.session);
  116. } else {
  117. sessions.delete(delta.sessionId);
  118. }
  119. }
  120. return {
  121. gap: false,
  122. state: { ...current, seq: frame.toSeq, sessions },
  123. };
  124. }
  125. /**
  126. * useSyncExternalStore 兼容的只读 store:subscribe + getState 返回稳定引用。
  127. * 状态本体与纯 applyFrame 可独立单测;传输绑定(connect/handleFrame/close)
  128. * 负责订阅生命周期与断档重订阅。
  129. */
  130. export class SessionsIndexStore {
  131. private state: SessionsIndexState = EMPTY_SESSIONS_INDEX_STATE;
  132. private readonly listeners = new Set<() => void>();
  133. /** 缓存的有序列表(getSessions 稳定引用,避免每次 new array 触发重渲染)。 */
  134. private cachedList: SessionSummary[] | null = null;
  135. // 传输绑定(可选:纯 applyFrame 单测不需要)。
  136. private transport: SessionsIndexTransport | null = null;
  137. private frameUnsub: (() => void) | null = null;
  138. private faultUnsub: (() => void) | null = null;
  139. private restartUnsub: (() => void) | null = null;
  140. private lifecycleUnsub: (() => void) | null = null;
  141. private subscriptionId: string | null = null;
  142. private awaitingInitial: { subscriptionId: string; mode: "snapshot" | "resume" } | null = null;
  143. private subscriptionHasAppliedBase = false;
  144. private recovery: {
  145. subscriptionId: string;
  146. requestInFlight: boolean;
  147. ackReceived: boolean;
  148. validFrameSeen: boolean;
  149. upgradePending: boolean;
  150. ackMode: "snapshot" | "resume" | null;
  151. forceSnapshot: boolean;
  152. postRecoveryGapPending: boolean;
  153. frameDeadline: ReturnType<typeof setTimeout> | null;
  154. /** 本次 flight 是为内容确定性失败发起的:终态用 contentRejected,且不再无限退避重订阅。 */
  155. contentFault: boolean;
  156. } | null = null;
  157. private status: SessionsIndexStoreStatus = "idle";
  158. private generation = 0;
  159. private closed = false;
  160. private runtimeRestartReconnectTimer: ReturnType<typeof setTimeout> | null = null;
  161. private runtimeRestartBurstCount = 0;
  162. private lastRuntimeRestartAt = 0;
  163. private subscribeRetryTimer: ReturnType<typeof setTimeout> | null = null;
  164. private errorRecoveryRetryTimer: ReturnType<typeof setTimeout> | null = null;
  165. private errorRecoveryRetryAttempt = 0;
  166. subscribe = (listener: () => void): (() => void) => {
  167. this.listeners.add(listener);
  168. return () => {
  169. this.listeners.delete(listener);
  170. };
  171. };
  172. getState = (): SessionsIndexState => this.state;
  173. getStatus(): SessionsIndexStoreStatus {
  174. return this.status;
  175. }
  176. /**
  177. * 绑定传输并发起订阅:注册帧监听 + subscribe(水位不变量:仅当真持有一致状态才带 base)。
  178. * 断档帧 → 丢 base 重订阅(handleFrame 触发)。close 后可再次 connect(React
  179. * effect 卸载/重挂载——StrictMode 双调——走同一路径复活)。
  180. */
  181. async connect(
  182. transport: SessionsIndexTransport,
  183. options: {
  184. forceSnapshot?: boolean;
  185. initialOverflowRetry?: boolean;
  186. subscribeRetryAttempt?: number;
  187. errorRecoveryRetryAttempt?: number;
  188. } = {},
  189. ): Promise<void> {
  190. if (this.runtimeRestartReconnectTimer) {
  191. clearTimeout(this.runtimeRestartReconnectTimer);
  192. this.runtimeRestartReconnectTimer = null;
  193. }
  194. this.clearSubscribeRetry();
  195. if (options.errorRecoveryRetryAttempt === undefined) {
  196. this.clearErrorRecoveryRetry();
  197. this.errorRecoveryRetryAttempt = 0;
  198. }
  199. this.closed = false;
  200. this.transport = transport;
  201. if (!this.frameUnsub) {
  202. this.frameUnsub = transport.onFrame((frame, context) => this.handleFrame(frame, context));
  203. this.faultUnsub = transport.onAssemblyFault((fault) => {
  204. if (fault.subscriptionId === this.subscriptionId) {
  205. this.handleAssemblyFault(fault.subscriptionId, fault.deliveryKind, fault.reasonCode);
  206. }
  207. });
  208. if (transport.onRuntimeLifecycle) {
  209. this.lifecycleUnsub = transport.onRuntimeLifecycle((state) => {
  210. if (state === "available") this.handleRuntimeAvailable();
  211. else this.handleRuntimeUnavailable();
  212. });
  213. } else {
  214. this.restartUnsub = transport.onRuntimeRestart(() => this.handleRuntimeRestart());
  215. }
  216. }
  217. const generation = ++this.generation;
  218. this.discardRecovery();
  219. this.status = "connecting";
  220. this.emit();
  221. const base =
  222. options.forceSnapshot || this.state.logEpoch === null
  223. ? undefined
  224. : { logEpoch: this.state.logEpoch, seq: this.state.seq };
  225. try {
  226. const result = await transport.subscribe(base ? { base } : {});
  227. if (generation !== this.generation || this.closed) {
  228. void unsubscribeIgnoringFailure(transport, result.ack.subscriptionId);
  229. return;
  230. }
  231. // 与 conversationProjectionStore.connect 同因(线上 notOwned 卡死):
  232. // subscribe ACK 的 await 窗口内旧订阅仍可能创建 same-sub recovery,而 host scope 在
  233. // 新 ACK remember() 时已静默驱逐旧 ownership。换代成功即丢弃旧 recovery,避免其
  234. // 迟到失败把 live 的新订阅打成 error。
  235. this.discardRecovery();
  236. this.subscriptionId = result.ack.subscriptionId;
  237. this.status = "live";
  238. this.clearErrorRecoveryRetry();
  239. this.errorRecoveryRetryAttempt = 0;
  240. this.subscriptionHasAppliedBase = Boolean(
  241. base && result.ack.mode === "resume" && result.ack.logEpoch === base.logEpoch,
  242. );
  243. this.awaitingInitial = {
  244. subscriptionId: result.ack.subscriptionId,
  245. mode: result.ack.mode,
  246. };
  247. // initial 只经 notification 到达;先绑定代际,再 activate 释放 ACK 前早帧。
  248. transport.activate(result.ack.subscriptionId);
  249. this.emit();
  250. } catch (error) {
  251. if (generation !== this.generation || this.closed) return;
  252. this.awaitingInitial = null;
  253. this.subscriptionHasAppliedBase = false;
  254. if (isRuntimeUnavailableError(error)) {
  255. // restored workspace 的被动列表订阅曾把 runtime 缺失当成普通失败并
  256. // 退避重试,最终由 getClient 批量启动 CLI。dormant 等待 lifecycle,不设 timer。
  257. this.handleRuntimeUnavailable();
  258. return;
  259. }
  260. const message = error instanceof Error ? error.message : String(error);
  261. if (
  262. message.includes("fault.subscription.initialFrameStagingOverflow") &&
  263. !options.initialOverflowRetry
  264. ) {
  265. await this.connect(transport, {
  266. forceSnapshot: true,
  267. initialOverflowRetry: true,
  268. ...(options.errorRecoveryRetryAttempt !== undefined
  269. ? { errorRecoveryRetryAttempt: options.errorRecoveryRetryAttempt }
  270. : {}),
  271. });
  272. return;
  273. }
  274. const retryAttempt = options.subscribeRetryAttempt ?? 0;
  275. const retryDelay = TRANSIENT_SUBSCRIBE_RETRY_DELAYS_MS[retryAttempt];
  276. if (isTransientSubscribeError(error) && retryDelay !== undefined) {
  277. // Host 冷启动时 provider registry 的配置锁可能短暂冲突。若把
  278. // 首次 subscribe 失败永久定格为 error,聚合层随即发布空列表并显示“还没有对话”。
  279. // 瞬时文件锁错误保持 hydrating,用有界退避重订阅;已有 snapshot 也继续保留。
  280. this.status = "connecting";
  281. logger.warn(`[v4-sessions-index] subscribe 瞬时失败,${retryDelay}ms 后重试: ${message}`);
  282. this.subscribeRetryTimer = setTimeout(() => {
  283. this.subscribeRetryTimer = null;
  284. if (this.closed || generation !== this.generation) return;
  285. void this.connect(transport, {
  286. ...(options.forceSnapshot ? { forceSnapshot: true } : {}),
  287. subscribeRetryAttempt: retryAttempt + 1,
  288. ...(options.errorRecoveryRetryAttempt !== undefined
  289. ? { errorRecoveryRetryAttempt: options.errorRecoveryRetryAttempt }
  290. : {}),
  291. });
  292. }, retryDelay);
  293. this.emit();
  294. return;
  295. }
  296. this.failAndScheduleRecovery(`subscribe:${message}`);
  297. }
  298. }
  299. /**
  300. * 远程 RPC proxy 换代时原地替换 transport。
  301. *
  302. * 先同步解除旧 transport 的本地监听,再对新 transport 强制取 snapshot;远端退订只做
  303. * best-effort,不能阻塞新 proxy 接管。服务端按 subscriptionId 精确退订,迟到 cleanup
  304. * 不会删除新代际。并发换代由 store generation 失效旧结果,store 身份和最后一份投影保持不变。
  305. */
  306. async replaceTransport(transport: SessionsIndexTransport): Promise<void> {
  307. if (!this.closed && this.transport === transport) return;
  308. const generation = ++this.generation;
  309. const previous = this.detachTransport();
  310. this.status = "connecting";
  311. this.emit();
  312. if (previous.transport && previous.subscriptionId) {
  313. // proxy handoff 后旧 RPC 可能永远不 settle;等待它会让新 transport
  314. // 永久停在 connecting。先完成本地 detach,远端精确退订异步收尾即可。
  315. void unsubscribeIgnoringFailure(previous.transport, previous.subscriptionId);
  316. }
  317. if (generation !== this.generation || this.closed) return;
  318. await this.connect(transport, { forceSnapshot: true });
  319. }
  320. /** 帧路由入口(initial / online notification)。断档 → 重订阅。 */
  321. handleFrame(
  322. frame: SessionsIndexTopicFrame,
  323. delivery?: { deliveryKind: TopicFrameDeliveryKind },
  324. ): void {
  325. if (this.closed) return;
  326. // 代际闸门:workspace 级 fan-out 会把同 topic 其他订阅者的帧也送到这里
  327. // (host 侧 task-index syncer 用独立 connectionId 常驻订阅 sessions-index)。
  328. // 不按自己的 subscriptionId 过滤会把别人的 (fromSeq, toSeq] 窗口当成断档,触发重订阅风暴。
  329. // subscriptionId 尚未就位时的 own initial 由 transport 有界 staging;绑定后 activate
  330. // 才释放。其他旧代际/foreign frame 在这里继续丢弃。
  331. if (this.subscriptionId === null || frame.subscriptionId !== this.subscriptionId) {
  332. return;
  333. }
  334. const awaitingInitial =
  335. this.awaitingInitial?.subscriptionId === frame.subscriptionId ? this.awaitingInitial : null;
  336. const deliveryKind = delivery?.deliveryKind ?? "online";
  337. const initial = deliveryKind === "initial" ? awaitingInitial : null;
  338. if (initial || (deliveryKind === "recovery" && awaitingInitial)) {
  339. this.awaitingInitial = null;
  340. }
  341. if (deliveryKind === "online" && this.recovery && frame.payload.kind === "snapshot") {
  342. const gap = this.applyFrame(frame);
  343. if (!gap) this.subscriptionHasAppliedBase = true;
  344. return;
  345. }
  346. if (deliveryKind === "online" && this.recovery) {
  347. if (frame.toSeq > this.state.seq) {
  348. this.recovery.postRecoveryGapPending ||= this.recovery.validFrameSeen;
  349. }
  350. return;
  351. }
  352. if (frame.payload.kind === "deltas" && !this.subscriptionHasAppliedBase) {
  353. this.requestRecovery(deliveryKind === "recovery");
  354. return;
  355. }
  356. const gap = this.applyFrame(frame);
  357. if (gap && this.transport) {
  358. logger.warn(
  359. `[v4-sessions-index] 帧断档 fromSeq=${frame.fromSeq} local=${this.state.seq},重订阅`,
  360. );
  361. if (initial) void this.connect(this.transport, { forceSnapshot: true });
  362. else this.requestRecovery(deliveryKind === "recovery");
  363. return;
  364. }
  365. this.subscriptionHasAppliedBase = true;
  366. if (deliveryKind === "recovery") this.markRecoveryFrameSeen();
  367. }
  368. private handleAssemblyFault(
  369. subscriptionId: string,
  370. deliveryKind?: TopicFrameDeliveryKind,
  371. reasonCode?: string,
  372. ): void {
  373. if (subscriptionId !== this.subscriptionId) return;
  374. if (
  375. this.awaitingInitial?.subscriptionId === subscriptionId &&
  376. (deliveryKind === "initial" || deliveryKind === "recovery" || deliveryKind === undefined)
  377. ) {
  378. this.awaitingInitial = null;
  379. }
  380. // 内容确定性失败不进瞬态阶梯(04-sync 封闭规则 11):resume 只会重投同一批被拒的内容。
  381. // 直接跳到唯一可能产出不同字节的强制 snapshot;它再被内容拒绝就停手。本 store 的 fail
  382. // closed 会清空投影并有界退避重订阅——对确定性失败那就是一个永不收敛的重订阅循环。
  383. if (isDeterministicContentFault(reasonCode)) {
  384. this.requestRecovery(true, { contentFault: true });
  385. return;
  386. }
  387. if (deliveryKind === "online" && this.recovery) {
  388. this.recovery.postRecoveryGapPending ||= this.recovery.validFrameSeen;
  389. return;
  390. }
  391. this.requestRecovery(
  392. deliveryKind === "recovery" || (deliveryKind === undefined && this.recovery !== null),
  393. );
  394. }
  395. private requestRecovery(recoveryEvent = false, options: { contentFault?: boolean } = {}): void {
  396. const transport = this.transport;
  397. const subscriptionId = this.subscriptionId;
  398. if (this.closed || !transport || !subscriptionId) return;
  399. const contentFault = options.contentFault === true;
  400. const existing = this.recovery;
  401. if (existing) {
  402. // 一旦本次 flight 出现过内容失败,终态就归内容失败:后续瞬态 fault 不该把它洗白。
  403. if (contentFault) existing.contentFault = true;
  404. if (!recoveryEvent) return;
  405. if (existing.forceSnapshot) {
  406. this.failRecovery("fault.subscription.recoveryFailed");
  407. return;
  408. }
  409. if (existing.requestInFlight || !existing.ackReceived) {
  410. existing.upgradePending = true;
  411. return;
  412. }
  413. if (existing.ackMode === "resume") this.issueRecovery(existing, true);
  414. else this.failRecovery("fault.subscription.recoveryFailed");
  415. return;
  416. }
  417. const recovery = {
  418. subscriptionId,
  419. requestInFlight: false,
  420. ackReceived: false,
  421. validFrameSeen: false,
  422. upgradePending: false,
  423. ackMode: null as "snapshot" | "resume" | null,
  424. forceSnapshot: false,
  425. postRecoveryGapPending: false,
  426. frameDeadline: null,
  427. contentFault,
  428. };
  429. this.recovery = recovery;
  430. // 内容失败跳过 resume 档直接强制 snapshot;瞬态失败仍按原阶梯先试 resume。
  431. this.issueRecovery(recovery, contentFault);
  432. }
  433. private issueRecovery(
  434. recovery: NonNullable<SessionsIndexStore["recovery"]>,
  435. forceSnapshot: boolean,
  436. ): void {
  437. const transport = this.transport;
  438. if (!transport) return;
  439. this.clearRecoveryDeadline(recovery);
  440. const effectiveForceSnapshot = forceSnapshot || !this.subscriptionHasAppliedBase;
  441. recovery.requestInFlight = true;
  442. recovery.ackReceived = false;
  443. recovery.ackMode = null;
  444. recovery.validFrameSeen = false;
  445. recovery.upgradePending = false;
  446. recovery.forceSnapshot = effectiveForceSnapshot;
  447. recovery.postRecoveryGapPending = false;
  448. void transport
  449. .resync({
  450. subscriptionId: recovery.subscriptionId,
  451. base:
  452. !this.subscriptionHasAppliedBase || this.state.logEpoch === null
  453. ? null
  454. : { logEpoch: this.state.logEpoch, seq: this.state.seq },
  455. ...(effectiveForceSnapshot ? { forceSnapshot: true } : {}),
  456. })
  457. .then((result) => {
  458. if (this.closed || this.recovery !== recovery) return;
  459. if (result.ack.subscriptionId !== recovery.subscriptionId) {
  460. throw new Error("fault.subscription.resyncGenerationMismatch");
  461. }
  462. recovery.requestInFlight = false;
  463. recovery.ackReceived = true;
  464. recovery.ackMode = result.ack.mode;
  465. this.settleRecovery(recovery);
  466. })
  467. .catch((error) => {
  468. if (this.closed || this.recovery !== recovery) return;
  469. this.clearRecoveryDeadline(recovery);
  470. this.recovery = null;
  471. const message = error instanceof Error ? error.message : String(error);
  472. logger.warn(`[v4-sessions-index] resync 失败: ${message}`);
  473. if (isRuntimeUnavailableError(error)) {
  474. this.handleRuntimeUnavailable();
  475. return;
  476. }
  477. if (message.includes("fault.subscription.notOwned") && this.transport) {
  478. // 与 conversationProjectionStore.issueRecovery 同因(线上事件):
  479. // notOwned 是 ownership 状态分歧的确定性失效而非瞬态故障,停在 error 会让
  480. // 会话列表永久卡死。携当前水位 fresh subscribe 由服务端裁决 resume/snapshot,
  481. // 完成自愈。仅对 notOwned 特判,避免瞬态错误引发重连风暴。
  482. void this.connect(this.transport);
  483. return;
  484. }
  485. this.failAndScheduleRecovery(`resync:${message}`);
  486. });
  487. }
  488. private markRecoveryFrameSeen(): void {
  489. const recovery = this.recovery;
  490. if (!recovery) return;
  491. recovery.validFrameSeen = true;
  492. this.settleRecovery(recovery);
  493. }
  494. private settleRecovery(recovery: NonNullable<SessionsIndexStore["recovery"]>): void {
  495. if (this.recovery !== recovery || !recovery.ackReceived || recovery.requestInFlight) return;
  496. if (recovery.upgradePending) {
  497. this.clearRecoveryDeadline(recovery);
  498. if (!recovery.forceSnapshot && recovery.ackMode === "resume") {
  499. this.issueRecovery(recovery, true);
  500. } else {
  501. this.failRecovery("fault.subscription.recoveryFailed");
  502. }
  503. return;
  504. }
  505. if (recovery.validFrameSeen) {
  506. this.clearRecoveryDeadline(recovery);
  507. if (recovery.postRecoveryGapPending) this.issueRecovery(recovery, false);
  508. else this.recovery = null;
  509. return;
  510. }
  511. if (recovery.frameDeadline) return;
  512. recovery.frameDeadline = setTimeout(() => {
  513. recovery.frameDeadline = null;
  514. if (this.closed || this.recovery !== recovery || recovery.validFrameSeen) return;
  515. if (!recovery.forceSnapshot) this.issueRecovery(recovery, true);
  516. else
  517. this.failRecovery("fault.subscription.recoveryFrameTimedOut", { contentEligible: false });
  518. }, PROTOCOL_V4_LIMITS.logicalFrameAssemblyTimeoutMs);
  519. }
  520. private clearRecoveryDeadline(recovery: NonNullable<SessionsIndexStore["recovery"]>): void {
  521. if (!recovery.frameDeadline) return;
  522. clearTimeout(recovery.frameDeadline);
  523. recovery.frameDeadline = null;
  524. }
  525. private discardRecovery(): void {
  526. if (this.recovery) this.clearRecoveryDeadline(this.recovery);
  527. this.recovery = null;
  528. }
  529. private clearSubscribeRetry(): void {
  530. if (!this.subscribeRetryTimer) return;
  531. clearTimeout(this.subscribeRetryTimer);
  532. this.subscribeRetryTimer = null;
  533. }
  534. private clearErrorRecoveryRetry(): void {
  535. if (!this.errorRecoveryRetryTimer) return;
  536. clearTimeout(this.errorRecoveryRetryTimer);
  537. this.errorRecoveryRetryTimer = null;
  538. }
  539. /**
  540. * 内容确定性失败:终态 code 与传输失败区分,且**不排退避重订阅**——重订阅会拿到同一份读不懂的
  541. * 内容,本 store 的退避会因此变成永不收敛的循环(清空投影 → 重订阅 → 再被拒 → …)。自愈仍有
  542. * 路径:runtime 换代、fresh connect、用户重连都会重新订阅;被拿掉的只是那个循环。
  543. *
  544. * `contentEligible: false` 给**超时**终态用:deadline 没等到 recovery 帧是传输症状,不该被重标
  545. * 成 contentRejected,更不该因此取消那次仍然有意义的重试。
  546. */
  547. private failRecovery(reasonCode: string, options: { contentEligible?: boolean } = {}): void {
  548. // contentFault 必须在 discardRecovery 之前读。
  549. const contentFault = this.recovery?.contentFault === true && options.contentEligible !== false;
  550. this.failAndScheduleRecovery(contentFault ? SUBSCRIPTION_CONTENT_REJECTED : reasonCode, {
  551. scheduleRetry: !contentFault,
  552. });
  553. }
  554. /**
  555. * recovery/subscribe 失败时撤销旧 projection 的 live 证明,并用有界退避重新取权威
  556. * snapshot。error 仍对外可观测;重试仅在 transport/runtime 仍属于当前代际时执行。
  557. *
  558. * `scheduleRetry: false` 只给确定性失败用:重试必然得到同一结果时不该排它。
  559. */
  560. private failAndScheduleRecovery(
  561. reasonCode: string,
  562. options: { scheduleRetry?: boolean } = {},
  563. ): void {
  564. const transport = this.transport;
  565. const previousSubscriptionId = this.subscriptionId;
  566. this.discardRecovery();
  567. this.subscriptionId = null;
  568. this.awaitingInitial = null;
  569. this.subscriptionHasAppliedBase = false;
  570. this.state = EMPTY_SESSIONS_INDEX_STATE;
  571. this.cachedList = null;
  572. this.status = "error";
  573. logger.warn(`[v4-sessions-index] recovery fail-closed: ${reasonCode}`);
  574. if (transport && previousSubscriptionId) {
  575. void unsubscribeIgnoringFailure(transport, previousSubscriptionId);
  576. }
  577. this.clearErrorRecoveryRetry();
  578. if (transport && !this.closed && options.scheduleRetry !== false) {
  579. const attempt = this.errorRecoveryRetryAttempt;
  580. const delayMs =
  581. ERROR_RECOVERY_RETRY_DELAYS_MS[
  582. Math.min(attempt, ERROR_RECOVERY_RETRY_DELAYS_MS.length - 1)
  583. ];
  584. const nextAttempt = Math.min(attempt + 1, ERROR_RECOVERY_RETRY_DELAYS_MS.length - 1);
  585. const generation = this.generation;
  586. this.errorRecoveryRetryAttempt = nextAttempt;
  587. this.errorRecoveryRetryTimer = setTimeout(() => {
  588. this.errorRecoveryRetryTimer = null;
  589. if (this.closed || this.transport !== transport || this.generation !== generation) {
  590. return;
  591. }
  592. void this.connect(transport, {
  593. forceSnapshot: true,
  594. errorRecoveryRetryAttempt: nextAttempt,
  595. });
  596. }, delayMs);
  597. }
  598. this.emit();
  599. }
  600. private handleRuntimeRestart(): void {
  601. if (this.closed || !this.transport) return;
  602. const transport = this.transport;
  603. const now = Date.now();
  604. if (now - this.lastRuntimeRestartAt >= RUNTIME_RESTART_BURST_RESET_MS) {
  605. this.runtimeRestartBurstCount = 0;
  606. }
  607. this.lastRuntimeRestartAt = now;
  608. const delayMs =
  609. this.runtimeRestartBurstCount === 0
  610. ? 0
  611. : Math.min(
  612. RUNTIME_RESTART_RECONNECT_BASE_DELAY_MS *
  613. 2 ** Math.min(this.runtimeRestartBurstCount - 1, 16),
  614. RUNTIME_RESTART_RECONNECT_MAX_DELAY_MS,
  615. );
  616. this.runtimeRestartBurstCount += 1;
  617. this.generation += 1;
  618. this.clearErrorRecoveryRetry();
  619. this.errorRecoveryRetryAttempt = 0;
  620. this.subscriptionId = null;
  621. this.awaitingInitial = null;
  622. this.discardRecovery();
  623. this.subscriptionHasAppliedBase = false;
  624. if (this.status !== "connecting") {
  625. this.status = "connecting";
  626. this.emit();
  627. }
  628. if (this.runtimeRestartReconnectTimer) {
  629. clearTimeout(this.runtimeRestartReconnectTimer);
  630. }
  631. // runtimeRestarted 不能每到一条就立即 connect。若上游异常地连续发布
  632. // restart,subscribe 会反向触发更多 runtime 启动,形成无上限重连风暴。这里将 burst
  633. // 合并为一次 fresh subscribe,并按连续次数指数退避;稳定 30 秒后恢复首跳立即重连。
  634. this.runtimeRestartReconnectTimer = setTimeout(() => {
  635. this.runtimeRestartReconnectTimer = null;
  636. if (this.closed || this.transport !== transport) return;
  637. void this.connect(transport, { forceSnapshot: true });
  638. }, delayMs);
  639. }
  640. private handleRuntimeAvailable(): void {
  641. if (this.closed || !this.transport) return;
  642. this.handleRuntimeRestart();
  643. }
  644. private handleRuntimeUnavailable(): void {
  645. if (this.closed) return;
  646. this.generation += 1;
  647. this.subscriptionId = null;
  648. this.awaitingInitial = null;
  649. this.discardRecovery();
  650. this.subscriptionHasAppliedBase = false;
  651. this.clearSubscribeRetry();
  652. this.clearErrorRecoveryRetry();
  653. this.errorRecoveryRetryAttempt = 0;
  654. if (this.runtimeRestartReconnectTimer) {
  655. clearTimeout(this.runtimeRestartReconnectTimer);
  656. this.runtimeRestartReconnectTimer = null;
  657. }
  658. // runtime 已不存在时旧 summary 的 running/attention 失去 live 证明;持久 task 行由
  659. // tasks-index 保留,sessions-index 投影必须清空以避免孤儿 spinner。
  660. this.state = EMPTY_SESSIONS_INDEX_STATE;
  661. this.cachedList = null;
  662. this.status = "dormant";
  663. this.emit();
  664. }
  665. /** 释放订阅与监听(组件卸载 / workspace 切换)。 */
  666. close(): void {
  667. this.closed = true;
  668. this.generation += 1;
  669. this.status = "idle";
  670. const previous = this.detachTransport();
  671. if (previous.subscriptionId && previous.transport) {
  672. void unsubscribeIgnoringFailure(previous.transport, previous.subscriptionId);
  673. }
  674. }
  675. private detachTransport(): {
  676. transport: SessionsIndexTransport | null;
  677. subscriptionId: string | null;
  678. } {
  679. const previous = {
  680. transport: this.transport,
  681. subscriptionId: this.subscriptionId,
  682. };
  683. if (this.runtimeRestartReconnectTimer) {
  684. clearTimeout(this.runtimeRestartReconnectTimer);
  685. this.runtimeRestartReconnectTimer = null;
  686. }
  687. this.runtimeRestartBurstCount = 0;
  688. this.lastRuntimeRestartAt = 0;
  689. this.clearSubscribeRetry();
  690. this.clearErrorRecoveryRetry();
  691. this.errorRecoveryRetryAttempt = 0;
  692. this.frameUnsub?.();
  693. this.frameUnsub = null;
  694. this.faultUnsub?.();
  695. this.faultUnsub = null;
  696. this.restartUnsub?.();
  697. this.restartUnsub = null;
  698. this.lifecycleUnsub?.();
  699. this.lifecycleUnsub = null;
  700. this.transport = null;
  701. this.subscriptionId = null;
  702. this.awaitingInitial = null;
  703. this.discardRecovery();
  704. this.subscriptionHasAppliedBase = false;
  705. return previous;
  706. }
  707. /** 应用一帧;断档返回 true(调用方重订阅)。 */
  708. applyFrame(frame: SessionsIndexTopicFrame): boolean {
  709. const { state, gap } = applySessionsIndexFrame(this.state, frame);
  710. if (gap) return true;
  711. if (state !== this.state) {
  712. this.state = state;
  713. this.cachedList = null;
  714. this.emit();
  715. }
  716. return false;
  717. }
  718. /** 断档/重连时清空,等待新 snapshot。 */
  719. reset(): void {
  720. this.discardRecovery();
  721. this.subscriptionHasAppliedBase = false;
  722. this.state = EMPTY_SESSIONS_INDEX_STATE;
  723. this.cachedList = null;
  724. this.emit();
  725. }
  726. /** 会话列表(默认按 lastActivityAt 降序;分组/pin 是更上层逻辑)。 */
  727. getSessions(): SessionSummary[] {
  728. if (this.cachedList === null) {
  729. this.cachedList = [...this.state.sessions.values()].sort(
  730. (a, b) => b.lastActivityAt - a.lastActivityAt,
  731. );
  732. }
  733. return this.cachedList;
  734. }
  735. private emit(): void {
  736. for (const listener of this.listeners) listener();
  737. }
  738. }