@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/src/client.ts CHANGED
@@ -26,6 +26,7 @@ const defaultState: WhereverState = {
26
26
  clientId: null,
27
27
  conflict: null,
28
28
  isInterrupted: false,
29
+ notice: null,
29
30
  sessionError: null,
30
31
  readOnly: false,
31
32
  activeSessionFile: null,
@@ -97,6 +98,13 @@ export class WhereverClient {
97
98
  private resumeModel?: string;
98
99
  private listeners = new Set<(msg: any) => void>();
99
100
  private pendingUploads = new Map<string, {resolve: (val: any) => void, reject: (err: any) => void}>();
101
+ // Per-message confirmation watchdogs. A user message committed optimistically
102
+ // is only proven delivered when the server echoes it back; if no echo lands
103
+ // within CONFIRM_MS the watchdog flips it to delivery:'failed' so the UI can
104
+ // offer a retry instead of pretending it was sent (the half-open-socket loss).
105
+ private confirmTimers = new Map<string, ReturnType<typeof setTimeout>>();
106
+ private static readonly CONFIRM_MS = 12_000;
107
+ private static readonly PENDING_PREFIX = 'wherever-pending:';
100
108
 
101
109
  constructor(config: WhereverClientConfig) {
102
110
  this.config = {
@@ -311,6 +319,12 @@ export class WhereverClient {
311
319
  }
312
320
 
313
321
  if (resetState) {
322
+ // Full teardown wipes the store, so no unconfirmed message survives in it;
323
+ // clear their watchdogs to avoid firing against a fresh store. The
324
+ // persisted-pending localStorage entries intentionally REMAIN so a later
325
+ // load can still recover them.
326
+ for (const t of this.confirmTimers.values()) clearTimeout(t);
327
+ this.confirmTimers.clear();
314
328
  this.stateStore.set({
315
329
  ...defaultState,
316
330
  hideThinking: !!this.config.hideThinking,
@@ -723,6 +737,19 @@ export class WhereverClient {
723
737
  : m,
724
738
  );
725
739
  } else if (msg.content) {
740
+ // The server echoes the user's own message back once pi has appended
741
+ // it: that is the delivery CONFIRMATION for an optimistic (unconfirmed)
742
+ // echo. Confirm the matching pending message (flip delivery off, clear
743
+ // its watchdog, update the persisted-pending store) instead of adding
744
+ // a duplicate. If there was no pending match (e.g. another client sent
745
+ // it), fall back to the existing content-dedupe.
746
+ if (msg.role === 'user') {
747
+ const confirmedPending = this.confirmDeliveredByContent(msg.content);
748
+ if (confirmedPending) {
749
+ // Re-read: confirmDeliveredByContent already updated the store.
750
+ return get(this.stateStore);
751
+ }
752
+ }
726
753
  const lastUserMessage = [...newMessages]
727
754
  .reverse()
728
755
  .find((m) => m.role === 'user');
@@ -755,11 +782,31 @@ export class WhereverClient {
755
782
  this.agentEndTimeout = null;
756
783
  }
757
784
  this.agentEndTimeout = setTimeout(() => {
785
+ const now = Date.now();
758
786
  this.stateStore.update((s: WhereverState) => ({
759
787
  ...s,
760
788
  isStreaming: false,
761
789
  messages: s.messages.map((m: ChatMessage) =>
762
- m.isStreaming ? {...m, isStreaming: false} : m,
790
+ m.isStreaming
791
+ ? {
792
+ ...m,
793
+ isStreaming: false,
794
+ // A tool still streaming when the turn ends never got a
795
+ // tool_end (e.g. the turn was aborted, or its result frame
796
+ // was lost): its outcome is unknown. Mark it interrupted
797
+ // (neutral), never let it fall through to a green success
798
+ // tick, which would falsely claim it succeeded. Assistant/
799
+ // thinking messages just stop streaming.
800
+ ...(m.role === 'tool' ? {interrupted: true} : {}),
801
+ // Freeze a still-running tool's duration if it never got a
802
+ // tool_end (turn ended between steps), so "Elapsed" stops
803
+ // ticking and shows the final "Took".
804
+ endedAt:
805
+ m.role === 'tool' && m.endedAt === undefined
806
+ ? now
807
+ : m.endedAt,
808
+ }
809
+ : m,
763
810
  ),
764
811
  }));
765
812
  this.agentEndTimeout = null;
@@ -783,17 +830,19 @@ export class WhereverClient {
783
830
  ? {...m, isStreaming: false}
784
831
  : m,
785
832
  );
833
+ const startedAt = Date.now();
786
834
  const newMsg: ChatMessage = {
787
835
  id: this.generateId(),
788
836
  role: 'tool',
789
837
  content: toolArgs
790
838
  ? `$ ${msg.toolName} ${toolArgs}`
791
839
  : `$ ${msg.toolName}`,
792
- timestamp: Date.now(),
840
+ timestamp: startedAt,
793
841
  isStreaming: true,
794
842
  toolName: msg.toolName,
795
843
  toolArgs: toolArgs,
796
844
  toolOutput: '',
845
+ startedAt,
797
846
  };
798
847
  return {
799
848
  ...s,
@@ -835,17 +884,43 @@ export class WhereverClient {
835
884
 
836
885
  case 'tool_end': {
837
886
  const result = msg.result ? `${msg.result}` : '';
887
+ // An abort (e.g. the web "abort" button killed the tool mid-run) surfaces
888
+ // as isError with a trailing "...aborted" status. That is not a tool
889
+ // FAILURE, so render it as the neutral interrupted state, not a red
890
+ // error.
891
+ const aborted = !!msg.isError && this.isAbortedToolResult(result);
892
+ const effectiveIsError = !!msg.isError && !aborted;
893
+ const toolImages =
894
+ Array.isArray(msg.images) && msg.images.length > 0
895
+ ? msg.images
896
+ : undefined;
838
897
  this.stateStore.update((s: WhereverState) => {
839
- const toolMsg = [...s.messages]
840
- .reverse()
841
- .find(
898
+ // Claim the OLDEST still-streaming tool of this name (FIFO). Parallel
899
+ // tool calls share a name, so matching the LAST one (or any already
900
+ // finalized one) would let two tool_end frames land on the SAME
901
+ // message and leave the other tool stuck streaming: it would then be
902
+ // finalized by the 'aborted'/agent_end sweep with no result and render
903
+ // as a bogus green success. Preferring a streaming message means each
904
+ // tool_end settles a distinct in-flight call. Fall back to the newest
905
+ // non-error tool of this name only if none are still streaming.
906
+ const toolMsg =
907
+ s.messages.find(
842
908
  (m: ChatMessage) =>
843
909
  m.role === 'tool' &&
844
910
  m.toolName === msg.toolName &&
845
- !m.content.startsWith('Tool error:'),
846
- );
911
+ m.isStreaming,
912
+ ) ??
913
+ [...s.messages]
914
+ .reverse()
915
+ .find(
916
+ (m: ChatMessage) =>
917
+ m.role === 'tool' &&
918
+ m.toolName === msg.toolName &&
919
+ !m.content.startsWith('Tool error:'),
920
+ );
921
+ const endedAt = Date.now();
847
922
  if (toolMsg) {
848
- const errorPrefix = msg.isError ? 'Error: ' : '';
923
+ const errorPrefix = effectiveIsError ? 'Error: ' : '';
849
924
  return {
850
925
  ...s,
851
926
  messages: s.messages.map((m: ChatMessage) =>
@@ -854,26 +929,32 @@ export class WhereverClient {
854
929
  ...m,
855
930
  content: `${errorPrefix}${m.content}\n${result}`,
856
931
  isStreaming: false,
857
- isError: msg.isError,
932
+ isError: effectiveIsError,
933
+ interrupted: aborted,
858
934
  toolOutput: result,
935
+ ...(toolImages ? {images: toolImages} : {}),
936
+ endedAt,
859
937
  }
860
938
  : m,
861
939
  ),
862
940
  };
863
941
  } else {
864
- const content = msg.isError
942
+ const content = effectiveIsError
865
943
  ? `Tool error: ${msg.toolName}\n${result}`
866
944
  : `${msg.toolName}\n${result}`;
867
945
  const message: ChatMessage = {
868
946
  id: this.generateId(),
869
947
  role: 'tool',
870
948
  content,
871
- timestamp: Date.now(),
949
+ timestamp: endedAt,
872
950
  isStreaming: false,
873
951
  toolName: msg.toolName,
874
952
  toolArgs: '',
875
953
  toolOutput: result,
876
- isError: msg.isError,
954
+ ...(toolImages ? {images: toolImages} : {}),
955
+ isError: effectiveIsError,
956
+ interrupted: aborted,
957
+ endedAt,
877
958
  };
878
959
  return {
879
960
  ...s,
@@ -884,15 +965,31 @@ export class WhereverClient {
884
965
  break;
885
966
  }
886
967
 
887
- case 'aborted':
968
+ case 'aborted': {
969
+ const abortedAt = Date.now();
888
970
  this.stateStore.update((s: WhereverState) => ({
889
971
  ...s,
890
972
  isStreaming: false,
891
973
  messages: s.messages.map((m: ChatMessage) =>
892
- m.isStreaming ? {...m, isStreaming: false} : m,
974
+ m.isStreaming
975
+ ? {
976
+ ...m,
977
+ isStreaming: false,
978
+ // A tool still streaming when the turn is aborted was killed
979
+ // with no result: mark it interrupted (neutral), never leave
980
+ // it to fall through to a green success tick. Assistant/
981
+ // thinking messages just stop streaming.
982
+ ...(m.role === 'tool' ? {interrupted: true} : {}),
983
+ endedAt:
984
+ m.role === 'tool' && m.endedAt === undefined
985
+ ? abortedAt
986
+ : m.endedAt,
987
+ }
988
+ : m,
893
989
  ),
894
990
  }));
895
991
  break;
992
+ }
896
993
 
897
994
  case 'session_created':
898
995
  this.stateStore.update((s: WhereverState) => ({
@@ -943,6 +1040,17 @@ export class WhereverClient {
943
1040
  }));
944
1041
  break;
945
1042
 
1043
+ case 'session_notice':
1044
+ // A non-fatal notice for the active session (e.g. a CLI took over while
1045
+ // this session was mid-turn here, discarding the in-flight tool call or
1046
+ // streaming reply). Keep the session attached; surface it as a
1047
+ // dismissible banner. Ignore a notice for a session we switched away from.
1048
+ this.stateStore.update((s: WhereverState) => {
1049
+ if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId) return s;
1050
+ return { ...s, notice: { level: msg.level, message: msg.message } };
1051
+ });
1052
+ break;
1053
+
946
1054
  case 'session_destroyed':
947
1055
  this.stateStore.update((s: WhereverState) => {
948
1056
  if (s.sessionId === msg.sessionId) {
@@ -956,6 +1064,7 @@ export class WhereverClient {
956
1064
  activeModel: null,
957
1065
  loadingSession: false,
958
1066
  agentPending: false,
1067
+ notice: null,
959
1068
  };
960
1069
  }
961
1070
  return s;
@@ -1006,18 +1115,47 @@ export class WhereverClient {
1006
1115
  creatingSession: false,
1007
1116
  loadingSession: false,
1008
1117
  agentPending: false,
1118
+ notice: null,
1009
1119
  }));
1010
1120
  break;
1011
1121
 
1012
- case 'message_history':
1122
+ case 'message_history': {
1123
+ // The server transcript is authoritative for what was actually persisted.
1124
+ // Reconcile it against any unconfirmed outbound messages: keep the ones
1125
+ // that ARE in history (delivered), and re-surface the ones that are NOT
1126
+ // as recoverable 'failed' items so a message a half-open socket swallowed
1127
+ // is never silently lost across a reload/resync.
1128
+ const sessionIdForPending = msg.sessionId as string;
1129
+ // Carry-over from the CURRENT store (this-tab sends still in flight) plus
1130
+ // anything a PREVIOUS tab persisted before a reload.
1131
+ const inFlight = get(this.stateStore).messages.filter(
1132
+ (m) => m.role === 'user' && m.delivery !== undefined,
1133
+ );
1134
+ const persisted = this.loadPersistedPending(sessionIdForPending);
1135
+ const candidates = [...persisted, ...inFlight];
1013
1136
  this.stateStore.update((s: WhereverState) => {
1014
1137
  const mapped = this.mapHistory(msg.messages, msg.sessionId, s.isStreaming);
1015
1138
  const totalCount =
1016
1139
  typeof msg.totalCount === 'number' ? msg.totalCount : mapped.length;
1017
1140
  const offset = typeof msg.offset === 'number' ? msg.offset : 0;
1141
+ const historyContents = new Set(
1142
+ mapped.filter((m) => m.role === 'user').map((m) => m.content),
1143
+ );
1144
+ // Unconfirmed candidates whose content is NOT in the loaded history are
1145
+ // undelivered. De-dupe by content so two identical undelivered sends do
1146
+ // not multiply. Everything else the server persisted is already in
1147
+ // `mapped` (confirmed).
1148
+ const seen = new Set<string>();
1149
+ const undelivered: ChatMessage[] = [];
1150
+ for (const c of candidates) {
1151
+ if (historyContents.has(c.content)) continue;
1152
+ if (seen.has(c.content)) continue;
1153
+ seen.add(c.content);
1154
+ undelivered.push({...c, sessionId: sessionIdForPending, delivery: 'failed'});
1155
+ }
1018
1156
  return {
1019
1157
  ...s,
1020
- messages: mapped,
1158
+ messages: [...mapped, ...undelivered],
1021
1159
  historyTotalCount: totalCount,
1022
1160
  historyOffset: offset,
1023
1161
  loadingMoreHistory: false,
@@ -1025,7 +1163,12 @@ export class WhereverClient {
1025
1163
  resyncing: false,
1026
1164
  };
1027
1165
  });
1166
+ // Clear watchdogs for anything now confirmed, and rewrite the persisted
1167
+ // store to exactly the still-undelivered set.
1168
+ for (const c of candidates) this.clearConfirm(c.id);
1169
+ this.persistPending(sessionIdForPending);
1028
1170
  break;
1171
+ }
1029
1172
 
1030
1173
  case 'message_history_prepend':
1031
1174
  this.stateStore.update((s: WhereverState) => {
@@ -1054,6 +1197,24 @@ export class WhereverClient {
1054
1197
  }
1055
1198
  }
1056
1199
 
1200
+ /**
1201
+ * True when an errored tool result is the product of a USER ABORT (e.g. the
1202
+ * web "abort" button killed a running tool), rather than a genuine tool
1203
+ * failure. The pi tools append a trailing status line on abort ("Command
1204
+ * aborted" for bash, "Operation aborted" for edit/write, bare "aborted" for a
1205
+ * pre-execution abort). We match that trailing status so the UI can render a
1206
+ * neutral "interrupted" state instead of a red error: you cancelling a tool is
1207
+ * not the tool failing. Only meaningful when isError is already true; matched
1208
+ * as the LAST non-empty line to avoid false positives from command output that
1209
+ * merely contains the word "aborted".
1210
+ */
1211
+ private isAbortedToolResult(result: string | undefined): boolean {
1212
+ if (!result) return false;
1213
+ const lines = result.trimEnd().split('\n');
1214
+ const last = (lines[lines.length - 1] || '').trim();
1215
+ return /^(command|operation)?\s*aborted$/i.test(last);
1216
+ }
1217
+
1057
1218
  /**
1058
1219
  * Map a server `HistoryMessage[]` window into UI `ChatMessage[]`. When
1059
1220
  * `applyStreamingTail` is true, the last assistant/thinking message and any
@@ -1066,35 +1227,131 @@ export class WhereverClient {
1066
1227
  applyStreamingTail: boolean,
1067
1228
  ): ChatMessage[] {
1068
1229
  const mapped: ChatMessage[] = [];
1069
- const pendingCalls: Record<string, string[]> = {};
1230
+ // A tool_call is rendered IN PLACE, at its position in the stream, as a tool
1231
+ // message that is initially result-less. Its matching tool_result fills it
1232
+ // in later. We track the still-open calls per tool name as indices into
1233
+ // `mapped`, so a call that never receives a result simply stays where it was
1234
+ // issued (correctly marked interrupted below) instead of being hoisted to
1235
+ // the very end of the transcript. The end-hoisting was the bug: dangling
1236
+ // tool calls from EARLIER in the conversation (e.g. an interrupted long-
1237
+ // running bash, later superseded by a new user turn) would all pile up as a
1238
+ // "series of aborted tool calls" AFTER the latest reply, even though the CLI
1239
+ // shows them inline where they happened.
1240
+ //
1241
+ // Matching is by tool-call id when present (the server forwards it on both
1242
+ // tool_call and tool_result), which pairs a result to its EXACT call even
1243
+ // when same-named calls interleave with some left dangling. When the id is
1244
+ // absent (older sessions, or the synthesized bashExecution pair) we fall
1245
+ // back to oldest-open-first per tool name.
1246
+ const openCalls: Record<string, number[]> = {};
1247
+ const openById: Record<string, number> = {};
1248
+
1249
+ // Drop a resolved call's index from the name-FIFO list so an id match and a
1250
+ // later name-fallback can never both consume the same call.
1251
+ const removeFromNameQueue = (tName: string, idx: number) => {
1252
+ const q = openCalls[tName];
1253
+ if (!q) return;
1254
+ const at = q.indexOf(idx);
1255
+ if (at !== -1) q.splice(at, 1);
1256
+ };
1070
1257
 
1071
1258
  for (const m of rawMessages) {
1072
1259
  if (m.role === 'tool_call') {
1073
1260
  const tName = m.toolName || 'unknown';
1074
- if (!pendingCalls[tName]) {
1075
- pendingCalls[tName] = [];
1076
- }
1077
- pendingCalls[tName].push(m.content || '');
1078
- } else if (m.role === 'tool_result') {
1079
- const tName = m.toolName || 'unknown';
1080
- const tArgs =
1081
- pendingCalls[tName] && pendingCalls[tName].length > 0
1082
- ? pendingCalls[tName].shift()!
1083
- : '';
1261
+ const args = m.content || '';
1262
+ const idx = mapped.length;
1084
1263
  mapped.push({
1085
1264
  id: this.generateId(),
1086
1265
  role: 'tool',
1087
- content: tArgs
1088
- ? `$ ${tName} ${tArgs}\n${m.content}`
1089
- : `$ ${tName}\n${m.content}`,
1266
+ content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
1090
1267
  timestamp: m.timestamp,
1268
+ // No result yet. Marked as interrupted below if it stays unmatched;
1269
+ // the streaming tail promotes the last one back to streaming.
1091
1270
  isStreaming: false,
1092
1271
  toolName: tName,
1093
- toolArgs: tArgs,
1094
- toolOutput: m.content,
1095
- isError: m.isError,
1272
+ toolArgs: args,
1273
+ toolOutput: '',
1096
1274
  sessionId,
1275
+ // Keep the start so a matched result (or a still-running streaming
1276
+ // tail) can show a coherent duration / "Elapsed".
1277
+ ...(Number.isFinite(m.timestamp) ? {startedAt: m.timestamp} : {}),
1097
1278
  });
1279
+ if (!openCalls[tName]) openCalls[tName] = [];
1280
+ openCalls[tName].push(idx);
1281
+ if (typeof m.toolCallId === 'string' && m.toolCallId) {
1282
+ openById[m.toolCallId] = idx;
1283
+ }
1284
+ } else if (m.role === 'tool_result') {
1285
+ const tName = m.toolName || 'unknown';
1286
+ // Prefer an exact id match; else fill the OLDEST still-open call of this
1287
+ // name (FIFO), mirroring how parallel same-named calls resolve in order.
1288
+ let callIdx: number | undefined;
1289
+ if (
1290
+ typeof m.toolCallId === 'string' &&
1291
+ m.toolCallId &&
1292
+ openById[m.toolCallId] !== undefined
1293
+ ) {
1294
+ callIdx = openById[m.toolCallId];
1295
+ delete openById[m.toolCallId];
1296
+ removeFromNameQueue(tName, callIdx);
1297
+ } else if (openCalls[tName] && openCalls[tName].length > 0) {
1298
+ callIdx = openCalls[tName].shift()!;
1299
+ // Keep openById consistent if this call had also registered an id.
1300
+ for (const [id, i] of Object.entries(openById)) {
1301
+ if (i === callIdx) delete openById[id];
1302
+ }
1303
+ }
1304
+ const isError = m.isError && !this.isAbortedToolResult(m.content);
1305
+ const interrupted = !!m.isError && this.isAbortedToolResult(m.content);
1306
+ if (callIdx !== undefined) {
1307
+ const call = mapped[callIdx];
1308
+ const tArgs = call.toolArgs || '';
1309
+ const startedAt = call.startedAt;
1310
+ mapped[callIdx] = {
1311
+ ...call,
1312
+ content: tArgs
1313
+ ? `$ ${tName} ${tArgs}\n${m.content}`
1314
+ : `$ ${tName}\n${m.content}`,
1315
+ isStreaming: false,
1316
+ toolOutput: m.content,
1317
+ ...(Array.isArray(m.images) && m.images.length > 0
1318
+ ? {images: m.images}
1319
+ : {}),
1320
+ // A user abort surfaces as an errored result with a trailing
1321
+ // "...aborted" status. Render it as interrupted (neutral), not a red
1322
+ // error: aborting a tool is not the tool failing.
1323
+ isError,
1324
+ interrupted,
1325
+ timestamp: m.timestamp,
1326
+ // Duration only when both timestamps are finite and coherent
1327
+ // (end >= start); otherwise leave unset rather than show a bogus one.
1328
+ ...(startedAt !== undefined &&
1329
+ Number.isFinite(startedAt) &&
1330
+ Number.isFinite(m.timestamp) &&
1331
+ m.timestamp >= startedAt
1332
+ ? {endedAt: m.timestamp}
1333
+ : {}),
1334
+ };
1335
+ } else {
1336
+ // A result with no preceding open call (shouldn't normally happen).
1337
+ // Render it in place as a standalone tool message so nothing is lost.
1338
+ mapped.push({
1339
+ id: this.generateId(),
1340
+ role: 'tool',
1341
+ content: `$ ${tName}\n${m.content}`,
1342
+ timestamp: m.timestamp,
1343
+ isStreaming: false,
1344
+ toolName: tName,
1345
+ toolArgs: '',
1346
+ toolOutput: m.content,
1347
+ ...(Array.isArray(m.images) && m.images.length > 0
1348
+ ? {images: m.images}
1349
+ : {}),
1350
+ isError,
1351
+ interrupted,
1352
+ sessionId,
1353
+ });
1354
+ }
1098
1355
  } else {
1099
1356
  mapped.push({
1100
1357
  id: this.generateId(),
@@ -1108,22 +1365,27 @@ export class WhereverClient {
1108
1365
  }
1109
1366
  }
1110
1367
 
1111
- for (const [tName, argsList] of Object.entries(pendingCalls)) {
1112
- for (const args of argsList) {
1113
- mapped.push({
1114
- id: this.generateId(),
1115
- role: 'tool',
1116
- content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
1117
- timestamp:
1118
- mapped.length > 0
1119
- ? mapped[mapped.length - 1].timestamp + 1
1120
- : Date.now(),
1121
- isStreaming: applyStreamingTail,
1122
- toolName: tName,
1123
- toolArgs: args,
1124
- toolOutput: '',
1125
- sessionId,
1126
- });
1368
+ // Any call still open (issued a toolCall, never got a tool_result) is FROZEN
1369
+ // in place with no result. Meaning depends on context:
1370
+ // - streaming tail (applyStreamingTail): only the MOST RECENT open call is
1371
+ // plausibly still running; keep it streaming so the UI ticks "Elapsed".
1372
+ // Earlier open calls in the same window are already superseded and are
1373
+ // interrupted.
1374
+ // - otherwise: its outcome is unknown (e.g. a CLI takeover / interruption
1375
+ // killed it mid-run), so mark it `interrupted` for a neutral "no result"
1376
+ // state instead of a bogus green success tick.
1377
+ const allOpen: number[] = [];
1378
+ for (const idxs of Object.values(openCalls)) allOpen.push(...idxs);
1379
+ allOpen.sort((a, b) => a - b);
1380
+ const lastOpenIdx =
1381
+ applyStreamingTail && allOpen.length > 0
1382
+ ? allOpen[allOpen.length - 1]
1383
+ : -1;
1384
+ for (const idx of allOpen) {
1385
+ if (idx === lastOpenIdx) {
1386
+ mapped[idx] = {...mapped[idx], isStreaming: true};
1387
+ } else {
1388
+ mapped[idx] = {...mapped[idx], interrupted: true};
1127
1389
  }
1128
1390
  }
1129
1391
 
@@ -1232,6 +1494,11 @@ export class WhereverClient {
1232
1494
  return false;
1233
1495
  }
1234
1496
 
1497
+ // The frame was handed to an OPEN socket, but that is NOT proof of delivery:
1498
+ // a half-open TCP connection accepts send() (buffers locally, no throw) yet
1499
+ // the bytes never reach the server. So commit the echo as delivery:'sending'
1500
+ // (unconfirmed) and arm a watchdog + persist it, so it is recoverable on
1501
+ // reload and flips to 'failed' if the server never echoes it back.
1235
1502
  const message: ChatMessage = {
1236
1503
  id: this.generateId(),
1237
1504
  role: 'user',
@@ -1239,15 +1506,189 @@ export class WhereverClient {
1239
1506
  timestamp: Date.now(),
1240
1507
  isStreaming: false,
1241
1508
  sessionId: s.sessionId,
1509
+ delivery: 'sending',
1242
1510
  };
1243
1511
  this.stateStore.update((st: WhereverState) => ({
1244
1512
  ...st,
1245
1513
  sessionError: null,
1246
1514
  messages: [...st.messages, message],
1247
1515
  }));
1516
+ this.armConfirm(message.id);
1517
+ this.persistPending(s.sessionId);
1518
+ return true;
1519
+ }
1520
+
1521
+ // ==========================================================================
1522
+ // Outbound-message delivery confirmation + recovery.
1523
+ //
1524
+ // An optimistic user echo is unconfirmed until the server echoes it back. This
1525
+ // machinery makes an unconfirmed message survive a reload and surface a retry
1526
+ // affordance instead of being silently lost when a half-open socket swallowed
1527
+ // the frame.
1528
+ // ==========================================================================
1529
+
1530
+ private pendingKey(sessionId: string): string {
1531
+ return WhereverClient.PENDING_PREFIX + sessionId;
1532
+ }
1533
+
1534
+ // Persist the current session's still-unconfirmed (delivery-tagged) user
1535
+ // messages so a reload can recover them. Cleared to empty when none remain.
1536
+ private persistPending(sessionId: string | null): void {
1537
+ if (!sessionId || typeof localStorage === 'undefined') return;
1538
+ const pending = get(this.stateStore).messages.filter(
1539
+ (m) => m.role === 'user' && m.delivery !== undefined,
1540
+ );
1541
+ try {
1542
+ if (pending.length === 0) {
1543
+ localStorage.removeItem(this.pendingKey(sessionId));
1544
+ } else {
1545
+ localStorage.setItem(
1546
+ this.pendingKey(sessionId),
1547
+ JSON.stringify(
1548
+ pending.map((m) => ({
1549
+ id: m.id,
1550
+ content: m.content,
1551
+ timestamp: m.timestamp,
1552
+ // Persist as 'failed': a reload cannot know if it ever landed, so
1553
+ // it must be presented as needs-attention, never as delivered.
1554
+ delivery: 'failed' as const,
1555
+ })),
1556
+ ),
1557
+ );
1558
+ }
1559
+ } catch {}
1560
+ }
1561
+
1562
+ // Load persisted unconfirmed messages for a session (used on load/resync to
1563
+ // re-surface anything a previous tab left in limbo).
1564
+ private loadPersistedPending(sessionId: string): ChatMessage[] {
1565
+ if (typeof localStorage === 'undefined') return [];
1566
+ try {
1567
+ const raw = localStorage.getItem(this.pendingKey(sessionId));
1568
+ if (!raw) return [];
1569
+ const arr = JSON.parse(raw);
1570
+ if (!Array.isArray(arr)) return [];
1571
+ return arr
1572
+ .filter((m) => m && typeof m.content === 'string')
1573
+ .map((m) => ({
1574
+ id: typeof m.id === 'string' ? m.id : this.generateId(),
1575
+ role: 'user' as const,
1576
+ content: m.content,
1577
+ timestamp: typeof m.timestamp === 'number' ? m.timestamp : Date.now(),
1578
+ isStreaming: false,
1579
+ sessionId,
1580
+ delivery: 'failed' as const,
1581
+ }));
1582
+ } catch {
1583
+ return [];
1584
+ }
1585
+ }
1586
+
1587
+ private armConfirm(messageId: string): void {
1588
+ this.clearConfirm(messageId);
1589
+ if (typeof setTimeout !== 'function') return;
1590
+ const timer = setTimeout(() => {
1591
+ this.confirmTimers.delete(messageId);
1592
+ // Still unconfirmed after the window: mark it failed so the UI offers a
1593
+ // retry. Delivery is genuinely uncertain (a half-open socket may have
1594
+ // eaten it), so we do NOT auto-resend: that risks a duplicate. The user
1595
+ // decides.
1596
+ let sessionId: string | null = null;
1597
+ this.stateStore.update((st: WhereverState) => {
1598
+ const m = st.messages.find((x) => x.id === messageId);
1599
+ if (!m || m.delivery !== 'sending') return st;
1600
+ sessionId = st.sessionId;
1601
+ return {
1602
+ ...st,
1603
+ messages: st.messages.map((x) =>
1604
+ x.id === messageId ? {...x, delivery: 'failed'} : x,
1605
+ ),
1606
+ };
1607
+ });
1608
+ if (sessionId) this.persistPending(sessionId);
1609
+ }, WhereverClient.CONFIRM_MS);
1610
+ if (timer && typeof (timer as any).unref === 'function') {
1611
+ (timer as any).unref();
1612
+ }
1613
+ this.confirmTimers.set(messageId, timer);
1614
+ }
1615
+
1616
+ private clearConfirm(messageId: string): void {
1617
+ const t = this.confirmTimers.get(messageId);
1618
+ if (t) {
1619
+ clearTimeout(t);
1620
+ this.confirmTimers.delete(messageId);
1621
+ }
1622
+ }
1623
+
1624
+ // Mark the oldest still-unconfirmed user message with this content as
1625
+ // delivered (the server echoed it back). Content-matched because the server
1626
+ // echo carries no client message id. Returns true if one was confirmed.
1627
+ private confirmDeliveredByContent(content: string): boolean {
1628
+ let confirmedId: string | null = null;
1629
+ let sessionId: string | null = null;
1630
+ this.stateStore.update((st: WhereverState) => {
1631
+ const target = st.messages.find(
1632
+ (m) => m.role === 'user' && m.delivery !== undefined && m.content === content,
1633
+ );
1634
+ if (!target) return st;
1635
+ confirmedId = target.id;
1636
+ sessionId = st.sessionId;
1637
+ return {
1638
+ ...st,
1639
+ messages: st.messages.map((m) =>
1640
+ m.id === target.id ? {...m, delivery: undefined} : m,
1641
+ ),
1642
+ };
1643
+ });
1644
+ if (confirmedId) {
1645
+ this.clearConfirm(confirmedId);
1646
+ this.persistPending(sessionId);
1647
+ return true;
1648
+ }
1649
+ return false;
1650
+ }
1651
+
1652
+ // Retry a failed (or sending) outbound message: re-send its frame and re-arm
1653
+ // confirmation. Returns false if it could not be handed to an OPEN socket (the
1654
+ // message stays failed/recoverable).
1655
+ public resendMessage(messageId: string): boolean {
1656
+ const s = get(this.stateStore);
1657
+ const m = s.messages.find((x) => x.id === messageId && x.role === 'user');
1658
+ if (!m || !s.sessionId) return false;
1659
+ if (!this.getIsConnected()) {
1660
+ if (!this.ws && !this.reconnectTimer) this.scheduleReconnect();
1661
+ return false;
1662
+ }
1663
+ const ok = this.send({type: 'message', message: m.content, sessionId: s.sessionId});
1664
+ if (!ok) return false;
1665
+ this.stateStore.update((st: WhereverState) => ({
1666
+ ...st,
1667
+ sessionError: null,
1668
+ messages: st.messages.map((x) =>
1669
+ x.id === messageId ? {...x, delivery: 'sending', timestamp: Date.now()} : x,
1670
+ ),
1671
+ }));
1672
+ this.armConfirm(messageId);
1673
+ this.persistPending(s.sessionId);
1248
1674
  return true;
1249
1675
  }
1250
1676
 
1677
+ // Drop a failed outbound message the user chooses not to resend. Removes it
1678
+ // from the transcript and from the persisted-pending store.
1679
+ public discardMessage(messageId: string): void {
1680
+ let sessionId: string | null = null;
1681
+ this.clearConfirm(messageId);
1682
+ this.stateStore.update((st: WhereverState) => {
1683
+ sessionId = st.sessionId;
1684
+ return {
1685
+ ...st,
1686
+ messages: st.messages.filter((m) => m.id !== messageId),
1687
+ };
1688
+ });
1689
+ if (sessionId) this.persistPending(sessionId);
1690
+ }
1691
+
1251
1692
  public abort() {
1252
1693
  const s = get(this.stateStore);
1253
1694
  if (!s.sessionId) return;
@@ -1297,6 +1738,7 @@ export class WhereverClient {
1297
1738
  readOnly: false,
1298
1739
  conflict: null,
1299
1740
  sessionError: null,
1741
+ notice: null,
1300
1742
  creatingSession: false,
1301
1743
  resyncing: false,
1302
1744
  agentPending: false,
@@ -1364,6 +1806,7 @@ export class WhereverClient {
1364
1806
  activeCwd: null,
1365
1807
  activeModel: null,
1366
1808
  readOnly: false,
1809
+ notice: null,
1367
1810
  creatingSession: false,
1368
1811
  loadingSession: false,
1369
1812
  resyncing: false,
@@ -1406,6 +1849,10 @@ export class WhereverClient {
1406
1849
  this.stateStore.update((s: WhereverState) => ({...s, sessionError: null}));
1407
1850
  }
1408
1851
 
1852
+ public dismissNotice() {
1853
+ this.stateStore.update((s: WhereverState) => ({...s, notice: null}));
1854
+ }
1855
+
1409
1856
  public changeModel(model: string) {
1410
1857
  this.send({type: 'model_change', model});
1411
1858
  }