@zeniai/client-epic-state 5.2.39 → 5.2.40

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.
@@ -7,6 +7,7 @@ const rootActions_1 = require("../../rootActions");
7
7
  const zeniDayJS_1 = require("../../zeniDayJS");
8
8
  const aiCfoState_1 = require("./aiCfoState");
9
9
  exports.initialAiCfoState = {
10
+ deletedChatSessionIds: [],
10
11
  aiCfoByChatSessionId: {},
11
12
  partialQuestionAnswers: {},
12
13
  syntheticAnswersByChatSessionId: {},
@@ -474,6 +475,11 @@ const toResponseBlockType = (answer, userId) => {
474
475
  createdAt: (0, zeniDayJS_1.date)(timestamp),
475
476
  };
476
477
  };
478
+ // How many deleted session ids to remember. The tombstone only has to outlive
479
+ // an in-flight history request, which is seconds, so this is generous. Capped
480
+ // because `clearSession` would otherwise grow the array for the life of the
481
+ // store and every `setChatHistory` scans it.
482
+ const DELETED_SESSION_MEMORY = 100;
477
483
  const aiCfo = (0, toolkit_1.createSlice)({
478
484
  name: 'aiCfo',
479
485
  initialState: exports.initialAiCfoState,
@@ -495,8 +501,25 @@ const aiCfo = (0, toolkit_1.createSlice)({
495
501
  setSessions(draft, action) {
496
502
  action.payload.forEach((chatSessionPayload) => {
497
503
  const { chat_session_id } = chatSessionPayload;
498
- // This is to prevent overwriting the session if it is already in state
499
- if (draft.aiCfoByChatSessionId[chat_session_id] == null) {
504
+ if (draft.aiCfoByChatSessionId[chat_session_id] != null) {
505
+ // The list is authoritative for a session's metadata, and a session
506
+ // seeded by `setChatHistory` has guessed metadata: no summary, and a
507
+ // `createdAt` taken from one page of a newest-first paginated
508
+ // history, which is later than the session really started.
509
+ // `questionAnswers` is left alone — the list must never wipe a
510
+ // thread that is on screen.
511
+ const entry = draft.aiCfoByChatSessionId[chat_session_id];
512
+ const incoming = toChatSession(chatSessionPayload);
513
+ entry.chatSession = {
514
+ ...incoming,
515
+ // Never downgrade a title already in state: a page of the list can
516
+ // carry a nullish summary, and assigning it wholesale would blank
517
+ // a header that was correct.
518
+ chatSessionSummary: incoming.chatSessionSummary ??
519
+ entry.chatSession.chatSessionSummary,
520
+ };
521
+ }
522
+ else {
500
523
  draft.aiCfoByChatSessionId[chat_session_id] = {
501
524
  chatSession: toChatSession(chatSessionPayload),
502
525
  questionAnswers: [],
@@ -509,8 +532,52 @@ const aiCfo = (0, toolkit_1.createSlice)({
509
532
  setChatHistory(draft, action) {
510
533
  const { chatSessionId, history, isPaginationComplete = false, } = action.payload;
511
534
  if (draft.aiCfoByChatSessionId[chatSessionId] == null) {
512
- console.warn(`session with id ${chatSessionId} not found in setChatHistory`);
513
- return;
535
+ // Sessions created server-side (a routine run) are opened by deep
536
+ // link, so their history can arrive before the sessions list has
537
+ // registered them. Dropping it here loses the messages for good: the
538
+ // response's null page token sets `hasMore: false`, which is the
539
+ // condition the refetch is guarded on. The response is itself proof
540
+ // the session exists, so seed the entry from the messages.
541
+ if (history.length === 0) {
542
+ return;
543
+ }
544
+ // A deleted session. Its history request is never cancelled
545
+ // (`mergeMap`), so seeding would resurrect the conversation into the
546
+ // rail, where clicking it 404s. Only this path is guarded:
547
+ // `clearSession` is optimistic, so if the server still lists the
548
+ // session, `setSessions` re-adding it is correct.
549
+ if (draft.deletedChatSessionIds?.includes(chatSessionId) === true) {
550
+ return;
551
+ }
552
+ // The human's id, taken off a message they actually sent. The API
553
+ // returns newest first, so `history[0]` is usually the agent's reply,
554
+ // and `chatSession.userId` is read as "whose conversation is this".
555
+ const owner = history.find((message) => message.sender === 'user') ?? history[0];
556
+ // Oldest message in the page, not `history[0]`: a session cannot
557
+ // start after its own messages, and the API returns newest first.
558
+ //
559
+ // Compared as instants, not strings. The wire format is an RFC 1123
560
+ // HTTP-date ("Thu, 03 Sep 2026 12:34:56 GMT") because `set_200`
561
+ // bypasses chat's isoformat encoder, and lexically "Mon…" precedes
562
+ // "Sat…" while being the later day. Unparseable values are filtered
563
+ // out, not compared: every comparison against NaN is false, so one
564
+ // used as the reduce's seed would carry through to an Invalid Date.
565
+ const oldest = history
566
+ .map((message) => ({ at: Date.parse(message.created_at), message }))
567
+ .filter(({ at }) => !Number.isNaN(at))
568
+ .reduce((min, entry) => (min == null || entry.at < min.at ? entry : min), undefined)?.message;
569
+ draft.aiCfoByChatSessionId[chatSessionId] = {
570
+ chatSession: {
571
+ chatSessionId,
572
+ userId: owner.user_id,
573
+ chatSessionSummary: undefined,
574
+ // Nothing in the page carried a usable timestamp. "Now" is a
575
+ // guess, but it is a sane one and it keeps the row out of the
576
+ // Invalid-Date behaviour above; the sessions list corrects it.
577
+ createdAt: oldest != null ? (0, zeniDayJS_1.date)(oldest.created_at) : (0, zeniDayJS_1.dateNow)(),
578
+ },
579
+ questionAnswers: [],
580
+ };
514
581
  }
515
582
  const session = draft.aiCfoByChatSessionId[chatSessionId];
516
583
  // Check if we have an existing partial Q&A pair for this session
@@ -790,6 +857,13 @@ const aiCfo = (0, toolkit_1.createSlice)({
790
857
  },
791
858
  clearSession(draft, action) {
792
859
  const sessionId = action.payload;
860
+ draft.deletedChatSessionIds ?? (draft.deletedChatSessionIds = []);
861
+ if (!draft.deletedChatSessionIds.includes(sessionId)) {
862
+ draft.deletedChatSessionIds.push(sessionId);
863
+ if (draft.deletedChatSessionIds.length > DELETED_SESSION_MEMORY) {
864
+ draft.deletedChatSessionIds.splice(0, draft.deletedChatSessionIds.length - DELETED_SESSION_MEMORY);
865
+ }
866
+ }
793
867
  delete draft.aiCfoByChatSessionId[sessionId];
794
868
  delete draft.syntheticAnswersByChatSessionId[sessionId];
795
869
  if (draft.partialQuestionAnswers?.[sessionId] != null) {
@@ -241,4 +241,20 @@ export interface AiCfoState {
241
241
  aiCfoByChatSessionId: Record<ID, ChatSessionWithMessages>;
242
242
  partialQuestionAnswers: Record<ID, AiCfoQuestionWithAnswer | undefined>;
243
243
  syntheticAnswersByChatSessionId: Record<ID, SyntheticAiCfoAnswer[]>;
244
+ /**
245
+ * Sessions this client has deleted. `setChatHistory` seeds an entry for a
246
+ * session it has not seen, so without a tombstone an in-flight history
247
+ * response arriving after the delete would recreate the whole conversation
248
+ * and put the deleted chat back in the rail. `fetchChatHistoryEpic` uses
249
+ * `mergeMap`, so that request is never cancelled. Same race, and the same
250
+ * reasoning, as `deletedScheduleIds` on the view slice. Bounded — it only
251
+ * needs to outlive an in-flight request.
252
+ *
253
+ * Optional because `AiCfoState` is public API of a package four apps
254
+ * consume: making it required turns a bug fix into a compile break for
255
+ * every literal of this type, in this repo and in theirs. The reducer's
256
+ * initial state always sets it, so it is only ever absent on a
257
+ * hand-built literal — which is exactly the case that must keep working.
258
+ */
259
+ deletedChatSessionIds?: ID[];
244
260
  }
@@ -1,8 +1,9 @@
1
1
  import { createSlice } from '@reduxjs/toolkit';
2
2
  import { clearAll } from '../../rootActions';
3
- import { date as zeniDate } from '../../zeniDayJS';
3
+ import { dateNow, date as zeniDate } from '../../zeniDayJS';
4
4
  import { ALL_AI_CFO_ANSWER_RESPONSE_TYPES, toAiCfoAnswerResponseType, toAiCfoAnswerResponseTypeStrict, toAiCfoAnswerStateType, toAiCfoVisualizationTypeStrict, toInteractiveFormTypeStrict, toMessageSender, toMessageType, toYFormatScaleStrict, toYFormatTypeStrict, toYFormatUnitStrict, } from './aiCfoState';
5
5
  export const initialAiCfoState = {
6
+ deletedChatSessionIds: [],
6
7
  aiCfoByChatSessionId: {},
7
8
  partialQuestionAnswers: {},
8
9
  syntheticAnswersByChatSessionId: {},
@@ -468,6 +469,11 @@ const toResponseBlockType = (answer, userId) => {
468
469
  createdAt: zeniDate(timestamp),
469
470
  };
470
471
  };
472
+ // How many deleted session ids to remember. The tombstone only has to outlive
473
+ // an in-flight history request, which is seconds, so this is generous. Capped
474
+ // because `clearSession` would otherwise grow the array for the life of the
475
+ // store and every `setChatHistory` scans it.
476
+ const DELETED_SESSION_MEMORY = 100;
471
477
  const aiCfo = createSlice({
472
478
  name: 'aiCfo',
473
479
  initialState: initialAiCfoState,
@@ -489,8 +495,25 @@ const aiCfo = createSlice({
489
495
  setSessions(draft, action) {
490
496
  action.payload.forEach((chatSessionPayload) => {
491
497
  const { chat_session_id } = chatSessionPayload;
492
- // This is to prevent overwriting the session if it is already in state
493
- if (draft.aiCfoByChatSessionId[chat_session_id] == null) {
498
+ if (draft.aiCfoByChatSessionId[chat_session_id] != null) {
499
+ // The list is authoritative for a session's metadata, and a session
500
+ // seeded by `setChatHistory` has guessed metadata: no summary, and a
501
+ // `createdAt` taken from one page of a newest-first paginated
502
+ // history, which is later than the session really started.
503
+ // `questionAnswers` is left alone — the list must never wipe a
504
+ // thread that is on screen.
505
+ const entry = draft.aiCfoByChatSessionId[chat_session_id];
506
+ const incoming = toChatSession(chatSessionPayload);
507
+ entry.chatSession = {
508
+ ...incoming,
509
+ // Never downgrade a title already in state: a page of the list can
510
+ // carry a nullish summary, and assigning it wholesale would blank
511
+ // a header that was correct.
512
+ chatSessionSummary: incoming.chatSessionSummary ??
513
+ entry.chatSession.chatSessionSummary,
514
+ };
515
+ }
516
+ else {
494
517
  draft.aiCfoByChatSessionId[chat_session_id] = {
495
518
  chatSession: toChatSession(chatSessionPayload),
496
519
  questionAnswers: [],
@@ -503,8 +526,52 @@ const aiCfo = createSlice({
503
526
  setChatHistory(draft, action) {
504
527
  const { chatSessionId, history, isPaginationComplete = false, } = action.payload;
505
528
  if (draft.aiCfoByChatSessionId[chatSessionId] == null) {
506
- console.warn(`session with id ${chatSessionId} not found in setChatHistory`);
507
- return;
529
+ // Sessions created server-side (a routine run) are opened by deep
530
+ // link, so their history can arrive before the sessions list has
531
+ // registered them. Dropping it here loses the messages for good: the
532
+ // response's null page token sets `hasMore: false`, which is the
533
+ // condition the refetch is guarded on. The response is itself proof
534
+ // the session exists, so seed the entry from the messages.
535
+ if (history.length === 0) {
536
+ return;
537
+ }
538
+ // A deleted session. Its history request is never cancelled
539
+ // (`mergeMap`), so seeding would resurrect the conversation into the
540
+ // rail, where clicking it 404s. Only this path is guarded:
541
+ // `clearSession` is optimistic, so if the server still lists the
542
+ // session, `setSessions` re-adding it is correct.
543
+ if (draft.deletedChatSessionIds?.includes(chatSessionId) === true) {
544
+ return;
545
+ }
546
+ // The human's id, taken off a message they actually sent. The API
547
+ // returns newest first, so `history[0]` is usually the agent's reply,
548
+ // and `chatSession.userId` is read as "whose conversation is this".
549
+ const owner = history.find((message) => message.sender === 'user') ?? history[0];
550
+ // Oldest message in the page, not `history[0]`: a session cannot
551
+ // start after its own messages, and the API returns newest first.
552
+ //
553
+ // Compared as instants, not strings. The wire format is an RFC 1123
554
+ // HTTP-date ("Thu, 03 Sep 2026 12:34:56 GMT") because `set_200`
555
+ // bypasses chat's isoformat encoder, and lexically "Mon…" precedes
556
+ // "Sat…" while being the later day. Unparseable values are filtered
557
+ // out, not compared: every comparison against NaN is false, so one
558
+ // used as the reduce's seed would carry through to an Invalid Date.
559
+ const oldest = history
560
+ .map((message) => ({ at: Date.parse(message.created_at), message }))
561
+ .filter(({ at }) => !Number.isNaN(at))
562
+ .reduce((min, entry) => (min == null || entry.at < min.at ? entry : min), undefined)?.message;
563
+ draft.aiCfoByChatSessionId[chatSessionId] = {
564
+ chatSession: {
565
+ chatSessionId,
566
+ userId: owner.user_id,
567
+ chatSessionSummary: undefined,
568
+ // Nothing in the page carried a usable timestamp. "Now" is a
569
+ // guess, but it is a sane one and it keeps the row out of the
570
+ // Invalid-Date behaviour above; the sessions list corrects it.
571
+ createdAt: oldest != null ? zeniDate(oldest.created_at) : dateNow(),
572
+ },
573
+ questionAnswers: [],
574
+ };
508
575
  }
509
576
  const session = draft.aiCfoByChatSessionId[chatSessionId];
510
577
  // Check if we have an existing partial Q&A pair for this session
@@ -784,6 +851,13 @@ const aiCfo = createSlice({
784
851
  },
785
852
  clearSession(draft, action) {
786
853
  const sessionId = action.payload;
854
+ draft.deletedChatSessionIds ?? (draft.deletedChatSessionIds = []);
855
+ if (!draft.deletedChatSessionIds.includes(sessionId)) {
856
+ draft.deletedChatSessionIds.push(sessionId);
857
+ if (draft.deletedChatSessionIds.length > DELETED_SESSION_MEMORY) {
858
+ draft.deletedChatSessionIds.splice(0, draft.deletedChatSessionIds.length - DELETED_SESSION_MEMORY);
859
+ }
860
+ }
787
861
  delete draft.aiCfoByChatSessionId[sessionId];
788
862
  delete draft.syntheticAnswersByChatSessionId[sessionId];
789
863
  if (draft.partialQuestionAnswers?.[sessionId] != null) {
@@ -33,9 +33,18 @@ const financeStatement = createSlice({
33
33
  },
34
34
  },
35
35
  updateFinanceStatementTimeframe(draft, action) {
36
+ // Unrelated UI re-dispatches the *current* timeframe as a side effect (the
37
+ // reports page hangs its table scroll reset off that callback); dropping the
38
+ // anchor there would silently reset the user's period to the latest one.
39
+ if (draft.timeframe === action.payload) {
40
+ return;
41
+ }
36
42
  draft.timeframe = action.payload;
43
+ // A month anchor is meaningless once the timeframe becomes quarter/year, so
44
+ // a real change drops it and returns the width to the default — 12 months
45
+ // must not become 12 quarters. Order is the user's, so it survives.
37
46
  draft.selectedCOABalancesRange = {
38
- numberOfPeriods: draft.selectedCOABalancesRange.numberOfPeriods,
47
+ numberOfPeriods: initialFinanceStatementState.selectedCOABalancesRange.numberOfPeriods,
39
48
  orderBy: draft.selectedCOABalancesRange.orderBy,
40
49
  };
41
50
  },
@@ -77,8 +86,7 @@ const financeStatement = createSlice({
77
86
  draft.selectedReportId = action.payload;
78
87
  },
79
88
  updateFinanceStatementAdditionalBalancesSelection(draft, action) {
80
- const { firstMonthOfFY, additionalBalances: additionalBalancesPayload, coaBalances, maxNumOfPeriodsToHighlight, } = action.payload;
81
- const safeCoaBalances = coaBalances != null ? coaBalances : [];
89
+ const { additionalBalances: additionalBalancesPayload, maxNumOfPeriodsToHighlight, } = action.payload;
82
90
  const additionalBalances = additionalBalancesPayload ?? [];
83
91
  let tempAdditionalBalances = [...additionalBalances];
84
92
  if (additionalBalances.includes('this_period_vs_last_period') ||
@@ -94,30 +102,12 @@ const financeStatement = createSlice({
94
102
  draft.maxNumOfPeriodsToHighlight = maxNumOfPeriodsToHighlight;
95
103
  draft.isAdditionalBalancesShown =
96
104
  additionalBalances.length != 0 ? true : false;
97
- const { timeframe, selectedCOABalancesRange } = draft;
98
- if (safeCoaBalances.length > 0) {
99
- const thisPeriod = extractThisPeriod(action.payload.firstMonthOfFY, timeframe, selectedCOABalancesRange, safeCoaBalances);
100
- if (thisPeriod != null) {
101
- const selectedCoaBalancesRangeWithThisPeriod = {
102
- ...selectedCOABalancesRange,
103
- thisPeriod,
104
- };
105
- const selectionRanges = getSelectedAndHighlightedRangesForThisPeriod({
106
- firstMonthOfFY,
107
- thisPeriod: thisPeriod,
108
- coaBalances: safeCoaBalances,
109
- timeframe,
110
- maxNumOfPeriodsToHighlight: maxNumOfPeriodsToHighlight,
111
- currentSelection: {
112
- selectedCOABalancesRange: selectedCoaBalancesRangeWithThisPeriod,
113
- },
114
- orderBy: 'ascending_date',
115
- maxNumOfPeriodsToSelect: maxNumOfPeriodsToHighlight,
116
- });
117
- draft.selectedCOABalancesRange =
118
- selectionRanges.selectedCOABalancesRange;
119
- }
120
- }
105
+ // Column metadata only must not touch selectedCOABalancesRange. The
106
+ // reports page fires this on load, on resize and on every fetch-state
107
+ // transition (so also on report switch and on remount after a drill-down)
108
+ // with a viewport-derived period count that knows nothing about the range
109
+ // the user picked. The width default comes from initial state, and from
110
+ // updateFinanceStatementTimeframe on a real timeframe change.
121
111
  },
122
112
  updateDownloadState(draft, action) {
123
113
  draft.downloadState = action.payload;
@@ -37,9 +37,18 @@ const financeStatement = (0, toolkit_1.createSlice)({
37
37
  },
38
38
  },
39
39
  updateFinanceStatementTimeframe(draft, action) {
40
+ // Unrelated UI re-dispatches the *current* timeframe as a side effect (the
41
+ // reports page hangs its table scroll reset off that callback); dropping the
42
+ // anchor there would silently reset the user's period to the latest one.
43
+ if (draft.timeframe === action.payload) {
44
+ return;
45
+ }
40
46
  draft.timeframe = action.payload;
47
+ // A month anchor is meaningless once the timeframe becomes quarter/year, so
48
+ // a real change drops it and returns the width to the default — 12 months
49
+ // must not become 12 quarters. Order is the user's, so it survives.
41
50
  draft.selectedCOABalancesRange = {
42
- numberOfPeriods: draft.selectedCOABalancesRange.numberOfPeriods,
51
+ numberOfPeriods: exports.initialFinanceStatementState.selectedCOABalancesRange.numberOfPeriods,
43
52
  orderBy: draft.selectedCOABalancesRange.orderBy,
44
53
  };
45
54
  },
@@ -81,8 +90,7 @@ const financeStatement = (0, toolkit_1.createSlice)({
81
90
  draft.selectedReportId = action.payload;
82
91
  },
83
92
  updateFinanceStatementAdditionalBalancesSelection(draft, action) {
84
- const { firstMonthOfFY, additionalBalances: additionalBalancesPayload, coaBalances, maxNumOfPeriodsToHighlight, } = action.payload;
85
- const safeCoaBalances = coaBalances != null ? coaBalances : [];
93
+ const { additionalBalances: additionalBalancesPayload, maxNumOfPeriodsToHighlight, } = action.payload;
86
94
  const additionalBalances = additionalBalancesPayload ?? [];
87
95
  let tempAdditionalBalances = [...additionalBalances];
88
96
  if (additionalBalances.includes('this_period_vs_last_period') ||
@@ -98,30 +106,12 @@ const financeStatement = (0, toolkit_1.createSlice)({
98
106
  draft.maxNumOfPeriodsToHighlight = maxNumOfPeriodsToHighlight;
99
107
  draft.isAdditionalBalancesShown =
100
108
  additionalBalances.length != 0 ? true : false;
101
- const { timeframe, selectedCOABalancesRange } = draft;
102
- if (safeCoaBalances.length > 0) {
103
- const thisPeriod = (0, thisPeriodHelpers_1.extractThisPeriod)(action.payload.firstMonthOfFY, timeframe, selectedCOABalancesRange, safeCoaBalances);
104
- if (thisPeriod != null) {
105
- const selectedCoaBalancesRangeWithThisPeriod = {
106
- ...selectedCOABalancesRange,
107
- thisPeriod,
108
- };
109
- const selectionRanges = (0, getSelectedAndHighlightedRanges_1.getSelectedAndHighlightedRangesForThisPeriod)({
110
- firstMonthOfFY,
111
- thisPeriod: thisPeriod,
112
- coaBalances: safeCoaBalances,
113
- timeframe,
114
- maxNumOfPeriodsToHighlight: maxNumOfPeriodsToHighlight,
115
- currentSelection: {
116
- selectedCOABalancesRange: selectedCoaBalancesRangeWithThisPeriod,
117
- },
118
- orderBy: 'ascending_date',
119
- maxNumOfPeriodsToSelect: maxNumOfPeriodsToHighlight,
120
- });
121
- draft.selectedCOABalancesRange =
122
- selectionRanges.selectedCOABalancesRange;
123
- }
124
- }
109
+ // Column metadata only must not touch selectedCOABalancesRange. The
110
+ // reports page fires this on load, on resize and on every fetch-state
111
+ // transition (so also on report switch and on remount after a drill-down)
112
+ // with a viewport-derived period count that knows nothing about the range
113
+ // the user picked. The width default comes from initial state, and from
114
+ // updateFinanceStatementTimeframe on a real timeframe change.
125
115
  },
126
116
  updateDownloadState(draft, action) {
127
117
  draft.downloadState = action.payload;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeniai/client-epic-state",
3
- "version": "5.2.39",
3
+ "version": "5.2.40",
4
4
  "description": "Shared module between Web & Mobile containing required abstractions for state management, async network communication. ",
5
5
  "main": "lib/index.js",
6
6
  "module": "lib/esm/index.js",