@wherever-dev/client 0.3.0 → 0.3.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/CHANGELOG.md +16 -0
- package/dist/client.d.ts +11 -0
- package/dist/client.js +289 -14
- package/dist/client.js.map +1 -1
- package/dist/types.d.ts +3 -0
- package/package.json +1 -1
- package/src/client.ts +301 -15
- package/src/types.ts +20 -0
- package/test/message-delivery-confirmation.test.ts +194 -0
- package/test/mid-stream-steer.test.ts +91 -0
- package/test/tool-duration-history.test.ts +93 -0
- package/test/tool-duration.test.ts +86 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @wherever-dev/client
|
|
2
2
|
|
|
3
|
+
## 0.3.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 333f6ad: Never silently lose a message when the connection drops mid-send; confirm delivery and recover it on reload.
|
|
8
|
+
|
|
9
|
+
A frame handed to a socket that reports OPEN can still never reach the server (a half-open TCP connection: `send()` buffers locally and does not throw, but the bytes never land). The optimistic echo was treated as delivered, the input was cleared, and on reload the message was gone with no way to recover it.
|
|
10
|
+
|
|
11
|
+
Outbound user messages are now tracked as `delivery: 'sending'` until the server echoes them back (`message_end` role:user), at which point they are confirmed. If no echo arrives within a window, the message flips to `delivery: 'failed'` and the UI surfaces "Not delivered" with Retry / Discard instead of a normal-looking sent message. Unconfirmed messages are persisted per session, so a reload reconciles them against the loaded history: anything the server actually persisted is shown as delivered, and anything it did not is re-surfaced as a recoverable failed message (never silently dropped). New client APIs: `resendMessage(id)` and `discardMessage(id)`.
|
|
12
|
+
|
|
13
|
+
- 9368269: Show how long each tool call has been running, like the pi CLI.
|
|
14
|
+
|
|
15
|
+
A running tool now shows a live-ticking "Elapsed N.Ns" and, once it finishes, "Took N.Ns" (one decimal, matching the CLI's bash duration format). The client reducer stamps `startedAt` on `tool_start` and `endedAt` on `tool_end` (new `ChatMessage` fields), and freezes a still-running tool's `endedAt` if the turn ends or is aborted without a `tool_end`, so the timer stops instead of counting up forever. The web UI ticks only while a tool is actually running (no per-frame work on an idle session).
|
|
16
|
+
|
|
17
|
+
Durations also survive a reload/reconnect: history mapping pairs each `tool_call` with its `tool_result` and derives `startedAt`/`endedAt` from their timestamps (no server change needed), so a tool restored from loaded history shows the same "Took N.Ns" as a live-streamed one.
|
|
18
|
+
|
|
3
19
|
## 0.3.0
|
|
4
20
|
|
|
5
21
|
### Minor Changes
|
package/dist/client.d.ts
CHANGED
|
@@ -34,6 +34,9 @@ export declare class WhereverClient {
|
|
|
34
34
|
private resumeModel?;
|
|
35
35
|
private listeners;
|
|
36
36
|
private pendingUploads;
|
|
37
|
+
private confirmTimers;
|
|
38
|
+
private static readonly CONFIRM_MS;
|
|
39
|
+
private static readonly PENDING_PREFIX;
|
|
37
40
|
constructor(config: WhereverClientConfig);
|
|
38
41
|
connect(newConfig?: Partial<WhereverClientConfig>, preserveState?: boolean): void;
|
|
39
42
|
disconnect(resetState?: boolean): void;
|
|
@@ -64,6 +67,14 @@ export declare class WhereverClient {
|
|
|
64
67
|
loadMoreHistory(): void;
|
|
65
68
|
send(msg: any): boolean;
|
|
66
69
|
sendMessage(text: string): boolean;
|
|
70
|
+
private pendingKey;
|
|
71
|
+
private persistPending;
|
|
72
|
+
private loadPersistedPending;
|
|
73
|
+
private armConfirm;
|
|
74
|
+
private clearConfirm;
|
|
75
|
+
private confirmDeliveredByContent;
|
|
76
|
+
resendMessage(messageId: string): boolean;
|
|
77
|
+
discardMessage(messageId: string): void;
|
|
67
78
|
abort(): void;
|
|
68
79
|
joinSession(sessionFile: string, cwd?: string, model?: string): void;
|
|
69
80
|
switchSession(sessionFile: string, cwd?: string, model?: string): void;
|
package/dist/client.js
CHANGED
|
@@ -84,6 +84,13 @@ export class WhereverClient {
|
|
|
84
84
|
resumeModel;
|
|
85
85
|
listeners = new Set();
|
|
86
86
|
pendingUploads = new Map();
|
|
87
|
+
// Per-message confirmation watchdogs. A user message committed optimistically
|
|
88
|
+
// is only proven delivered when the server echoes it back; if no echo lands
|
|
89
|
+
// within CONFIRM_MS the watchdog flips it to delivery:'failed' so the UI can
|
|
90
|
+
// offer a retry instead of pretending it was sent (the half-open-socket loss).
|
|
91
|
+
confirmTimers = new Map();
|
|
92
|
+
static CONFIRM_MS = 12_000;
|
|
93
|
+
static PENDING_PREFIX = 'wherever-pending:';
|
|
87
94
|
constructor(config) {
|
|
88
95
|
this.config = {
|
|
89
96
|
secure: true,
|
|
@@ -288,6 +295,13 @@ export class WhereverClient {
|
|
|
288
295
|
this.ws = null;
|
|
289
296
|
}
|
|
290
297
|
if (resetState) {
|
|
298
|
+
// Full teardown wipes the store, so no unconfirmed message survives in it;
|
|
299
|
+
// clear their watchdogs to avoid firing against a fresh store. The
|
|
300
|
+
// persisted-pending localStorage entries intentionally REMAIN so a later
|
|
301
|
+
// load can still recover them.
|
|
302
|
+
for (const t of this.confirmTimers.values())
|
|
303
|
+
clearTimeout(t);
|
|
304
|
+
this.confirmTimers.clear();
|
|
291
305
|
this.stateStore.set({
|
|
292
306
|
...defaultState,
|
|
293
307
|
hideThinking: !!this.config.hideThinking,
|
|
@@ -667,6 +681,19 @@ export class WhereverClient {
|
|
|
667
681
|
: m);
|
|
668
682
|
}
|
|
669
683
|
else if (msg.content) {
|
|
684
|
+
// The server echoes the user's own message back once pi has appended
|
|
685
|
+
// it: that is the delivery CONFIRMATION for an optimistic (unconfirmed)
|
|
686
|
+
// echo. Confirm the matching pending message (flip delivery off, clear
|
|
687
|
+
// its watchdog, update the persisted-pending store) instead of adding
|
|
688
|
+
// a duplicate. If there was no pending match (e.g. another client sent
|
|
689
|
+
// it), fall back to the existing content-dedupe.
|
|
690
|
+
if (msg.role === 'user') {
|
|
691
|
+
const confirmedPending = this.confirmDeliveredByContent(msg.content);
|
|
692
|
+
if (confirmedPending) {
|
|
693
|
+
// Re-read: confirmDeliveredByContent already updated the store.
|
|
694
|
+
return get(this.stateStore);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
670
697
|
const lastUserMessage = [...newMessages]
|
|
671
698
|
.reverse()
|
|
672
699
|
.find((m) => m.role === 'user');
|
|
@@ -695,10 +722,22 @@ export class WhereverClient {
|
|
|
695
722
|
this.agentEndTimeout = null;
|
|
696
723
|
}
|
|
697
724
|
this.agentEndTimeout = setTimeout(() => {
|
|
725
|
+
const now = Date.now();
|
|
698
726
|
this.stateStore.update((s) => ({
|
|
699
727
|
...s,
|
|
700
728
|
isStreaming: false,
|
|
701
|
-
messages: s.messages.map((m) => m.isStreaming
|
|
729
|
+
messages: s.messages.map((m) => m.isStreaming
|
|
730
|
+
? {
|
|
731
|
+
...m,
|
|
732
|
+
isStreaming: false,
|
|
733
|
+
// Freeze a still-running tool's duration if it never got a
|
|
734
|
+
// tool_end (turn ended between steps), so "Elapsed" stops
|
|
735
|
+
// ticking and shows the final "Took".
|
|
736
|
+
endedAt: m.role === 'tool' && m.endedAt === undefined
|
|
737
|
+
? now
|
|
738
|
+
: m.endedAt,
|
|
739
|
+
}
|
|
740
|
+
: m),
|
|
702
741
|
}));
|
|
703
742
|
this.agentEndTimeout = null;
|
|
704
743
|
}, 300);
|
|
@@ -718,17 +757,19 @@ export class WhereverClient {
|
|
|
718
757
|
const finalizedMessages = s.messages.map((m) => m.isStreaming && (m.role === 'assistant' || m.role === 'thinking')
|
|
719
758
|
? { ...m, isStreaming: false }
|
|
720
759
|
: m);
|
|
760
|
+
const startedAt = Date.now();
|
|
721
761
|
const newMsg = {
|
|
722
762
|
id: this.generateId(),
|
|
723
763
|
role: 'tool',
|
|
724
764
|
content: toolArgs
|
|
725
765
|
? `$ ${msg.toolName} ${toolArgs}`
|
|
726
766
|
: `$ ${msg.toolName}`,
|
|
727
|
-
timestamp:
|
|
767
|
+
timestamp: startedAt,
|
|
728
768
|
isStreaming: true,
|
|
729
769
|
toolName: msg.toolName,
|
|
730
770
|
toolArgs: toolArgs,
|
|
731
771
|
toolOutput: '',
|
|
772
|
+
startedAt,
|
|
732
773
|
};
|
|
733
774
|
return {
|
|
734
775
|
...s,
|
|
@@ -769,6 +810,7 @@ export class WhereverClient {
|
|
|
769
810
|
.find((m) => m.role === 'tool' &&
|
|
770
811
|
m.toolName === msg.toolName &&
|
|
771
812
|
!m.content.startsWith('Tool error:'));
|
|
813
|
+
const endedAt = Date.now();
|
|
772
814
|
if (toolMsg) {
|
|
773
815
|
const errorPrefix = msg.isError ? 'Error: ' : '';
|
|
774
816
|
return {
|
|
@@ -780,6 +822,7 @@ export class WhereverClient {
|
|
|
780
822
|
isStreaming: false,
|
|
781
823
|
isError: msg.isError,
|
|
782
824
|
toolOutput: result,
|
|
825
|
+
endedAt,
|
|
783
826
|
}
|
|
784
827
|
: m),
|
|
785
828
|
};
|
|
@@ -792,12 +835,13 @@ export class WhereverClient {
|
|
|
792
835
|
id: this.generateId(),
|
|
793
836
|
role: 'tool',
|
|
794
837
|
content,
|
|
795
|
-
timestamp:
|
|
838
|
+
timestamp: endedAt,
|
|
796
839
|
isStreaming: false,
|
|
797
840
|
toolName: msg.toolName,
|
|
798
841
|
toolArgs: '',
|
|
799
842
|
toolOutput: result,
|
|
800
843
|
isError: msg.isError,
|
|
844
|
+
endedAt,
|
|
801
845
|
};
|
|
802
846
|
return {
|
|
803
847
|
...s,
|
|
@@ -807,13 +851,23 @@ export class WhereverClient {
|
|
|
807
851
|
});
|
|
808
852
|
break;
|
|
809
853
|
}
|
|
810
|
-
case 'aborted':
|
|
854
|
+
case 'aborted': {
|
|
855
|
+
const abortedAt = Date.now();
|
|
811
856
|
this.stateStore.update((s) => ({
|
|
812
857
|
...s,
|
|
813
858
|
isStreaming: false,
|
|
814
|
-
messages: s.messages.map((m) => m.isStreaming
|
|
859
|
+
messages: s.messages.map((m) => m.isStreaming
|
|
860
|
+
? {
|
|
861
|
+
...m,
|
|
862
|
+
isStreaming: false,
|
|
863
|
+
endedAt: m.role === 'tool' && m.endedAt === undefined
|
|
864
|
+
? abortedAt
|
|
865
|
+
: m.endedAt,
|
|
866
|
+
}
|
|
867
|
+
: m),
|
|
815
868
|
}));
|
|
816
869
|
break;
|
|
870
|
+
}
|
|
817
871
|
case 'session_created':
|
|
818
872
|
this.stateStore.update((s) => ({
|
|
819
873
|
...s,
|
|
@@ -922,14 +976,40 @@ export class WhereverClient {
|
|
|
922
976
|
agentPending: false,
|
|
923
977
|
}));
|
|
924
978
|
break;
|
|
925
|
-
case 'message_history':
|
|
979
|
+
case 'message_history': {
|
|
980
|
+
// The server transcript is authoritative for what was actually persisted.
|
|
981
|
+
// Reconcile it against any unconfirmed outbound messages: keep the ones
|
|
982
|
+
// that ARE in history (delivered), and re-surface the ones that are NOT
|
|
983
|
+
// as recoverable 'failed' items so a message a half-open socket swallowed
|
|
984
|
+
// is never silently lost across a reload/resync.
|
|
985
|
+
const sessionIdForPending = msg.sessionId;
|
|
986
|
+
// Carry-over from the CURRENT store (this-tab sends still in flight) plus
|
|
987
|
+
// anything a PREVIOUS tab persisted before a reload.
|
|
988
|
+
const inFlight = get(this.stateStore).messages.filter((m) => m.role === 'user' && m.delivery !== undefined);
|
|
989
|
+
const persisted = this.loadPersistedPending(sessionIdForPending);
|
|
990
|
+
const candidates = [...persisted, ...inFlight];
|
|
926
991
|
this.stateStore.update((s) => {
|
|
927
992
|
const mapped = this.mapHistory(msg.messages, msg.sessionId, s.isStreaming);
|
|
928
993
|
const totalCount = typeof msg.totalCount === 'number' ? msg.totalCount : mapped.length;
|
|
929
994
|
const offset = typeof msg.offset === 'number' ? msg.offset : 0;
|
|
995
|
+
const historyContents = new Set(mapped.filter((m) => m.role === 'user').map((m) => m.content));
|
|
996
|
+
// Unconfirmed candidates whose content is NOT in the loaded history are
|
|
997
|
+
// undelivered. De-dupe by content so two identical undelivered sends do
|
|
998
|
+
// not multiply. Everything else the server persisted is already in
|
|
999
|
+
// `mapped` (confirmed).
|
|
1000
|
+
const seen = new Set();
|
|
1001
|
+
const undelivered = [];
|
|
1002
|
+
for (const c of candidates) {
|
|
1003
|
+
if (historyContents.has(c.content))
|
|
1004
|
+
continue;
|
|
1005
|
+
if (seen.has(c.content))
|
|
1006
|
+
continue;
|
|
1007
|
+
seen.add(c.content);
|
|
1008
|
+
undelivered.push({ ...c, sessionId: sessionIdForPending, delivery: 'failed' });
|
|
1009
|
+
}
|
|
930
1010
|
return {
|
|
931
1011
|
...s,
|
|
932
|
-
messages: mapped,
|
|
1012
|
+
messages: [...mapped, ...undelivered],
|
|
933
1013
|
historyTotalCount: totalCount,
|
|
934
1014
|
historyOffset: offset,
|
|
935
1015
|
loadingMoreHistory: false,
|
|
@@ -937,7 +1017,13 @@ export class WhereverClient {
|
|
|
937
1017
|
resyncing: false,
|
|
938
1018
|
};
|
|
939
1019
|
});
|
|
1020
|
+
// Clear watchdogs for anything now confirmed, and rewrite the persisted
|
|
1021
|
+
// store to exactly the still-undelivered set.
|
|
1022
|
+
for (const c of candidates)
|
|
1023
|
+
this.clearConfirm(c.id);
|
|
1024
|
+
this.persistPending(sessionIdForPending);
|
|
940
1025
|
break;
|
|
1026
|
+
}
|
|
941
1027
|
case 'message_history_prepend':
|
|
942
1028
|
this.stateStore.update((s) => {
|
|
943
1029
|
// Older window prepended ahead of currently-loaded messages. No
|
|
@@ -971,6 +1057,10 @@ export class WhereverClient {
|
|
|
971
1057
|
*/
|
|
972
1058
|
mapHistory(rawMessages, sessionId, applyStreamingTail) {
|
|
973
1059
|
const mapped = [];
|
|
1060
|
+
// Each pending tool_call carries its args AND its start timestamp (the ts of
|
|
1061
|
+
// the toolCall entry). When the matching tool_result arrives, startedAt =
|
|
1062
|
+
// the call ts and endedAt = the result ts, so a tool reconstructed from
|
|
1063
|
+
// loaded history shows the same "Took N.Ns" as a live-streamed one.
|
|
974
1064
|
const pendingCalls = {};
|
|
975
1065
|
for (const m of rawMessages) {
|
|
976
1066
|
if (m.role === 'tool_call') {
|
|
@@ -978,13 +1068,14 @@ export class WhereverClient {
|
|
|
978
1068
|
if (!pendingCalls[tName]) {
|
|
979
1069
|
pendingCalls[tName] = [];
|
|
980
1070
|
}
|
|
981
|
-
pendingCalls[tName].push(m.content || '');
|
|
1071
|
+
pendingCalls[tName].push({ args: m.content || '', startedAt: m.timestamp });
|
|
982
1072
|
}
|
|
983
1073
|
else if (m.role === 'tool_result') {
|
|
984
1074
|
const tName = m.toolName || 'unknown';
|
|
985
|
-
const
|
|
1075
|
+
const call = pendingCalls[tName] && pendingCalls[tName].length > 0
|
|
986
1076
|
? pendingCalls[tName].shift()
|
|
987
|
-
:
|
|
1077
|
+
: undefined;
|
|
1078
|
+
const tArgs = call?.args ?? '';
|
|
988
1079
|
mapped.push({
|
|
989
1080
|
id: this.generateId(),
|
|
990
1081
|
role: 'tool',
|
|
@@ -998,6 +1089,15 @@ export class WhereverClient {
|
|
|
998
1089
|
toolOutput: m.content,
|
|
999
1090
|
isError: m.isError,
|
|
1000
1091
|
sessionId,
|
|
1092
|
+
// Duration from the matched call. Only when both timestamps are
|
|
1093
|
+
// finite and coherent (end >= start); otherwise leave unset so the UI
|
|
1094
|
+
// simply shows no duration rather than a bogus one.
|
|
1095
|
+
...(call &&
|
|
1096
|
+
Number.isFinite(call.startedAt) &&
|
|
1097
|
+
Number.isFinite(m.timestamp) &&
|
|
1098
|
+
m.timestamp >= call.startedAt
|
|
1099
|
+
? { startedAt: call.startedAt, endedAt: m.timestamp }
|
|
1100
|
+
: {}),
|
|
1001
1101
|
});
|
|
1002
1102
|
}
|
|
1003
1103
|
else {
|
|
@@ -1012,20 +1112,25 @@ export class WhereverClient {
|
|
|
1012
1112
|
});
|
|
1013
1113
|
}
|
|
1014
1114
|
}
|
|
1015
|
-
for (const [tName,
|
|
1016
|
-
for (const
|
|
1115
|
+
for (const [tName, calls] of Object.entries(pendingCalls)) {
|
|
1116
|
+
for (const call of calls) {
|
|
1017
1117
|
mapped.push({
|
|
1018
1118
|
id: this.generateId(),
|
|
1019
1119
|
role: 'tool',
|
|
1020
|
-
content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
|
|
1120
|
+
content: call.args ? `$ ${tName} ${call.args}` : `$ ${tName}`,
|
|
1021
1121
|
timestamp: mapped.length > 0
|
|
1022
1122
|
? mapped[mapped.length - 1].timestamp + 1
|
|
1023
1123
|
: Date.now(),
|
|
1024
1124
|
isStreaming: applyStreamingTail,
|
|
1025
1125
|
toolName: tName,
|
|
1026
|
-
toolArgs: args,
|
|
1126
|
+
toolArgs: call.args,
|
|
1027
1127
|
toolOutput: '',
|
|
1028
1128
|
sessionId,
|
|
1129
|
+
// An unmatched call (no result yet). Keep its start so a still-running
|
|
1130
|
+
// tool in the streaming tail can tick "Elapsed"; leave endedAt unset.
|
|
1131
|
+
...(Number.isFinite(call.startedAt)
|
|
1132
|
+
? { startedAt: call.startedAt }
|
|
1133
|
+
: {}),
|
|
1029
1134
|
});
|
|
1030
1135
|
}
|
|
1031
1136
|
}
|
|
@@ -1128,6 +1233,11 @@ export class WhereverClient {
|
|
|
1128
1233
|
}));
|
|
1129
1234
|
return false;
|
|
1130
1235
|
}
|
|
1236
|
+
// The frame was handed to an OPEN socket, but that is NOT proof of delivery:
|
|
1237
|
+
// a half-open TCP connection accepts send() (buffers locally, no throw) yet
|
|
1238
|
+
// the bytes never reach the server. So commit the echo as delivery:'sending'
|
|
1239
|
+
// (unconfirmed) and arm a watchdog + persist it, so it is recoverable on
|
|
1240
|
+
// reload and flips to 'failed' if the server never echoes it back.
|
|
1131
1241
|
const message = {
|
|
1132
1242
|
id: this.generateId(),
|
|
1133
1243
|
role: 'user',
|
|
@@ -1135,14 +1245,179 @@ export class WhereverClient {
|
|
|
1135
1245
|
timestamp: Date.now(),
|
|
1136
1246
|
isStreaming: false,
|
|
1137
1247
|
sessionId: s.sessionId,
|
|
1248
|
+
delivery: 'sending',
|
|
1138
1249
|
};
|
|
1139
1250
|
this.stateStore.update((st) => ({
|
|
1140
1251
|
...st,
|
|
1141
1252
|
sessionError: null,
|
|
1142
1253
|
messages: [...st.messages, message],
|
|
1143
1254
|
}));
|
|
1255
|
+
this.armConfirm(message.id);
|
|
1256
|
+
this.persistPending(s.sessionId);
|
|
1144
1257
|
return true;
|
|
1145
1258
|
}
|
|
1259
|
+
// ==========================================================================
|
|
1260
|
+
// Outbound-message delivery confirmation + recovery.
|
|
1261
|
+
//
|
|
1262
|
+
// An optimistic user echo is unconfirmed until the server echoes it back. This
|
|
1263
|
+
// machinery makes an unconfirmed message survive a reload and surface a retry
|
|
1264
|
+
// affordance instead of being silently lost when a half-open socket swallowed
|
|
1265
|
+
// the frame.
|
|
1266
|
+
// ==========================================================================
|
|
1267
|
+
pendingKey(sessionId) {
|
|
1268
|
+
return WhereverClient.PENDING_PREFIX + sessionId;
|
|
1269
|
+
}
|
|
1270
|
+
// Persist the current session's still-unconfirmed (delivery-tagged) user
|
|
1271
|
+
// messages so a reload can recover them. Cleared to empty when none remain.
|
|
1272
|
+
persistPending(sessionId) {
|
|
1273
|
+
if (!sessionId || typeof localStorage === 'undefined')
|
|
1274
|
+
return;
|
|
1275
|
+
const pending = get(this.stateStore).messages.filter((m) => m.role === 'user' && m.delivery !== undefined);
|
|
1276
|
+
try {
|
|
1277
|
+
if (pending.length === 0) {
|
|
1278
|
+
localStorage.removeItem(this.pendingKey(sessionId));
|
|
1279
|
+
}
|
|
1280
|
+
else {
|
|
1281
|
+
localStorage.setItem(this.pendingKey(sessionId), JSON.stringify(pending.map((m) => ({
|
|
1282
|
+
id: m.id,
|
|
1283
|
+
content: m.content,
|
|
1284
|
+
timestamp: m.timestamp,
|
|
1285
|
+
// Persist as 'failed': a reload cannot know if it ever landed, so
|
|
1286
|
+
// it must be presented as needs-attention, never as delivered.
|
|
1287
|
+
delivery: 'failed',
|
|
1288
|
+
}))));
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
catch { }
|
|
1292
|
+
}
|
|
1293
|
+
// Load persisted unconfirmed messages for a session (used on load/resync to
|
|
1294
|
+
// re-surface anything a previous tab left in limbo).
|
|
1295
|
+
loadPersistedPending(sessionId) {
|
|
1296
|
+
if (typeof localStorage === 'undefined')
|
|
1297
|
+
return [];
|
|
1298
|
+
try {
|
|
1299
|
+
const raw = localStorage.getItem(this.pendingKey(sessionId));
|
|
1300
|
+
if (!raw)
|
|
1301
|
+
return [];
|
|
1302
|
+
const arr = JSON.parse(raw);
|
|
1303
|
+
if (!Array.isArray(arr))
|
|
1304
|
+
return [];
|
|
1305
|
+
return arr
|
|
1306
|
+
.filter((m) => m && typeof m.content === 'string')
|
|
1307
|
+
.map((m) => ({
|
|
1308
|
+
id: typeof m.id === 'string' ? m.id : this.generateId(),
|
|
1309
|
+
role: 'user',
|
|
1310
|
+
content: m.content,
|
|
1311
|
+
timestamp: typeof m.timestamp === 'number' ? m.timestamp : Date.now(),
|
|
1312
|
+
isStreaming: false,
|
|
1313
|
+
sessionId,
|
|
1314
|
+
delivery: 'failed',
|
|
1315
|
+
}));
|
|
1316
|
+
}
|
|
1317
|
+
catch {
|
|
1318
|
+
return [];
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
armConfirm(messageId) {
|
|
1322
|
+
this.clearConfirm(messageId);
|
|
1323
|
+
if (typeof setTimeout !== 'function')
|
|
1324
|
+
return;
|
|
1325
|
+
const timer = setTimeout(() => {
|
|
1326
|
+
this.confirmTimers.delete(messageId);
|
|
1327
|
+
// Still unconfirmed after the window: mark it failed so the UI offers a
|
|
1328
|
+
// retry. Delivery is genuinely uncertain (a half-open socket may have
|
|
1329
|
+
// eaten it), so we do NOT auto-resend: that risks a duplicate. The user
|
|
1330
|
+
// decides.
|
|
1331
|
+
let sessionId = null;
|
|
1332
|
+
this.stateStore.update((st) => {
|
|
1333
|
+
const m = st.messages.find((x) => x.id === messageId);
|
|
1334
|
+
if (!m || m.delivery !== 'sending')
|
|
1335
|
+
return st;
|
|
1336
|
+
sessionId = st.sessionId;
|
|
1337
|
+
return {
|
|
1338
|
+
...st,
|
|
1339
|
+
messages: st.messages.map((x) => x.id === messageId ? { ...x, delivery: 'failed' } : x),
|
|
1340
|
+
};
|
|
1341
|
+
});
|
|
1342
|
+
if (sessionId)
|
|
1343
|
+
this.persistPending(sessionId);
|
|
1344
|
+
}, WhereverClient.CONFIRM_MS);
|
|
1345
|
+
if (timer && typeof timer.unref === 'function') {
|
|
1346
|
+
timer.unref();
|
|
1347
|
+
}
|
|
1348
|
+
this.confirmTimers.set(messageId, timer);
|
|
1349
|
+
}
|
|
1350
|
+
clearConfirm(messageId) {
|
|
1351
|
+
const t = this.confirmTimers.get(messageId);
|
|
1352
|
+
if (t) {
|
|
1353
|
+
clearTimeout(t);
|
|
1354
|
+
this.confirmTimers.delete(messageId);
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
// Mark the oldest still-unconfirmed user message with this content as
|
|
1358
|
+
// delivered (the server echoed it back). Content-matched because the server
|
|
1359
|
+
// echo carries no client message id. Returns true if one was confirmed.
|
|
1360
|
+
confirmDeliveredByContent(content) {
|
|
1361
|
+
let confirmedId = null;
|
|
1362
|
+
let sessionId = null;
|
|
1363
|
+
this.stateStore.update((st) => {
|
|
1364
|
+
const target = st.messages.find((m) => m.role === 'user' && m.delivery !== undefined && m.content === content);
|
|
1365
|
+
if (!target)
|
|
1366
|
+
return st;
|
|
1367
|
+
confirmedId = target.id;
|
|
1368
|
+
sessionId = st.sessionId;
|
|
1369
|
+
return {
|
|
1370
|
+
...st,
|
|
1371
|
+
messages: st.messages.map((m) => m.id === target.id ? { ...m, delivery: undefined } : m),
|
|
1372
|
+
};
|
|
1373
|
+
});
|
|
1374
|
+
if (confirmedId) {
|
|
1375
|
+
this.clearConfirm(confirmedId);
|
|
1376
|
+
this.persistPending(sessionId);
|
|
1377
|
+
return true;
|
|
1378
|
+
}
|
|
1379
|
+
return false;
|
|
1380
|
+
}
|
|
1381
|
+
// Retry a failed (or sending) outbound message: re-send its frame and re-arm
|
|
1382
|
+
// confirmation. Returns false if it could not be handed to an OPEN socket (the
|
|
1383
|
+
// message stays failed/recoverable).
|
|
1384
|
+
resendMessage(messageId) {
|
|
1385
|
+
const s = get(this.stateStore);
|
|
1386
|
+
const m = s.messages.find((x) => x.id === messageId && x.role === 'user');
|
|
1387
|
+
if (!m || !s.sessionId)
|
|
1388
|
+
return false;
|
|
1389
|
+
if (!this.getIsConnected()) {
|
|
1390
|
+
if (!this.ws && !this.reconnectTimer)
|
|
1391
|
+
this.scheduleReconnect();
|
|
1392
|
+
return false;
|
|
1393
|
+
}
|
|
1394
|
+
const ok = this.send({ type: 'message', message: m.content, sessionId: s.sessionId });
|
|
1395
|
+
if (!ok)
|
|
1396
|
+
return false;
|
|
1397
|
+
this.stateStore.update((st) => ({
|
|
1398
|
+
...st,
|
|
1399
|
+
sessionError: null,
|
|
1400
|
+
messages: st.messages.map((x) => x.id === messageId ? { ...x, delivery: 'sending', timestamp: Date.now() } : x),
|
|
1401
|
+
}));
|
|
1402
|
+
this.armConfirm(messageId);
|
|
1403
|
+
this.persistPending(s.sessionId);
|
|
1404
|
+
return true;
|
|
1405
|
+
}
|
|
1406
|
+
// Drop a failed outbound message the user chooses not to resend. Removes it
|
|
1407
|
+
// from the transcript and from the persisted-pending store.
|
|
1408
|
+
discardMessage(messageId) {
|
|
1409
|
+
let sessionId = null;
|
|
1410
|
+
this.clearConfirm(messageId);
|
|
1411
|
+
this.stateStore.update((st) => {
|
|
1412
|
+
sessionId = st.sessionId;
|
|
1413
|
+
return {
|
|
1414
|
+
...st,
|
|
1415
|
+
messages: st.messages.filter((m) => m.id !== messageId),
|
|
1416
|
+
};
|
|
1417
|
+
});
|
|
1418
|
+
if (sessionId)
|
|
1419
|
+
this.persistPending(sessionId);
|
|
1420
|
+
}
|
|
1146
1421
|
abort() {
|
|
1147
1422
|
const s = get(this.stateStore);
|
|
1148
1423
|
if (!s.sessionId)
|