@wherever-dev/client 0.3.0 → 0.3.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.
- package/CHANGELOG.md +67 -0
- package/dist/client.d.ts +24 -0
- package/dist/client.js +483 -47
- package/dist/client.js.map +1 -1
- package/dist/types.d.ts +14 -0
- package/package.json +1 -1
- package/src/client.ts +496 -49
- package/src/types.ts +48 -0
- package/test/message-delivery-confirmation.test.ts +194 -0
- package/test/mid-stream-steer.test.ts +91 -0
- package/test/tool-aborted-render.test.ts +170 -0
- package/test/tool-duration-history.test.ts +93 -0
- package/test/tool-duration.test.ts +86 -0
- package/test/tool-interrupted-history.test.ts +294 -0
package/dist/client.js
CHANGED
|
@@ -14,6 +14,7 @@ const defaultState = {
|
|
|
14
14
|
clientId: null,
|
|
15
15
|
conflict: null,
|
|
16
16
|
isInterrupted: false,
|
|
17
|
+
notice: null,
|
|
17
18
|
sessionError: null,
|
|
18
19
|
readOnly: false,
|
|
19
20
|
activeSessionFile: null,
|
|
@@ -84,6 +85,13 @@ export class WhereverClient {
|
|
|
84
85
|
resumeModel;
|
|
85
86
|
listeners = new Set();
|
|
86
87
|
pendingUploads = new Map();
|
|
88
|
+
// Per-message confirmation watchdogs. A user message committed optimistically
|
|
89
|
+
// is only proven delivered when the server echoes it back; if no echo lands
|
|
90
|
+
// within CONFIRM_MS the watchdog flips it to delivery:'failed' so the UI can
|
|
91
|
+
// offer a retry instead of pretending it was sent (the half-open-socket loss).
|
|
92
|
+
confirmTimers = new Map();
|
|
93
|
+
static CONFIRM_MS = 12_000;
|
|
94
|
+
static PENDING_PREFIX = 'wherever-pending:';
|
|
87
95
|
constructor(config) {
|
|
88
96
|
this.config = {
|
|
89
97
|
secure: true,
|
|
@@ -288,6 +296,13 @@ export class WhereverClient {
|
|
|
288
296
|
this.ws = null;
|
|
289
297
|
}
|
|
290
298
|
if (resetState) {
|
|
299
|
+
// Full teardown wipes the store, so no unconfirmed message survives in it;
|
|
300
|
+
// clear their watchdogs to avoid firing against a fresh store. The
|
|
301
|
+
// persisted-pending localStorage entries intentionally REMAIN so a later
|
|
302
|
+
// load can still recover them.
|
|
303
|
+
for (const t of this.confirmTimers.values())
|
|
304
|
+
clearTimeout(t);
|
|
305
|
+
this.confirmTimers.clear();
|
|
291
306
|
this.stateStore.set({
|
|
292
307
|
...defaultState,
|
|
293
308
|
hideThinking: !!this.config.hideThinking,
|
|
@@ -667,6 +682,19 @@ export class WhereverClient {
|
|
|
667
682
|
: m);
|
|
668
683
|
}
|
|
669
684
|
else if (msg.content) {
|
|
685
|
+
// The server echoes the user's own message back once pi has appended
|
|
686
|
+
// it: that is the delivery CONFIRMATION for an optimistic (unconfirmed)
|
|
687
|
+
// echo. Confirm the matching pending message (flip delivery off, clear
|
|
688
|
+
// its watchdog, update the persisted-pending store) instead of adding
|
|
689
|
+
// a duplicate. If there was no pending match (e.g. another client sent
|
|
690
|
+
// it), fall back to the existing content-dedupe.
|
|
691
|
+
if (msg.role === 'user') {
|
|
692
|
+
const confirmedPending = this.confirmDeliveredByContent(msg.content);
|
|
693
|
+
if (confirmedPending) {
|
|
694
|
+
// Re-read: confirmDeliveredByContent already updated the store.
|
|
695
|
+
return get(this.stateStore);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
670
698
|
const lastUserMessage = [...newMessages]
|
|
671
699
|
.reverse()
|
|
672
700
|
.find((m) => m.role === 'user');
|
|
@@ -695,10 +723,29 @@ export class WhereverClient {
|
|
|
695
723
|
this.agentEndTimeout = null;
|
|
696
724
|
}
|
|
697
725
|
this.agentEndTimeout = setTimeout(() => {
|
|
726
|
+
const now = Date.now();
|
|
698
727
|
this.stateStore.update((s) => ({
|
|
699
728
|
...s,
|
|
700
729
|
isStreaming: false,
|
|
701
|
-
messages: s.messages.map((m) => m.isStreaming
|
|
730
|
+
messages: s.messages.map((m) => m.isStreaming
|
|
731
|
+
? {
|
|
732
|
+
...m,
|
|
733
|
+
isStreaming: false,
|
|
734
|
+
// A tool still streaming when the turn ends never got a
|
|
735
|
+
// tool_end (e.g. the turn was aborted, or its result frame
|
|
736
|
+
// was lost): its outcome is unknown. Mark it interrupted
|
|
737
|
+
// (neutral), never let it fall through to a green success
|
|
738
|
+
// tick, which would falsely claim it succeeded. Assistant/
|
|
739
|
+
// thinking messages just stop streaming.
|
|
740
|
+
...(m.role === 'tool' ? { interrupted: true } : {}),
|
|
741
|
+
// Freeze a still-running tool's duration if it never got a
|
|
742
|
+
// tool_end (turn ended between steps), so "Elapsed" stops
|
|
743
|
+
// ticking and shows the final "Took".
|
|
744
|
+
endedAt: m.role === 'tool' && m.endedAt === undefined
|
|
745
|
+
? now
|
|
746
|
+
: m.endedAt,
|
|
747
|
+
}
|
|
748
|
+
: m),
|
|
702
749
|
}));
|
|
703
750
|
this.agentEndTimeout = null;
|
|
704
751
|
}, 300);
|
|
@@ -718,17 +765,19 @@ export class WhereverClient {
|
|
|
718
765
|
const finalizedMessages = s.messages.map((m) => m.isStreaming && (m.role === 'assistant' || m.role === 'thinking')
|
|
719
766
|
? { ...m, isStreaming: false }
|
|
720
767
|
: m);
|
|
768
|
+
const startedAt = Date.now();
|
|
721
769
|
const newMsg = {
|
|
722
770
|
id: this.generateId(),
|
|
723
771
|
role: 'tool',
|
|
724
772
|
content: toolArgs
|
|
725
773
|
? `$ ${msg.toolName} ${toolArgs}`
|
|
726
774
|
: `$ ${msg.toolName}`,
|
|
727
|
-
timestamp:
|
|
775
|
+
timestamp: startedAt,
|
|
728
776
|
isStreaming: true,
|
|
729
777
|
toolName: msg.toolName,
|
|
730
778
|
toolArgs: toolArgs,
|
|
731
779
|
toolOutput: '',
|
|
780
|
+
startedAt,
|
|
732
781
|
};
|
|
733
782
|
return {
|
|
734
783
|
...s,
|
|
@@ -763,14 +812,35 @@ export class WhereverClient {
|
|
|
763
812
|
}
|
|
764
813
|
case 'tool_end': {
|
|
765
814
|
const result = msg.result ? `${msg.result}` : '';
|
|
815
|
+
// An abort (e.g. the web "abort" button killed the tool mid-run) surfaces
|
|
816
|
+
// as isError with a trailing "...aborted" status. That is not a tool
|
|
817
|
+
// FAILURE, so render it as the neutral interrupted state, not a red
|
|
818
|
+
// error.
|
|
819
|
+
const aborted = !!msg.isError && this.isAbortedToolResult(result);
|
|
820
|
+
const effectiveIsError = !!msg.isError && !aborted;
|
|
821
|
+
const toolImages = Array.isArray(msg.images) && msg.images.length > 0
|
|
822
|
+
? msg.images
|
|
823
|
+
: undefined;
|
|
766
824
|
this.stateStore.update((s) => {
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
825
|
+
// Claim the OLDEST still-streaming tool of this name (FIFO). Parallel
|
|
826
|
+
// tool calls share a name, so matching the LAST one (or any already
|
|
827
|
+
// finalized one) would let two tool_end frames land on the SAME
|
|
828
|
+
// message and leave the other tool stuck streaming: it would then be
|
|
829
|
+
// finalized by the 'aborted'/agent_end sweep with no result and render
|
|
830
|
+
// as a bogus green success. Preferring a streaming message means each
|
|
831
|
+
// tool_end settles a distinct in-flight call. Fall back to the newest
|
|
832
|
+
// non-error tool of this name only if none are still streaming.
|
|
833
|
+
const toolMsg = s.messages.find((m) => m.role === 'tool' &&
|
|
770
834
|
m.toolName === msg.toolName &&
|
|
771
|
-
|
|
835
|
+
m.isStreaming) ??
|
|
836
|
+
[...s.messages]
|
|
837
|
+
.reverse()
|
|
838
|
+
.find((m) => m.role === 'tool' &&
|
|
839
|
+
m.toolName === msg.toolName &&
|
|
840
|
+
!m.content.startsWith('Tool error:'));
|
|
841
|
+
const endedAt = Date.now();
|
|
772
842
|
if (toolMsg) {
|
|
773
|
-
const errorPrefix =
|
|
843
|
+
const errorPrefix = effectiveIsError ? 'Error: ' : '';
|
|
774
844
|
return {
|
|
775
845
|
...s,
|
|
776
846
|
messages: s.messages.map((m) => m.id === toolMsg.id
|
|
@@ -778,26 +848,32 @@ export class WhereverClient {
|
|
|
778
848
|
...m,
|
|
779
849
|
content: `${errorPrefix}${m.content}\n${result}`,
|
|
780
850
|
isStreaming: false,
|
|
781
|
-
isError:
|
|
851
|
+
isError: effectiveIsError,
|
|
852
|
+
interrupted: aborted,
|
|
782
853
|
toolOutput: result,
|
|
854
|
+
...(toolImages ? { images: toolImages } : {}),
|
|
855
|
+
endedAt,
|
|
783
856
|
}
|
|
784
857
|
: m),
|
|
785
858
|
};
|
|
786
859
|
}
|
|
787
860
|
else {
|
|
788
|
-
const content =
|
|
861
|
+
const content = effectiveIsError
|
|
789
862
|
? `Tool error: ${msg.toolName}\n${result}`
|
|
790
863
|
: `${msg.toolName}\n${result}`;
|
|
791
864
|
const message = {
|
|
792
865
|
id: this.generateId(),
|
|
793
866
|
role: 'tool',
|
|
794
867
|
content,
|
|
795
|
-
timestamp:
|
|
868
|
+
timestamp: endedAt,
|
|
796
869
|
isStreaming: false,
|
|
797
870
|
toolName: msg.toolName,
|
|
798
871
|
toolArgs: '',
|
|
799
872
|
toolOutput: result,
|
|
800
|
-
|
|
873
|
+
...(toolImages ? { images: toolImages } : {}),
|
|
874
|
+
isError: effectiveIsError,
|
|
875
|
+
interrupted: aborted,
|
|
876
|
+
endedAt,
|
|
801
877
|
};
|
|
802
878
|
return {
|
|
803
879
|
...s,
|
|
@@ -807,13 +883,28 @@ export class WhereverClient {
|
|
|
807
883
|
});
|
|
808
884
|
break;
|
|
809
885
|
}
|
|
810
|
-
case 'aborted':
|
|
886
|
+
case 'aborted': {
|
|
887
|
+
const abortedAt = Date.now();
|
|
811
888
|
this.stateStore.update((s) => ({
|
|
812
889
|
...s,
|
|
813
890
|
isStreaming: false,
|
|
814
|
-
messages: s.messages.map((m) => m.isStreaming
|
|
891
|
+
messages: s.messages.map((m) => m.isStreaming
|
|
892
|
+
? {
|
|
893
|
+
...m,
|
|
894
|
+
isStreaming: false,
|
|
895
|
+
// A tool still streaming when the turn is aborted was killed
|
|
896
|
+
// with no result: mark it interrupted (neutral), never leave
|
|
897
|
+
// it to fall through to a green success tick. Assistant/
|
|
898
|
+
// thinking messages just stop streaming.
|
|
899
|
+
...(m.role === 'tool' ? { interrupted: true } : {}),
|
|
900
|
+
endedAt: m.role === 'tool' && m.endedAt === undefined
|
|
901
|
+
? abortedAt
|
|
902
|
+
: m.endedAt,
|
|
903
|
+
}
|
|
904
|
+
: m),
|
|
815
905
|
}));
|
|
816
906
|
break;
|
|
907
|
+
}
|
|
817
908
|
case 'session_created':
|
|
818
909
|
this.stateStore.update((s) => ({
|
|
819
910
|
...s,
|
|
@@ -860,6 +951,17 @@ export class WhereverClient {
|
|
|
860
951
|
contextUsage: msg.contextUsage ?? null,
|
|
861
952
|
}));
|
|
862
953
|
break;
|
|
954
|
+
case 'session_notice':
|
|
955
|
+
// A non-fatal notice for the active session (e.g. a CLI took over while
|
|
956
|
+
// this session was mid-turn here, discarding the in-flight tool call or
|
|
957
|
+
// streaming reply). Keep the session attached; surface it as a
|
|
958
|
+
// dismissible banner. Ignore a notice for a session we switched away from.
|
|
959
|
+
this.stateStore.update((s) => {
|
|
960
|
+
if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)
|
|
961
|
+
return s;
|
|
962
|
+
return { ...s, notice: { level: msg.level, message: msg.message } };
|
|
963
|
+
});
|
|
964
|
+
break;
|
|
863
965
|
case 'session_destroyed':
|
|
864
966
|
this.stateStore.update((s) => {
|
|
865
967
|
if (s.sessionId === msg.sessionId) {
|
|
@@ -873,6 +975,7 @@ export class WhereverClient {
|
|
|
873
975
|
activeModel: null,
|
|
874
976
|
loadingSession: false,
|
|
875
977
|
agentPending: false,
|
|
978
|
+
notice: null,
|
|
876
979
|
};
|
|
877
980
|
}
|
|
878
981
|
return s;
|
|
@@ -920,16 +1023,43 @@ export class WhereverClient {
|
|
|
920
1023
|
creatingSession: false,
|
|
921
1024
|
loadingSession: false,
|
|
922
1025
|
agentPending: false,
|
|
1026
|
+
notice: null,
|
|
923
1027
|
}));
|
|
924
1028
|
break;
|
|
925
|
-
case 'message_history':
|
|
1029
|
+
case 'message_history': {
|
|
1030
|
+
// The server transcript is authoritative for what was actually persisted.
|
|
1031
|
+
// Reconcile it against any unconfirmed outbound messages: keep the ones
|
|
1032
|
+
// that ARE in history (delivered), and re-surface the ones that are NOT
|
|
1033
|
+
// as recoverable 'failed' items so a message a half-open socket swallowed
|
|
1034
|
+
// is never silently lost across a reload/resync.
|
|
1035
|
+
const sessionIdForPending = msg.sessionId;
|
|
1036
|
+
// Carry-over from the CURRENT store (this-tab sends still in flight) plus
|
|
1037
|
+
// anything a PREVIOUS tab persisted before a reload.
|
|
1038
|
+
const inFlight = get(this.stateStore).messages.filter((m) => m.role === 'user' && m.delivery !== undefined);
|
|
1039
|
+
const persisted = this.loadPersistedPending(sessionIdForPending);
|
|
1040
|
+
const candidates = [...persisted, ...inFlight];
|
|
926
1041
|
this.stateStore.update((s) => {
|
|
927
1042
|
const mapped = this.mapHistory(msg.messages, msg.sessionId, s.isStreaming);
|
|
928
1043
|
const totalCount = typeof msg.totalCount === 'number' ? msg.totalCount : mapped.length;
|
|
929
1044
|
const offset = typeof msg.offset === 'number' ? msg.offset : 0;
|
|
1045
|
+
const historyContents = new Set(mapped.filter((m) => m.role === 'user').map((m) => m.content));
|
|
1046
|
+
// Unconfirmed candidates whose content is NOT in the loaded history are
|
|
1047
|
+
// undelivered. De-dupe by content so two identical undelivered sends do
|
|
1048
|
+
// not multiply. Everything else the server persisted is already in
|
|
1049
|
+
// `mapped` (confirmed).
|
|
1050
|
+
const seen = new Set();
|
|
1051
|
+
const undelivered = [];
|
|
1052
|
+
for (const c of candidates) {
|
|
1053
|
+
if (historyContents.has(c.content))
|
|
1054
|
+
continue;
|
|
1055
|
+
if (seen.has(c.content))
|
|
1056
|
+
continue;
|
|
1057
|
+
seen.add(c.content);
|
|
1058
|
+
undelivered.push({ ...c, sessionId: sessionIdForPending, delivery: 'failed' });
|
|
1059
|
+
}
|
|
930
1060
|
return {
|
|
931
1061
|
...s,
|
|
932
|
-
messages: mapped,
|
|
1062
|
+
messages: [...mapped, ...undelivered],
|
|
933
1063
|
historyTotalCount: totalCount,
|
|
934
1064
|
historyOffset: offset,
|
|
935
1065
|
loadingMoreHistory: false,
|
|
@@ -937,7 +1067,13 @@ export class WhereverClient {
|
|
|
937
1067
|
resyncing: false,
|
|
938
1068
|
};
|
|
939
1069
|
});
|
|
1070
|
+
// Clear watchdogs for anything now confirmed, and rewrite the persisted
|
|
1071
|
+
// store to exactly the still-undelivered set.
|
|
1072
|
+
for (const c of candidates)
|
|
1073
|
+
this.clearConfirm(c.id);
|
|
1074
|
+
this.persistPending(sessionIdForPending);
|
|
940
1075
|
break;
|
|
1076
|
+
}
|
|
941
1077
|
case 'message_history_prepend':
|
|
942
1078
|
this.stateStore.update((s) => {
|
|
943
1079
|
// Older window prepended ahead of currently-loaded messages. No
|
|
@@ -963,6 +1099,24 @@ export class WhereverClient {
|
|
|
963
1099
|
break;
|
|
964
1100
|
}
|
|
965
1101
|
}
|
|
1102
|
+
/**
|
|
1103
|
+
* True when an errored tool result is the product of a USER ABORT (e.g. the
|
|
1104
|
+
* web "abort" button killed a running tool), rather than a genuine tool
|
|
1105
|
+
* failure. The pi tools append a trailing status line on abort ("Command
|
|
1106
|
+
* aborted" for bash, "Operation aborted" for edit/write, bare "aborted" for a
|
|
1107
|
+
* pre-execution abort). We match that trailing status so the UI can render a
|
|
1108
|
+
* neutral "interrupted" state instead of a red error: you cancelling a tool is
|
|
1109
|
+
* not the tool failing. Only meaningful when isError is already true; matched
|
|
1110
|
+
* as the LAST non-empty line to avoid false positives from command output that
|
|
1111
|
+
* merely contains the word "aborted".
|
|
1112
|
+
*/
|
|
1113
|
+
isAbortedToolResult(result) {
|
|
1114
|
+
if (!result)
|
|
1115
|
+
return false;
|
|
1116
|
+
const lines = result.trimEnd().split('\n');
|
|
1117
|
+
const last = (lines[lines.length - 1] || '').trim();
|
|
1118
|
+
return /^(command|operation)?\s*aborted$/i.test(last);
|
|
1119
|
+
}
|
|
966
1120
|
/**
|
|
967
1121
|
* Map a server `HistoryMessage[]` window into UI `ChatMessage[]`. When
|
|
968
1122
|
* `applyStreamingTail` is true, the last assistant/thinking message and any
|
|
@@ -971,34 +1125,134 @@ export class WhereverClient {
|
|
|
971
1125
|
*/
|
|
972
1126
|
mapHistory(rawMessages, sessionId, applyStreamingTail) {
|
|
973
1127
|
const mapped = [];
|
|
974
|
-
|
|
1128
|
+
// A tool_call is rendered IN PLACE, at its position in the stream, as a tool
|
|
1129
|
+
// message that is initially result-less. Its matching tool_result fills it
|
|
1130
|
+
// in later. We track the still-open calls per tool name as indices into
|
|
1131
|
+
// `mapped`, so a call that never receives a result simply stays where it was
|
|
1132
|
+
// issued (correctly marked interrupted below) instead of being hoisted to
|
|
1133
|
+
// the very end of the transcript. The end-hoisting was the bug: dangling
|
|
1134
|
+
// tool calls from EARLIER in the conversation (e.g. an interrupted long-
|
|
1135
|
+
// running bash, later superseded by a new user turn) would all pile up as a
|
|
1136
|
+
// "series of aborted tool calls" AFTER the latest reply, even though the CLI
|
|
1137
|
+
// shows them inline where they happened.
|
|
1138
|
+
//
|
|
1139
|
+
// Matching is by tool-call id when present (the server forwards it on both
|
|
1140
|
+
// tool_call and tool_result), which pairs a result to its EXACT call even
|
|
1141
|
+
// when same-named calls interleave with some left dangling. When the id is
|
|
1142
|
+
// absent (older sessions, or the synthesized bashExecution pair) we fall
|
|
1143
|
+
// back to oldest-open-first per tool name.
|
|
1144
|
+
const openCalls = {};
|
|
1145
|
+
const openById = {};
|
|
1146
|
+
// Drop a resolved call's index from the name-FIFO list so an id match and a
|
|
1147
|
+
// later name-fallback can never both consume the same call.
|
|
1148
|
+
const removeFromNameQueue = (tName, idx) => {
|
|
1149
|
+
const q = openCalls[tName];
|
|
1150
|
+
if (!q)
|
|
1151
|
+
return;
|
|
1152
|
+
const at = q.indexOf(idx);
|
|
1153
|
+
if (at !== -1)
|
|
1154
|
+
q.splice(at, 1);
|
|
1155
|
+
};
|
|
975
1156
|
for (const m of rawMessages) {
|
|
976
1157
|
if (m.role === 'tool_call') {
|
|
977
1158
|
const tName = m.toolName || 'unknown';
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
}
|
|
981
|
-
pendingCalls[tName].push(m.content || '');
|
|
982
|
-
}
|
|
983
|
-
else if (m.role === 'tool_result') {
|
|
984
|
-
const tName = m.toolName || 'unknown';
|
|
985
|
-
const tArgs = pendingCalls[tName] && pendingCalls[tName].length > 0
|
|
986
|
-
? pendingCalls[tName].shift()
|
|
987
|
-
: '';
|
|
1159
|
+
const args = m.content || '';
|
|
1160
|
+
const idx = mapped.length;
|
|
988
1161
|
mapped.push({
|
|
989
1162
|
id: this.generateId(),
|
|
990
1163
|
role: 'tool',
|
|
991
|
-
content:
|
|
992
|
-
? `$ ${tName} ${tArgs}\n${m.content}`
|
|
993
|
-
: `$ ${tName}\n${m.content}`,
|
|
1164
|
+
content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
|
|
994
1165
|
timestamp: m.timestamp,
|
|
1166
|
+
// No result yet. Marked as interrupted below if it stays unmatched;
|
|
1167
|
+
// the streaming tail promotes the last one back to streaming.
|
|
995
1168
|
isStreaming: false,
|
|
996
1169
|
toolName: tName,
|
|
997
|
-
toolArgs:
|
|
998
|
-
toolOutput:
|
|
999
|
-
isError: m.isError,
|
|
1170
|
+
toolArgs: args,
|
|
1171
|
+
toolOutput: '',
|
|
1000
1172
|
sessionId,
|
|
1173
|
+
// Keep the start so a matched result (or a still-running streaming
|
|
1174
|
+
// tail) can show a coherent duration / "Elapsed".
|
|
1175
|
+
...(Number.isFinite(m.timestamp) ? { startedAt: m.timestamp } : {}),
|
|
1001
1176
|
});
|
|
1177
|
+
if (!openCalls[tName])
|
|
1178
|
+
openCalls[tName] = [];
|
|
1179
|
+
openCalls[tName].push(idx);
|
|
1180
|
+
if (typeof m.toolCallId === 'string' && m.toolCallId) {
|
|
1181
|
+
openById[m.toolCallId] = idx;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
else if (m.role === 'tool_result') {
|
|
1185
|
+
const tName = m.toolName || 'unknown';
|
|
1186
|
+
// Prefer an exact id match; else fill the OLDEST still-open call of this
|
|
1187
|
+
// name (FIFO), mirroring how parallel same-named calls resolve in order.
|
|
1188
|
+
let callIdx;
|
|
1189
|
+
if (typeof m.toolCallId === 'string' &&
|
|
1190
|
+
m.toolCallId &&
|
|
1191
|
+
openById[m.toolCallId] !== undefined) {
|
|
1192
|
+
callIdx = openById[m.toolCallId];
|
|
1193
|
+
delete openById[m.toolCallId];
|
|
1194
|
+
removeFromNameQueue(tName, callIdx);
|
|
1195
|
+
}
|
|
1196
|
+
else if (openCalls[tName] && openCalls[tName].length > 0) {
|
|
1197
|
+
callIdx = openCalls[tName].shift();
|
|
1198
|
+
// Keep openById consistent if this call had also registered an id.
|
|
1199
|
+
for (const [id, i] of Object.entries(openById)) {
|
|
1200
|
+
if (i === callIdx)
|
|
1201
|
+
delete openById[id];
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
const isError = m.isError && !this.isAbortedToolResult(m.content);
|
|
1205
|
+
const interrupted = !!m.isError && this.isAbortedToolResult(m.content);
|
|
1206
|
+
if (callIdx !== undefined) {
|
|
1207
|
+
const call = mapped[callIdx];
|
|
1208
|
+
const tArgs = call.toolArgs || '';
|
|
1209
|
+
const startedAt = call.startedAt;
|
|
1210
|
+
mapped[callIdx] = {
|
|
1211
|
+
...call,
|
|
1212
|
+
content: tArgs
|
|
1213
|
+
? `$ ${tName} ${tArgs}\n${m.content}`
|
|
1214
|
+
: `$ ${tName}\n${m.content}`,
|
|
1215
|
+
isStreaming: false,
|
|
1216
|
+
toolOutput: m.content,
|
|
1217
|
+
...(Array.isArray(m.images) && m.images.length > 0
|
|
1218
|
+
? { images: m.images }
|
|
1219
|
+
: {}),
|
|
1220
|
+
// A user abort surfaces as an errored result with a trailing
|
|
1221
|
+
// "...aborted" status. Render it as interrupted (neutral), not a red
|
|
1222
|
+
// error: aborting a tool is not the tool failing.
|
|
1223
|
+
isError,
|
|
1224
|
+
interrupted,
|
|
1225
|
+
timestamp: m.timestamp,
|
|
1226
|
+
// Duration only when both timestamps are finite and coherent
|
|
1227
|
+
// (end >= start); otherwise leave unset rather than show a bogus one.
|
|
1228
|
+
...(startedAt !== undefined &&
|
|
1229
|
+
Number.isFinite(startedAt) &&
|
|
1230
|
+
Number.isFinite(m.timestamp) &&
|
|
1231
|
+
m.timestamp >= startedAt
|
|
1232
|
+
? { endedAt: m.timestamp }
|
|
1233
|
+
: {}),
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
else {
|
|
1237
|
+
// A result with no preceding open call (shouldn't normally happen).
|
|
1238
|
+
// Render it in place as a standalone tool message so nothing is lost.
|
|
1239
|
+
mapped.push({
|
|
1240
|
+
id: this.generateId(),
|
|
1241
|
+
role: 'tool',
|
|
1242
|
+
content: `$ ${tName}\n${m.content}`,
|
|
1243
|
+
timestamp: m.timestamp,
|
|
1244
|
+
isStreaming: false,
|
|
1245
|
+
toolName: tName,
|
|
1246
|
+
toolArgs: '',
|
|
1247
|
+
toolOutput: m.content,
|
|
1248
|
+
...(Array.isArray(m.images) && m.images.length > 0
|
|
1249
|
+
? { images: m.images }
|
|
1250
|
+
: {}),
|
|
1251
|
+
isError,
|
|
1252
|
+
interrupted,
|
|
1253
|
+
sessionId,
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1002
1256
|
}
|
|
1003
1257
|
else {
|
|
1004
1258
|
mapped.push({
|
|
@@ -1012,21 +1266,28 @@ export class WhereverClient {
|
|
|
1012
1266
|
});
|
|
1013
1267
|
}
|
|
1014
1268
|
}
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1269
|
+
// Any call still open (issued a toolCall, never got a tool_result) is FROZEN
|
|
1270
|
+
// in place with no result. Meaning depends on context:
|
|
1271
|
+
// - streaming tail (applyStreamingTail): only the MOST RECENT open call is
|
|
1272
|
+
// plausibly still running; keep it streaming so the UI ticks "Elapsed".
|
|
1273
|
+
// Earlier open calls in the same window are already superseded and are
|
|
1274
|
+
// interrupted.
|
|
1275
|
+
// - otherwise: its outcome is unknown (e.g. a CLI takeover / interruption
|
|
1276
|
+
// killed it mid-run), so mark it `interrupted` for a neutral "no result"
|
|
1277
|
+
// state instead of a bogus green success tick.
|
|
1278
|
+
const allOpen = [];
|
|
1279
|
+
for (const idxs of Object.values(openCalls))
|
|
1280
|
+
allOpen.push(...idxs);
|
|
1281
|
+
allOpen.sort((a, b) => a - b);
|
|
1282
|
+
const lastOpenIdx = applyStreamingTail && allOpen.length > 0
|
|
1283
|
+
? allOpen[allOpen.length - 1]
|
|
1284
|
+
: -1;
|
|
1285
|
+
for (const idx of allOpen) {
|
|
1286
|
+
if (idx === lastOpenIdx) {
|
|
1287
|
+
mapped[idx] = { ...mapped[idx], isStreaming: true };
|
|
1288
|
+
}
|
|
1289
|
+
else {
|
|
1290
|
+
mapped[idx] = { ...mapped[idx], interrupted: true };
|
|
1030
1291
|
}
|
|
1031
1292
|
}
|
|
1032
1293
|
if (applyStreamingTail && mapped.length > 0) {
|
|
@@ -1128,6 +1389,11 @@ export class WhereverClient {
|
|
|
1128
1389
|
}));
|
|
1129
1390
|
return false;
|
|
1130
1391
|
}
|
|
1392
|
+
// The frame was handed to an OPEN socket, but that is NOT proof of delivery:
|
|
1393
|
+
// a half-open TCP connection accepts send() (buffers locally, no throw) yet
|
|
1394
|
+
// the bytes never reach the server. So commit the echo as delivery:'sending'
|
|
1395
|
+
// (unconfirmed) and arm a watchdog + persist it, so it is recoverable on
|
|
1396
|
+
// reload and flips to 'failed' if the server never echoes it back.
|
|
1131
1397
|
const message = {
|
|
1132
1398
|
id: this.generateId(),
|
|
1133
1399
|
role: 'user',
|
|
@@ -1135,14 +1401,179 @@ export class WhereverClient {
|
|
|
1135
1401
|
timestamp: Date.now(),
|
|
1136
1402
|
isStreaming: false,
|
|
1137
1403
|
sessionId: s.sessionId,
|
|
1404
|
+
delivery: 'sending',
|
|
1138
1405
|
};
|
|
1139
1406
|
this.stateStore.update((st) => ({
|
|
1140
1407
|
...st,
|
|
1141
1408
|
sessionError: null,
|
|
1142
1409
|
messages: [...st.messages, message],
|
|
1143
1410
|
}));
|
|
1411
|
+
this.armConfirm(message.id);
|
|
1412
|
+
this.persistPending(s.sessionId);
|
|
1144
1413
|
return true;
|
|
1145
1414
|
}
|
|
1415
|
+
// ==========================================================================
|
|
1416
|
+
// Outbound-message delivery confirmation + recovery.
|
|
1417
|
+
//
|
|
1418
|
+
// An optimistic user echo is unconfirmed until the server echoes it back. This
|
|
1419
|
+
// machinery makes an unconfirmed message survive a reload and surface a retry
|
|
1420
|
+
// affordance instead of being silently lost when a half-open socket swallowed
|
|
1421
|
+
// the frame.
|
|
1422
|
+
// ==========================================================================
|
|
1423
|
+
pendingKey(sessionId) {
|
|
1424
|
+
return WhereverClient.PENDING_PREFIX + sessionId;
|
|
1425
|
+
}
|
|
1426
|
+
// Persist the current session's still-unconfirmed (delivery-tagged) user
|
|
1427
|
+
// messages so a reload can recover them. Cleared to empty when none remain.
|
|
1428
|
+
persistPending(sessionId) {
|
|
1429
|
+
if (!sessionId || typeof localStorage === 'undefined')
|
|
1430
|
+
return;
|
|
1431
|
+
const pending = get(this.stateStore).messages.filter((m) => m.role === 'user' && m.delivery !== undefined);
|
|
1432
|
+
try {
|
|
1433
|
+
if (pending.length === 0) {
|
|
1434
|
+
localStorage.removeItem(this.pendingKey(sessionId));
|
|
1435
|
+
}
|
|
1436
|
+
else {
|
|
1437
|
+
localStorage.setItem(this.pendingKey(sessionId), JSON.stringify(pending.map((m) => ({
|
|
1438
|
+
id: m.id,
|
|
1439
|
+
content: m.content,
|
|
1440
|
+
timestamp: m.timestamp,
|
|
1441
|
+
// Persist as 'failed': a reload cannot know if it ever landed, so
|
|
1442
|
+
// it must be presented as needs-attention, never as delivered.
|
|
1443
|
+
delivery: 'failed',
|
|
1444
|
+
}))));
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
catch { }
|
|
1448
|
+
}
|
|
1449
|
+
// Load persisted unconfirmed messages for a session (used on load/resync to
|
|
1450
|
+
// re-surface anything a previous tab left in limbo).
|
|
1451
|
+
loadPersistedPending(sessionId) {
|
|
1452
|
+
if (typeof localStorage === 'undefined')
|
|
1453
|
+
return [];
|
|
1454
|
+
try {
|
|
1455
|
+
const raw = localStorage.getItem(this.pendingKey(sessionId));
|
|
1456
|
+
if (!raw)
|
|
1457
|
+
return [];
|
|
1458
|
+
const arr = JSON.parse(raw);
|
|
1459
|
+
if (!Array.isArray(arr))
|
|
1460
|
+
return [];
|
|
1461
|
+
return arr
|
|
1462
|
+
.filter((m) => m && typeof m.content === 'string')
|
|
1463
|
+
.map((m) => ({
|
|
1464
|
+
id: typeof m.id === 'string' ? m.id : this.generateId(),
|
|
1465
|
+
role: 'user',
|
|
1466
|
+
content: m.content,
|
|
1467
|
+
timestamp: typeof m.timestamp === 'number' ? m.timestamp : Date.now(),
|
|
1468
|
+
isStreaming: false,
|
|
1469
|
+
sessionId,
|
|
1470
|
+
delivery: 'failed',
|
|
1471
|
+
}));
|
|
1472
|
+
}
|
|
1473
|
+
catch {
|
|
1474
|
+
return [];
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
armConfirm(messageId) {
|
|
1478
|
+
this.clearConfirm(messageId);
|
|
1479
|
+
if (typeof setTimeout !== 'function')
|
|
1480
|
+
return;
|
|
1481
|
+
const timer = setTimeout(() => {
|
|
1482
|
+
this.confirmTimers.delete(messageId);
|
|
1483
|
+
// Still unconfirmed after the window: mark it failed so the UI offers a
|
|
1484
|
+
// retry. Delivery is genuinely uncertain (a half-open socket may have
|
|
1485
|
+
// eaten it), so we do NOT auto-resend: that risks a duplicate. The user
|
|
1486
|
+
// decides.
|
|
1487
|
+
let sessionId = null;
|
|
1488
|
+
this.stateStore.update((st) => {
|
|
1489
|
+
const m = st.messages.find((x) => x.id === messageId);
|
|
1490
|
+
if (!m || m.delivery !== 'sending')
|
|
1491
|
+
return st;
|
|
1492
|
+
sessionId = st.sessionId;
|
|
1493
|
+
return {
|
|
1494
|
+
...st,
|
|
1495
|
+
messages: st.messages.map((x) => x.id === messageId ? { ...x, delivery: 'failed' } : x),
|
|
1496
|
+
};
|
|
1497
|
+
});
|
|
1498
|
+
if (sessionId)
|
|
1499
|
+
this.persistPending(sessionId);
|
|
1500
|
+
}, WhereverClient.CONFIRM_MS);
|
|
1501
|
+
if (timer && typeof timer.unref === 'function') {
|
|
1502
|
+
timer.unref();
|
|
1503
|
+
}
|
|
1504
|
+
this.confirmTimers.set(messageId, timer);
|
|
1505
|
+
}
|
|
1506
|
+
clearConfirm(messageId) {
|
|
1507
|
+
const t = this.confirmTimers.get(messageId);
|
|
1508
|
+
if (t) {
|
|
1509
|
+
clearTimeout(t);
|
|
1510
|
+
this.confirmTimers.delete(messageId);
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
// Mark the oldest still-unconfirmed user message with this content as
|
|
1514
|
+
// delivered (the server echoed it back). Content-matched because the server
|
|
1515
|
+
// echo carries no client message id. Returns true if one was confirmed.
|
|
1516
|
+
confirmDeliveredByContent(content) {
|
|
1517
|
+
let confirmedId = null;
|
|
1518
|
+
let sessionId = null;
|
|
1519
|
+
this.stateStore.update((st) => {
|
|
1520
|
+
const target = st.messages.find((m) => m.role === 'user' && m.delivery !== undefined && m.content === content);
|
|
1521
|
+
if (!target)
|
|
1522
|
+
return st;
|
|
1523
|
+
confirmedId = target.id;
|
|
1524
|
+
sessionId = st.sessionId;
|
|
1525
|
+
return {
|
|
1526
|
+
...st,
|
|
1527
|
+
messages: st.messages.map((m) => m.id === target.id ? { ...m, delivery: undefined } : m),
|
|
1528
|
+
};
|
|
1529
|
+
});
|
|
1530
|
+
if (confirmedId) {
|
|
1531
|
+
this.clearConfirm(confirmedId);
|
|
1532
|
+
this.persistPending(sessionId);
|
|
1533
|
+
return true;
|
|
1534
|
+
}
|
|
1535
|
+
return false;
|
|
1536
|
+
}
|
|
1537
|
+
// Retry a failed (or sending) outbound message: re-send its frame and re-arm
|
|
1538
|
+
// confirmation. Returns false if it could not be handed to an OPEN socket (the
|
|
1539
|
+
// message stays failed/recoverable).
|
|
1540
|
+
resendMessage(messageId) {
|
|
1541
|
+
const s = get(this.stateStore);
|
|
1542
|
+
const m = s.messages.find((x) => x.id === messageId && x.role === 'user');
|
|
1543
|
+
if (!m || !s.sessionId)
|
|
1544
|
+
return false;
|
|
1545
|
+
if (!this.getIsConnected()) {
|
|
1546
|
+
if (!this.ws && !this.reconnectTimer)
|
|
1547
|
+
this.scheduleReconnect();
|
|
1548
|
+
return false;
|
|
1549
|
+
}
|
|
1550
|
+
const ok = this.send({ type: 'message', message: m.content, sessionId: s.sessionId });
|
|
1551
|
+
if (!ok)
|
|
1552
|
+
return false;
|
|
1553
|
+
this.stateStore.update((st) => ({
|
|
1554
|
+
...st,
|
|
1555
|
+
sessionError: null,
|
|
1556
|
+
messages: st.messages.map((x) => x.id === messageId ? { ...x, delivery: 'sending', timestamp: Date.now() } : x),
|
|
1557
|
+
}));
|
|
1558
|
+
this.armConfirm(messageId);
|
|
1559
|
+
this.persistPending(s.sessionId);
|
|
1560
|
+
return true;
|
|
1561
|
+
}
|
|
1562
|
+
// Drop a failed outbound message the user chooses not to resend. Removes it
|
|
1563
|
+
// from the transcript and from the persisted-pending store.
|
|
1564
|
+
discardMessage(messageId) {
|
|
1565
|
+
let sessionId = null;
|
|
1566
|
+
this.clearConfirm(messageId);
|
|
1567
|
+
this.stateStore.update((st) => {
|
|
1568
|
+
sessionId = st.sessionId;
|
|
1569
|
+
return {
|
|
1570
|
+
...st,
|
|
1571
|
+
messages: st.messages.filter((m) => m.id !== messageId),
|
|
1572
|
+
};
|
|
1573
|
+
});
|
|
1574
|
+
if (sessionId)
|
|
1575
|
+
this.persistPending(sessionId);
|
|
1576
|
+
}
|
|
1146
1577
|
abort() {
|
|
1147
1578
|
const s = get(this.stateStore);
|
|
1148
1579
|
if (!s.sessionId)
|
|
@@ -1191,6 +1622,7 @@ export class WhereverClient {
|
|
|
1191
1622
|
readOnly: false,
|
|
1192
1623
|
conflict: null,
|
|
1193
1624
|
sessionError: null,
|
|
1625
|
+
notice: null,
|
|
1194
1626
|
creatingSession: false,
|
|
1195
1627
|
resyncing: false,
|
|
1196
1628
|
agentPending: false,
|
|
@@ -1250,6 +1682,7 @@ export class WhereverClient {
|
|
|
1250
1682
|
activeCwd: null,
|
|
1251
1683
|
activeModel: null,
|
|
1252
1684
|
readOnly: false,
|
|
1685
|
+
notice: null,
|
|
1253
1686
|
creatingSession: false,
|
|
1254
1687
|
loadingSession: false,
|
|
1255
1688
|
resyncing: false,
|
|
@@ -1286,6 +1719,9 @@ export class WhereverClient {
|
|
|
1286
1719
|
dismissSessionError() {
|
|
1287
1720
|
this.stateStore.update((s) => ({ ...s, sessionError: null }));
|
|
1288
1721
|
}
|
|
1722
|
+
dismissNotice() {
|
|
1723
|
+
this.stateStore.update((s) => ({ ...s, notice: null }));
|
|
1724
|
+
}
|
|
1289
1725
|
changeModel(model) {
|
|
1290
1726
|
this.send({ type: 'model_change', model });
|
|
1291
1727
|
}
|