@seedtactics/insight-client 17.0.1 → 17.0.2

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.
@@ -34,8 +34,10 @@ import { JobsBackend, LogBackend } from "../network/backend.js";
34
34
  import { InProcessMaterial, LogType, LocType, ActiveJob, WorkorderComment, ActiveWorkorder, InProcessMaterialLocation, } from "../network/api.js";
35
35
  import { last30JobComment } from "./scheduled-jobs.js";
36
36
  import { atom } from "jotai";
37
+ import { HashSet } from "@seedtactics/immutable-collections";
37
38
  import { currentOperator } from "../data/operators.js";
38
39
  const currentStatusRW = atom({
40
+ revision: 0,
39
41
  timeOfCurrentStatusUTC: new Date(),
40
42
  jobs: {},
41
43
  pallets: {},
@@ -100,59 +102,50 @@ export const updateCurrentStatus = atom(null, (_, set, { evt }) => {
100
102
  });
101
103
  function processEventsIntoCurrentStatus(entry) {
102
104
  return (curSt) => {
103
- const mats = new Map();
104
- function adjustMat(id, f) {
105
- if (mats.size === 0) {
106
- for (const m of curSt.material) {
107
- mats.set(m.materialID, m);
108
- }
109
- }
110
- const oldMat = mats.get(id);
111
- if (oldMat !== undefined) {
112
- mats.set(id, new InProcessMaterial(f(oldMat)));
113
- }
114
- }
115
- switch (entry.type) {
116
- case LogType.PartMark:
117
- for (const m of entry.material) {
118
- adjustMat(m.id, (inmat) => ({ ...inmat, serial: entry.result }));
119
- }
120
- break;
121
- case LogType.OrderAssignment:
122
- for (const m of entry.material) {
123
- adjustMat(m.id, (inmat) => ({ ...inmat, workorderId: entry.result }));
124
- }
125
- break;
126
- case LogType.Inspection:
127
- case LogType.InspectionForce:
128
- if (entry.result.toLowerCase() === "true" || entry.result === "1") {
129
- let inspType;
130
- if (entry.type === LogType.InspectionForce) {
131
- inspType = entry.program;
132
- }
133
- else {
134
- inspType = (entry.details || {}).InspectionType;
135
- }
136
- if (inspType) {
137
- for (const m of entry.material) {
138
- adjustMat(m.id, (inmat) => ({
139
- ...inmat,
140
- signaledInspections: [...inmat.signaledInspections, inspType],
141
- }));
105
+ if (entry.type !== LogType.PartMark &&
106
+ entry.type !== LogType.OrderAssignment &&
107
+ entry.type !== LogType.Inspection &&
108
+ entry.type !== LogType.InspectionForce)
109
+ return curSt;
110
+ const materialIds = HashSet.from(entry.material.map((m) => m.id));
111
+ // Anonymous raw material can repeat ID -1, including several pieces in the same slot. A log
112
+ // updates identified material in place; it must never rebuild these targets through an ID map.
113
+ const material = curSt.material.map((mat) => {
114
+ if (mat.materialID < 0 || !materialIds.has(mat.materialID))
115
+ return mat;
116
+ const data = mat;
117
+ switch (entry.type) {
118
+ case LogType.PartMark:
119
+ return mat.serial === entry.result
120
+ ? mat
121
+ : new InProcessMaterial({ ...data, serial: entry.result });
122
+ case LogType.OrderAssignment:
123
+ return mat.workorderId === entry.result
124
+ ? mat
125
+ : new InProcessMaterial({ ...data, workorderId: entry.result });
126
+ case LogType.Inspection:
127
+ case LogType.InspectionForce:
128
+ if (entry.result.toLowerCase() === "true" || entry.result === "1") {
129
+ let inspType;
130
+ if (entry.type === LogType.InspectionForce) {
131
+ inspType = entry.program;
132
+ }
133
+ else {
134
+ inspType = (entry.details || {}).InspectionType;
142
135
  }
136
+ if (inspType && !mat.signaledInspections.includes(inspType))
137
+ return new InProcessMaterial({
138
+ ...data,
139
+ signaledInspections: [...mat.signaledInspections, inspType],
140
+ });
143
141
  }
144
- }
145
- break;
146
- }
147
- if (mats.size === 0) {
148
- return curSt;
149
- }
150
- else {
151
- return {
152
- ...curSt,
153
- material: Array.from(mats.values()),
154
- };
155
- }
142
+ break;
143
+ }
144
+ return mat;
145
+ });
146
+ return material.every((mat, idx) => mat === curSt.material[idx])
147
+ ? curSt
148
+ : { ...curSt, material };
156
149
  };
157
150
  }
158
151
  export const reorderQueuedMatInCurrentStatus = atom(null, (_, set, { queue, matId, newIdx }) => {
@@ -1,4 +1,5 @@
1
- import { ICurrentStatus, IHistoricData, ILogEntry, IRecentHistoricData, IServerEvent } from "../network/api.js";
1
+ import { IHistoricData, ILogEntry, IRecentHistoricData, IServerEvent } from "../network/api.js";
2
+ export { onLoadCurrentSt } from "../network/current-status-session.js";
2
3
  import * as currentSt from "./current-status.js";
3
4
  import { Atom } from "jotai";
4
5
  export interface ServerEventAndTime {
@@ -22,9 +23,6 @@ export declare const onLoadLast30Jobs: import("jotai").WritableAtom<null, [histo
22
23
  export declare const onLoadLast30Log: import("jotai").WritableAtom<null, [log: readonly Readonly<ILogEntry>[]], void> & {
23
24
  init: null;
24
25
  };
25
- export declare const onLoadCurrentSt: import("jotai").WritableAtom<null, [curSt: Readonly<ICurrentStatus>], void> & {
26
- init: null;
27
- };
28
26
  export interface QueuedMatMove extends currentSt.QueueReordering {
29
27
  readonly operator: string | null;
30
28
  }
@@ -31,6 +31,8 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31
31
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
32
  */
33
33
  import { QueuePosition, } from "../network/api.js";
34
+ import { acceptCurrentStatusSnapshot, currentStatusSessionAtom, onLoadCurrentSt, } from "../network/current-status-session.js";
35
+ export { onLoadCurrentSt } from "../network/current-status-session.js";
34
36
  import { JobsBackend } from "../network/backend.js";
35
37
  import { LazySeq } from "@seedtactics/immutable-collections";
36
38
  import * as simProd from "./sim-production.js";
@@ -109,11 +111,6 @@ export const onLoadLast30Log = atom(null, (_, set, log) => {
109
111
  const newCntr = LazySeq.of(log).maxBy((x) => x.counter)?.counter ?? null;
110
112
  set(lastEventCounterRW, (oldCntr) => oldCntr === null ? newCntr : Math.max(oldCntr, newCntr ?? -1));
111
113
  });
112
- export const onLoadCurrentSt = atom(null, (_, set, curSt) => {
113
- set(currentSt.setCurrentStatus, curSt);
114
- set(customSt.replaceCustomState, curSt.customState ?? null);
115
- set(names.setNamesFromCurrentStatus, curSt);
116
- });
117
114
  // Show queue drops immediately. Recovery must not replace intervening live updates or drags.
118
115
  export const moveQueuedMatInCurrentStatus = atom(null, async (get, set, { operator, ...move }) => {
119
116
  const before = get(currentSt.currentStatus);
@@ -123,15 +120,17 @@ export const moveQueuedMatInCurrentStatus = atom(null, async (get, set, { operat
123
120
  await JobsBackend.setMaterialInQueue(move.matId, operator, new QueuePosition({ queue: move.queue, position: move.newIdx }));
124
121
  }
125
122
  catch (error) {
123
+ const session = get(currentStatusSessionAtom).id;
126
124
  const beforeReload = get(currentSt.currentStatus);
127
125
  try {
128
126
  const refreshed = await JobsBackend.currentStatus();
129
127
  if (get(currentSt.currentStatus) === beforeReload)
130
- set(onLoadCurrentSt, refreshed);
128
+ set(acceptCurrentStatusSnapshot, session, refreshed, "http");
131
129
  }
132
130
  catch {
133
131
  // If the server is unreachable, undo only this move's untouched optimistic snapshot.
134
- if (get(currentSt.currentStatus) === optimistic)
132
+ if (get(currentStatusSessionAtom).id === session &&
133
+ get(currentSt.currentStatus) === optimistic)
135
134
  set(onLoadCurrentSt, before);
136
135
  }
137
136
  throw error;
@@ -31,10 +31,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
31
  import { useMemo, useState } from "react";
32
32
  import { Alert, Box, Button, Stack, Typography } from "@mui/material";
33
33
  import { LazySeq } from "@seedtactics/immutable-collections";
34
+ import { useSetAtom } from "jotai";
34
35
  import { basketSlotLabel } from "../../cell-status/station-cycles.js";
35
36
  import * as api from "../../network/api.js";
36
37
  import { serverErrorMessage } from "../../network/api-errors.js";
37
38
  import { JobsBackend } from "../../network/backend.js";
39
+ import { refreshCurrentStatus } from "../../network/websocket.js";
38
40
  import { InProcMaterial } from "./Material.js";
39
41
  import { MoveMaterialArrowNode } from "./MoveMaterialArrows.js";
40
42
  import { MoveMaterialNodeKindType } from "../../data/move-arrows.js";
@@ -121,6 +123,8 @@ function SlotMaterial({ material, basketId, fsize, }) {
121
123
  }
122
124
  export function BasketLoadStationWorkflow({ basket, material, fsize, title, elapsed, }) {
123
125
  const [submission, setSubmission] = useState();
126
+ const refresh = useSetAtom(refreshCurrentStatus);
127
+ const [refreshError, setRefreshError] = useState();
124
128
  const workState = useMemo(() => stationWork(material, basket), [basket, material]);
125
129
  const blockedReason = basket.loadStationWork?.confirmationBlockedReason?.trim();
126
130
  const instructionWarning = basket.loadStationWork?.instructionWarning?.trim();
@@ -152,6 +156,19 @@ export function BasketLoadStationWorkflow({ basket, material, fsize, title, elap
152
156
  .concat(loadsBySlot.keysToLazySeq())
153
157
  .distinctBy((slot) => slot)
154
158
  .toSortedArray((slot) => slot), [basket.emptySlots, basket.unknownSlots, materialBySlot, loadsBySlot]);
159
+ async function refreshStatus(workId) {
160
+ setRefreshError(undefined);
161
+ try {
162
+ if (!(await refresh(AbortSignal.timeout(5000))))
163
+ setRefreshError({ workId, message: "The connection changed while refreshing status." });
164
+ }
165
+ catch (error) {
166
+ setRefreshError({
167
+ workId,
168
+ message: serverErrorMessage(error) ?? "Unable to refresh status.",
169
+ });
170
+ }
171
+ }
155
172
  async function submit() {
156
173
  if (work === undefined || !work.ready)
157
174
  return;
@@ -174,6 +191,7 @@ export function BasketLoadStationWorkflow({ basket, material, fsize, title, elap
174
191
  const reason = serverErrorMessage(error);
175
192
  setSubmission((current) => (current === pending ? { ...pending, state, reason } : current));
176
193
  }
194
+ await refreshStatus(submittedWorkId);
177
195
  }
178
196
  const submissionDisabled = !work?.ready ||
179
197
  submissionState === "submitting" ||
@@ -192,7 +210,7 @@ export function BasketLoadStationWorkflow({ basket, material, fsize, title, elap
192
210
  minWidth: "8ch",
193
211
  textAlign: "right",
194
212
  fontVariantNumeric: "tabular-nums",
195
- }, children: elapsed })] }), _jsxs(Stack, { spacing: 2, sx: { ml: "4em", mr: "4em", mt: 2 }, children: [work?.confirmEmpty && work.ready && (_jsxs(Typography, { children: ["Confirm basket ", basket.basketId, " is empty."] })), instructionWarning && _jsx(Alert, { severity: "warning", children: instructionWarning }), work && !work.ready && (_jsx(Alert, { severity: "info", children: blockedReason ||
213
+ }, children: elapsed })] }), _jsxs(Stack, { spacing: 2, sx: { ml: "4em", mr: "4em", mt: 2 }, children: [refreshError?.workId === work?.workId && refreshError && (_jsxs(Alert, { severity: "warning", action: _jsx(Button, { onClick: () => void refreshStatus(refreshError.workId), children: "Refresh status" }), children: [refreshError.message, " Refresh current status to review the latest work."] })), work?.confirmEmpty && work.ready && (_jsxs(Typography, { children: ["Confirm basket ", basket.basketId, " is empty."] })), instructionWarning && _jsx(Alert, { severity: "warning", children: instructionWarning }), work && !work.ready && (_jsx(Alert, { severity: "info", children: blockedReason ||
196
214
  (work.awaitingSlots.length > 0
197
215
  ? `Waiting for material for slots ${work.awaitingSlots.map(basketSlotLabel).join(", ")}.`
198
216
  : "Basket work is not ready for confirmation.") })), !work && workState.type === "inconsistent" ? (_jsx(Alert, { severity: "warning", children: "Basket work is inconsistent. Wait for refreshed material actions before confirming." })) : null, submissionState === "accepted" ? (_jsx(Alert, { severity: "success", children: "Confirmation accepted. Waiting for refreshed work." })) : submissionState === "conflict" ? (_jsx(Alert, { severity: "warning", children: submissionReason ??
@@ -4,7 +4,7 @@ import type { AppProps } from "./components/App.js";
4
4
  */
5
5
  export declare function bootstrapInsight(appProps?: AppProps, rootElement?: HTMLElement): Promise<void>;
6
6
  export { customState } from "./cell-status/custom-state.js";
7
- export { currentStatusIsLive } from "./network/websocket.js";
7
+ export { currentStatusIsLive, refreshCurrentStatus } from "./network/websocket.js";
8
8
  export type { AppProps };
9
9
  export { defaultChooseModes } from "./components/ChooseMode.js";
10
10
  export type { ChooseModeItem } from "./components/ChooseMode.js";
package/dist/extension.js CHANGED
@@ -16,7 +16,7 @@ export async function bootstrapInsight(appProps = {}, rootElement) {
16
16
  render(appProps, root, store);
17
17
  }
18
18
  export { customState } from "./cell-status/custom-state.js";
19
- export { currentStatusIsLive } from "./network/websocket.js";
19
+ export { currentStatusIsLive, refreshCurrentStatus } from "./network/websocket.js";
20
20
  export { defaultChooseModes } from "./components/ChooseMode.js";
21
21
  export { RouteLocation } from "./components/routes.js";
22
22
  export { authenticatedFetch } from "./network/backend.js";
package/dist/index.html CHANGED
@@ -6,7 +6,7 @@
6
6
  <link rel="shortcut icon" href="/assets/favicon-gWFxiJK2.ico" />
7
7
  <title>SeedTactic FMS Insight</title>
8
8
  <style type="text/css">.download-loader{width:100px;height:100px;display:inline-block}.download-circular{width:100px;height:100px;animation:2s linear infinite rotate}.download-path{stroke-dasharray:1 200;stroke-dashoffset:0;stroke-linecap:round;stroke:#8d6e63;animation:1.5s ease-out infinite dash}@keyframes rotate{to{transform:rotate(360deg)}}@keyframes dash{0%{stroke-dasharray:1 200;stroke-dashoffset:0}50%{stroke-dasharray:89 200;stroke-dashoffset:-35px}to{stroke-dasharray:89 200;stroke-dashoffset:-124px}}</style>
9
- <script type="module" crossorigin src="/assets/index-CfHZxY5F.js"></script>
9
+ <script type="module" crossorigin src="/assets/index-Cjt4dPv7.js"></script>
10
10
  <link rel="stylesheet" crossorigin href="/assets/index-DXfAwuj-.css">
11
11
  </head>
12
12
  <body>
@@ -695,6 +695,7 @@ export interface INewProgramContent {
695
695
  revision: number;
696
696
  }
697
697
  export declare class CurrentStatus implements ICurrentStatus {
698
+ revision: number;
698
699
  timeOfCurrentStatusUTC: Date;
699
700
  jobs: {
700
701
  [key: string]: ActiveJob;
@@ -719,6 +720,7 @@ export declare class CurrentStatus implements ICurrentStatus {
719
720
  toJSON(data?: any): any;
720
721
  }
721
722
  export interface ICurrentStatus {
723
+ revision: number;
722
724
  timeOfCurrentStatusUTC: Date;
723
725
  jobs: {
724
726
  [key: string]: ActiveJob;
@@ -3600,6 +3600,7 @@ export class CurrentStatus {
3600
3600
  }
3601
3601
  init(_data) {
3602
3602
  if (_data) {
3603
+ this.revision = _data["Revision"];
3603
3604
  this.timeOfCurrentStatusUTC = _data["TimeOfCurrentStatusUTC"]
3604
3605
  ? new Date(_data["TimeOfCurrentStatusUTC"].toString())
3605
3606
  : undefined;
@@ -3670,6 +3671,7 @@ export class CurrentStatus {
3670
3671
  }
3671
3672
  toJSON(data) {
3672
3673
  data = typeof data === "object" ? data : {};
3674
+ data["Revision"] = this.revision;
3673
3675
  data["TimeOfCurrentStatusUTC"] = this.timeOfCurrentStatusUTC
3674
3676
  ? this.timeOfCurrentStatusUTC.toISOString()
3675
3677
  : undefined;
@@ -3,7 +3,7 @@ import { User } from "oidc-client-ts";
3
3
  export interface JobAPI {
4
4
  history(startUTC: Date, endUTC: Date): Promise<Readonly<api.IHistoricData>>;
5
5
  recent(startUTC: Date, alreadyKnownSchIds: string[]): Promise<Readonly<api.IRecentHistoricData>>;
6
- currentStatus(): Promise<Readonly<api.ICurrentStatus>>;
6
+ currentStatus(signal?: AbortSignal): Promise<Readonly<api.ICurrentStatus>>;
7
7
  setJobComment(unique: string, comment: string): Promise<void>;
8
8
  removeMaterialFromAllQueues(materialId: number, operatorName: string | undefined): Promise<void>;
9
9
  bulkRemoveMaterialFromQueues(operatorName: string | null, materialIds: ReadonlyArray<number> | null): Promise<void>;
@@ -25,7 +25,7 @@ export interface FmsAPI {
25
25
  }
26
26
  export interface LogAPI {
27
27
  get(startUTC: Date, endUTC: Date, signal?: AbortSignal): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
28
- recent(lastSeenCounter: number, expectedEndUTCofLastSeen: Date | null | undefined): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
28
+ recent(lastSeenCounter: number, expectedEndUTCofLastSeen: Date | null | undefined, signal?: AbortSignal): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
29
29
  logForMaterial(materialID: number, signal?: AbortSignal): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
30
30
  logForMaterials(materialIDs: ReadonlyArray<number> | null | undefined): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
31
31
  logForSerial(serial: string, signal?: AbortSignal): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
@@ -0,0 +1,27 @@
1
+ import { type Getter } from "jotai";
2
+ import type { ICurrentStatus } from "./api.js";
3
+ type CurrentStatusSession = {
4
+ readonly id: number;
5
+ readonly open: boolean;
6
+ readonly snapshot: {
7
+ readonly status: Readonly<ICurrentStatus>;
8
+ readonly source: "http" | "socket";
9
+ } | null;
10
+ };
11
+ export declare const currentStatusSessionAtom: import("jotai").PrimitiveAtom<CurrentStatusSession> & {
12
+ init: CurrentStatusSession;
13
+ };
14
+ export declare const currentStatusIsLiveRW: import("jotai").PrimitiveAtom<boolean> & {
15
+ init: boolean;
16
+ };
17
+ export declare const errorLoadingStatusRW: import("jotai").PrimitiveAtom<string | null> & {
18
+ init: string | null;
19
+ };
20
+ export declare function isCurrentSession(get: Getter, session: number): boolean;
21
+ export declare const onLoadCurrentSt: import("jotai").WritableAtom<null, [status: Readonly<ICurrentStatus>], void> & {
22
+ init: null;
23
+ };
24
+ export declare const acceptCurrentStatusSnapshot: import("jotai").WritableAtom<null, [session: number, status: Readonly<ICurrentStatus>, source: "http" | "socket"], boolean> & {
25
+ init: null;
26
+ };
27
+ export {};
@@ -0,0 +1,65 @@
1
+ /* Copyright (c) 2021, John Lenz
2
+
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ * Redistributions of source code must retain the above copyright
9
+ notice, this list of conditions and the following disclaimer.
10
+
11
+ * Redistributions in binary form must reproduce the above
12
+ copyright notice, this list of conditions and the following
13
+ disclaimer in the documentation and/or other materials provided
14
+ with the distribution.
15
+
16
+ * Neither the name of John Lenz, Black Maple Software, SeedTactics,
17
+ nor the names of other contributors may be used to endorse or
18
+ promote products derived from this software without specific
19
+ prior written permission.
20
+
21
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
+ */
33
+ import { atom } from "jotai";
34
+ import { setCurrentStatus } from "../cell-status/current-status.js";
35
+ import { replaceCustomState } from "../cell-status/custom-state.js";
36
+ import { setNamesFromCurrentStatus } from "../cell-status/names.js";
37
+ export const currentStatusSessionAtom = atom({
38
+ id: 0,
39
+ open: false,
40
+ snapshot: null,
41
+ });
42
+ export const currentStatusIsLiveRW = atom(false);
43
+ export const errorLoadingStatusRW = atom(null);
44
+ export function isCurrentSession(get, session) {
45
+ return get(currentStatusSessionAtom).id === session;
46
+ }
47
+ // Raw replacement also serves offline fixtures and local rollbacks. Live server snapshots must
48
+ // use acceptCurrentStatusSnapshot so the display and its comparison revision move together.
49
+ export const onLoadCurrentSt = atom(null, (_, set, status) => {
50
+ set(setCurrentStatus, status);
51
+ set(replaceCustomState, status.customState ?? null);
52
+ set(setNamesFromCurrentStatus, status);
53
+ });
54
+ export const acceptCurrentStatusSnapshot = atom(null, (get, set, session, status, source) => {
55
+ const current = get(currentStatusSessionAtom);
56
+ const installed = current.snapshot?.status;
57
+ if (current.id !== session || (installed && status.revision <= installed.revision))
58
+ return false;
59
+ set(onLoadCurrentSt, status);
60
+ set(currentStatusSessionAtom, { ...current, snapshot: { status, source } });
61
+ if (current.open)
62
+ set(currentStatusIsLiveRW, true);
63
+ set(errorLoadingStatusRW, null);
64
+ return true;
65
+ });
@@ -2,4 +2,7 @@ import { Atom } from "jotai";
2
2
  export declare const websocketReconnecting: Atom<boolean>;
3
3
  export declare const currentStatusIsLive: Atom<boolean>;
4
4
  export declare const errorLoadingLast30: Atom<string | null>;
5
+ export declare const refreshCurrentStatus: import("jotai").WritableAtom<null, [signal?: AbortSignal | undefined], Promise<boolean>> & {
6
+ init: null;
7
+ };
5
8
  export declare function WebsocketConnection(): null;
@@ -30,14 +30,16 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
30
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
31
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
32
  */
33
+ import { acceptCurrentStatusSnapshot, currentStatusSessionAtom, currentStatusIsLiveRW, errorLoadingStatusRW, isCurrentSession, } from "./current-status-session.js";
33
34
  import { ServerEvent } from "./api.js";
34
35
  import { apiErrorMessage } from "./api-errors.js";
35
36
  import { JobsBackend, LogBackend } from "./backend.js";
36
37
  import { fmsInformation } from "./server-settings.js";
37
38
  import { useEffect, useRef } from "react";
38
- import { lastEventCounter, onLoadCurrentSt, onLoadLast30Jobs, onLoadLast30Log, onLiveServerEvent, onHistoricalServerEvent, } from "../cell-status/loading.js";
39
+ import { lastEventCounter, onLoadLast30Jobs, onLoadLast30Log, onLiveServerEvent, onHistoricalServerEvent, } from "../cell-status/loading.js";
39
40
  import { addDays } from "date-fns";
40
41
  import { last30SchIds } from "../cell-status/scheduled-jobs.js";
42
+ import { currentStatus } from "../cell-status/current-status.js";
41
43
  import { HashSet, OrderedMap } from "@seedtactics/immutable-collections";
42
44
  import { atom, useAtomValue, useSetAtom } from "jotai";
43
45
  const websocketReconnectingAtom = atom(false);
@@ -45,9 +47,7 @@ export const websocketReconnecting = websocketReconnectingAtom;
45
47
  // True while the websocket is open and this connection has loaded or received a current status, so
46
48
  // the retained current status reflects the server. Loading the historical jobs and log does not
47
49
  // affect it.
48
- const currentStatusIsLiveRW = atom(false);
49
50
  export const currentStatusIsLive = currentStatusIsLiveRW;
50
- const websocketSessionAtom = atom({ id: 0, statusFromSocket: false });
51
51
  // Only historical effects wait for HTTP catch-up. A fresh session discards its predecessor's
52
52
  // unapplied buffer and reloads from lastEventCounter, which has not advanced past that history.
53
53
  const bufferedLogAtom = atom(null);
@@ -56,22 +56,67 @@ const bufferedLogAtom = atom(null);
56
56
  const loadedLogCountersAtom = atom(HashSet.empty());
57
57
  const errorLoadingLast30RW = atom(null);
58
58
  const errorLoadingLogRW = atom(null);
59
- export const errorLoadingLast30 = atom((get) => get(errorLoadingLast30RW) ?? get(errorLoadingLogRW));
60
- function isCurrentSession(get, session) {
61
- return get(websocketSessionAtom).id === session;
59
+ export const errorLoadingLast30 = atom((get) => get(errorLoadingStatusRW) ?? get(errorLoadingLast30RW) ?? get(errorLoadingLogRW));
60
+ async function loadCurrentStatus(get, set, session, signal) {
61
+ while (isCurrentSession(get, session)) {
62
+ const before = get(currentStatus);
63
+ const snapshot = get(currentStatusSessionAtom).snapshot;
64
+ let st;
65
+ try {
66
+ signal?.throwIfAborted();
67
+ st = await JobsBackend.currentStatus(signal);
68
+ signal?.throwIfAborted();
69
+ }
70
+ catch (error) {
71
+ const current = get(currentStatusSessionAtom);
72
+ if (current.id !== session)
73
+ return false;
74
+ if (!signal?.aborted &&
75
+ current.snapshot !== snapshot &&
76
+ current.snapshot?.source === "socket")
77
+ return true;
78
+ throw error;
79
+ }
80
+ const current = get(currentStatusSessionAtom);
81
+ if (current.id !== session)
82
+ return false;
83
+ const installed = current.snapshot?.status;
84
+ if (installed && st.revision <= installed.revision)
85
+ return true;
86
+ // A higher server revision can replace an intervening complete snapshot, but a log edit or
87
+ // optimistic local edit still needs a fresh read rather than being overwritten.
88
+ if (get(currentStatus) !== before && get(currentStatus) !== installed)
89
+ continue;
90
+ set(acceptCurrentStatusSnapshot, session, st, "http");
91
+ return true;
92
+ }
93
+ return false;
62
94
  }
63
- function loadCurrentStatus(get, set, session) {
64
- return JobsBackend.currentStatus().then((st) => {
65
- const current = get(websocketSessionAtom);
66
- if (current.id !== session || current.statusFromSocket)
95
+ // Every caller starts its own read, after its action has settled. Session ownership stays here.
96
+ export const refreshCurrentStatus = atom(null, (get, set, signal) => loadCurrentStatus(get, set, get(currentStatusSessionAtom).id, signal));
97
+ async function loadBootstrapStatus(get, set, session, retryDelay = 1000) {
98
+ try {
99
+ await loadCurrentStatus(get, set, session, AbortSignal.timeout(10000));
100
+ }
101
+ catch (error) {
102
+ if (!isCurrentSession(get, session) || get(currentStatusIsLiveRW))
67
103
  return;
68
- set(onLoadCurrentSt, st);
69
- set(currentStatusIsLiveRW, true);
70
- });
104
+ set(errorLoadingStatusRW, apiErrorMessage(error, "Error loading current status"));
105
+ setTimeout(() => {
106
+ if (isCurrentSession(get, session) && !get(currentStatusIsLiveRW)) {
107
+ void loadBootstrapStatus(get, set, session, Math.min(retryDelay * 2, 30000));
108
+ }
109
+ }, retryDelay);
110
+ }
71
111
  }
72
112
  function loadHistory(get, set, session, from, retryDelay = 1000) {
73
113
  const now = new Date();
74
- const request = from === null ? LogBackend.get(addDays(now, -30), now) : LogBackend.recent(from, undefined);
114
+ // Initial history can be much larger than status. Bound both headers and body reads, then
115
+ // retry from the same applied position while retaining buffered socket events.
116
+ const signal = AbortSignal.timeout(120000);
117
+ const request = from === null
118
+ ? LogBackend.get(addDays(now, -30), now, signal)
119
+ : LogBackend.recent(from, undefined, signal);
75
120
  return request.then((log) => {
76
121
  if (!isCurrentSession(get, session))
77
122
  return;
@@ -84,7 +129,9 @@ function loadHistory(get, set, session, from, retryDelay = 1000) {
84
129
  }, (e) => {
85
130
  if (!isCurrentSession(get, session))
86
131
  return;
87
- set(errorLoadingLogRW, apiErrorMessage(e, "Error loading log history"));
132
+ set(errorLoadingLogRW, signal.aborted
133
+ ? "Loading log history timed out."
134
+ : apiErrorMessage(e, "Error loading log history"));
88
135
  // Keep buffering and retry from the same applied position without interrupting live status.
89
136
  setTimeout(() => {
90
137
  if (isCurrentSession(get, session)) {
@@ -96,7 +143,7 @@ function loadHistory(get, set, session, from, retryDelay = 1000) {
96
143
  function loadConnection(get, set, session) {
97
144
  const from = get(lastEventCounter);
98
145
  const schIds = get(last30SchIds);
99
- const curStProm = loadCurrentStatus(get, set, session);
146
+ const curStProm = loadBootstrapStatus(get, set, session);
100
147
  const jobsProm = JobsBackend.recent(addDays(new Date(), -30), from !== null && schIds ? Array.from(schIds) : []).then((j) => {
101
148
  if (isCurrentSession(get, session))
102
149
  set(onLoadLast30Jobs, j);
@@ -169,12 +216,13 @@ class ReconnectingWebsocket {
169
216
  }
170
217
  }
171
218
  const onOpenAtom = atom(null, (get, set) => {
172
- const session = get(websocketSessionAtom).id + 1;
173
- set(websocketSessionAtom, { id: session, statusFromSocket: false });
219
+ const session = get(currentStatusSessionAtom).id + 1;
220
+ set(currentStatusSessionAtom, { id: session, open: true, snapshot: null });
174
221
  set(websocketReconnectingAtom, true);
175
222
  set(currentStatusIsLiveRW, false);
176
223
  set(errorLoadingLast30RW, null);
177
224
  set(errorLoadingLogRW, null);
225
+ set(errorLoadingStatusRW, null);
178
226
  set(bufferedLogAtom, OrderedMap.empty());
179
227
  loadConnection(get, set, session);
180
228
  return session;
@@ -186,16 +234,23 @@ const onCloseAtom = atom(null, (get, set, session, reconnecting) => {
186
234
  set(websocketReconnectingAtom, true);
187
235
  if (session === null || !isCurrentSession(get, session))
188
236
  return;
189
- set(websocketSessionAtom, { id: session + 1, statusFromSocket: false });
237
+ set(currentStatusSessionAtom, { id: session + 1, open: false, snapshot: null });
190
238
  set(currentStatusIsLiveRW, false);
191
239
  set(bufferedLogAtom, null);
192
240
  });
193
241
  const onMessageAtom = atom(null, (get, set, evt, session) => {
194
242
  if (session === null || !isCurrentSession(get, session))
195
243
  return;
196
- const serverEvt = ServerEvent.fromJS(JSON.parse(evt.data));
244
+ const received = ServerEvent.fromJS(JSON.parse(evt.data));
245
+ const status = received.newCurrentStatus;
246
+ const accepted = status && set(acceptCurrentStatusSnapshot, session, status, "socket");
247
+ const serverEvt = status && !accepted
248
+ ? new ServerEvent({ logEntry: received.logEntry, newJobs: received.newJobs })
249
+ : received;
197
250
  const eventAndTime = { evt: serverEvt, now: new Date(), expire: true };
198
- set(onLiveServerEvent, eventAndTime);
251
+ // Complete snapshots were installed above; standalone log edits still apply immediately.
252
+ if (!serverEvt.newCurrentStatus)
253
+ set(onLiveServerEvent, eventAndTime);
199
254
  const log = serverEvt.logEntry;
200
255
  const buffered = get(bufferedLogAtom);
201
256
  if (!log || !get(loadedLogCountersAtom).has(log.counter)) {
@@ -206,10 +261,6 @@ const onMessageAtom = atom(null, (get, set, evt, session) => {
206
261
  set(onHistoricalServerEvent, eventAndTime);
207
262
  }
208
263
  }
209
- if (serverEvt.newCurrentStatus) {
210
- set(websocketSessionAtom, { id: session, statusFromSocket: true });
211
- set(currentStatusIsLiveRW, true);
212
- }
213
264
  });
214
265
  export function WebsocketConnection() {
215
266
  const onOpen = useSetAtom(onOpenAtom);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seedtactics/insight-client",
3
- "version": "17.0.1",
3
+ "version": "17.0.2",
4
4
  "license": "BSD-3-Clause",
5
5
  "repository": {
6
6
  "url": "https://github.com/SeedTactics/fms-insight"