@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/src/client.ts CHANGED
@@ -97,6 +97,13 @@ export class WhereverClient {
97
97
  private resumeModel?: string;
98
98
  private listeners = new Set<(msg: any) => void>();
99
99
  private pendingUploads = new Map<string, {resolve: (val: any) => void, reject: (err: any) => void}>();
100
+ // Per-message confirmation watchdogs. A user message committed optimistically
101
+ // is only proven delivered when the server echoes it back; if no echo lands
102
+ // within CONFIRM_MS the watchdog flips it to delivery:'failed' so the UI can
103
+ // offer a retry instead of pretending it was sent (the half-open-socket loss).
104
+ private confirmTimers = new Map<string, ReturnType<typeof setTimeout>>();
105
+ private static readonly CONFIRM_MS = 12_000;
106
+ private static readonly PENDING_PREFIX = 'wherever-pending:';
100
107
 
101
108
  constructor(config: WhereverClientConfig) {
102
109
  this.config = {
@@ -311,6 +318,12 @@ export class WhereverClient {
311
318
  }
312
319
 
313
320
  if (resetState) {
321
+ // Full teardown wipes the store, so no unconfirmed message survives in it;
322
+ // clear their watchdogs to avoid firing against a fresh store. The
323
+ // persisted-pending localStorage entries intentionally REMAIN so a later
324
+ // load can still recover them.
325
+ for (const t of this.confirmTimers.values()) clearTimeout(t);
326
+ this.confirmTimers.clear();
314
327
  this.stateStore.set({
315
328
  ...defaultState,
316
329
  hideThinking: !!this.config.hideThinking,
@@ -723,6 +736,19 @@ export class WhereverClient {
723
736
  : m,
724
737
  );
725
738
  } else if (msg.content) {
739
+ // The server echoes the user's own message back once pi has appended
740
+ // it: that is the delivery CONFIRMATION for an optimistic (unconfirmed)
741
+ // echo. Confirm the matching pending message (flip delivery off, clear
742
+ // its watchdog, update the persisted-pending store) instead of adding
743
+ // a duplicate. If there was no pending match (e.g. another client sent
744
+ // it), fall back to the existing content-dedupe.
745
+ if (msg.role === 'user') {
746
+ const confirmedPending = this.confirmDeliveredByContent(msg.content);
747
+ if (confirmedPending) {
748
+ // Re-read: confirmDeliveredByContent already updated the store.
749
+ return get(this.stateStore);
750
+ }
751
+ }
726
752
  const lastUserMessage = [...newMessages]
727
753
  .reverse()
728
754
  .find((m) => m.role === 'user');
@@ -755,11 +781,24 @@ export class WhereverClient {
755
781
  this.agentEndTimeout = null;
756
782
  }
757
783
  this.agentEndTimeout = setTimeout(() => {
784
+ const now = Date.now();
758
785
  this.stateStore.update((s: WhereverState) => ({
759
786
  ...s,
760
787
  isStreaming: false,
761
788
  messages: s.messages.map((m: ChatMessage) =>
762
- m.isStreaming ? {...m, isStreaming: false} : m,
789
+ m.isStreaming
790
+ ? {
791
+ ...m,
792
+ isStreaming: false,
793
+ // Freeze a still-running tool's duration if it never got a
794
+ // tool_end (turn ended between steps), so "Elapsed" stops
795
+ // ticking and shows the final "Took".
796
+ endedAt:
797
+ m.role === 'tool' && m.endedAt === undefined
798
+ ? now
799
+ : m.endedAt,
800
+ }
801
+ : m,
763
802
  ),
764
803
  }));
765
804
  this.agentEndTimeout = null;
@@ -783,17 +822,19 @@ export class WhereverClient {
783
822
  ? {...m, isStreaming: false}
784
823
  : m,
785
824
  );
825
+ const startedAt = Date.now();
786
826
  const newMsg: ChatMessage = {
787
827
  id: this.generateId(),
788
828
  role: 'tool',
789
829
  content: toolArgs
790
830
  ? `$ ${msg.toolName} ${toolArgs}`
791
831
  : `$ ${msg.toolName}`,
792
- timestamp: Date.now(),
832
+ timestamp: startedAt,
793
833
  isStreaming: true,
794
834
  toolName: msg.toolName,
795
835
  toolArgs: toolArgs,
796
836
  toolOutput: '',
837
+ startedAt,
797
838
  };
798
839
  return {
799
840
  ...s,
@@ -844,6 +885,7 @@ export class WhereverClient {
844
885
  m.toolName === msg.toolName &&
845
886
  !m.content.startsWith('Tool error:'),
846
887
  );
888
+ const endedAt = Date.now();
847
889
  if (toolMsg) {
848
890
  const errorPrefix = msg.isError ? 'Error: ' : '';
849
891
  return {
@@ -856,6 +898,7 @@ export class WhereverClient {
856
898
  isStreaming: false,
857
899
  isError: msg.isError,
858
900
  toolOutput: result,
901
+ endedAt,
859
902
  }
860
903
  : m,
861
904
  ),
@@ -868,12 +911,13 @@ export class WhereverClient {
868
911
  id: this.generateId(),
869
912
  role: 'tool',
870
913
  content,
871
- timestamp: Date.now(),
914
+ timestamp: endedAt,
872
915
  isStreaming: false,
873
916
  toolName: msg.toolName,
874
917
  toolArgs: '',
875
918
  toolOutput: result,
876
919
  isError: msg.isError,
920
+ endedAt,
877
921
  };
878
922
  return {
879
923
  ...s,
@@ -884,15 +928,26 @@ export class WhereverClient {
884
928
  break;
885
929
  }
886
930
 
887
- case 'aborted':
931
+ case 'aborted': {
932
+ const abortedAt = Date.now();
888
933
  this.stateStore.update((s: WhereverState) => ({
889
934
  ...s,
890
935
  isStreaming: false,
891
936
  messages: s.messages.map((m: ChatMessage) =>
892
- m.isStreaming ? {...m, isStreaming: false} : m,
937
+ m.isStreaming
938
+ ? {
939
+ ...m,
940
+ isStreaming: false,
941
+ endedAt:
942
+ m.role === 'tool' && m.endedAt === undefined
943
+ ? abortedAt
944
+ : m.endedAt,
945
+ }
946
+ : m,
893
947
  ),
894
948
  }));
895
949
  break;
950
+ }
896
951
 
897
952
  case 'session_created':
898
953
  this.stateStore.update((s: WhereverState) => ({
@@ -1009,15 +1064,43 @@ export class WhereverClient {
1009
1064
  }));
1010
1065
  break;
1011
1066
 
1012
- case 'message_history':
1067
+ case 'message_history': {
1068
+ // The server transcript is authoritative for what was actually persisted.
1069
+ // Reconcile it against any unconfirmed outbound messages: keep the ones
1070
+ // that ARE in history (delivered), and re-surface the ones that are NOT
1071
+ // as recoverable 'failed' items so a message a half-open socket swallowed
1072
+ // is never silently lost across a reload/resync.
1073
+ const sessionIdForPending = msg.sessionId as string;
1074
+ // Carry-over from the CURRENT store (this-tab sends still in flight) plus
1075
+ // anything a PREVIOUS tab persisted before a reload.
1076
+ const inFlight = get(this.stateStore).messages.filter(
1077
+ (m) => m.role === 'user' && m.delivery !== undefined,
1078
+ );
1079
+ const persisted = this.loadPersistedPending(sessionIdForPending);
1080
+ const candidates = [...persisted, ...inFlight];
1013
1081
  this.stateStore.update((s: WhereverState) => {
1014
1082
  const mapped = this.mapHistory(msg.messages, msg.sessionId, s.isStreaming);
1015
1083
  const totalCount =
1016
1084
  typeof msg.totalCount === 'number' ? msg.totalCount : mapped.length;
1017
1085
  const offset = typeof msg.offset === 'number' ? msg.offset : 0;
1086
+ const historyContents = new Set(
1087
+ mapped.filter((m) => m.role === 'user').map((m) => m.content),
1088
+ );
1089
+ // Unconfirmed candidates whose content is NOT in the loaded history are
1090
+ // undelivered. De-dupe by content so two identical undelivered sends do
1091
+ // not multiply. Everything else the server persisted is already in
1092
+ // `mapped` (confirmed).
1093
+ const seen = new Set<string>();
1094
+ const undelivered: ChatMessage[] = [];
1095
+ for (const c of candidates) {
1096
+ if (historyContents.has(c.content)) continue;
1097
+ if (seen.has(c.content)) continue;
1098
+ seen.add(c.content);
1099
+ undelivered.push({...c, sessionId: sessionIdForPending, delivery: 'failed'});
1100
+ }
1018
1101
  return {
1019
1102
  ...s,
1020
- messages: mapped,
1103
+ messages: [...mapped, ...undelivered],
1021
1104
  historyTotalCount: totalCount,
1022
1105
  historyOffset: offset,
1023
1106
  loadingMoreHistory: false,
@@ -1025,7 +1108,12 @@ export class WhereverClient {
1025
1108
  resyncing: false,
1026
1109
  };
1027
1110
  });
1111
+ // Clear watchdogs for anything now confirmed, and rewrite the persisted
1112
+ // store to exactly the still-undelivered set.
1113
+ for (const c of candidates) this.clearConfirm(c.id);
1114
+ this.persistPending(sessionIdForPending);
1028
1115
  break;
1116
+ }
1029
1117
 
1030
1118
  case 'message_history_prepend':
1031
1119
  this.stateStore.update((s: WhereverState) => {
@@ -1066,7 +1154,11 @@ export class WhereverClient {
1066
1154
  applyStreamingTail: boolean,
1067
1155
  ): ChatMessage[] {
1068
1156
  const mapped: ChatMessage[] = [];
1069
- const pendingCalls: Record<string, string[]> = {};
1157
+ // Each pending tool_call carries its args AND its start timestamp (the ts of
1158
+ // the toolCall entry). When the matching tool_result arrives, startedAt =
1159
+ // the call ts and endedAt = the result ts, so a tool reconstructed from
1160
+ // loaded history shows the same "Took N.Ns" as a live-streamed one.
1161
+ const pendingCalls: Record<string, {args: string; startedAt: number}[]> = {};
1070
1162
 
1071
1163
  for (const m of rawMessages) {
1072
1164
  if (m.role === 'tool_call') {
@@ -1074,13 +1166,14 @@ export class WhereverClient {
1074
1166
  if (!pendingCalls[tName]) {
1075
1167
  pendingCalls[tName] = [];
1076
1168
  }
1077
- pendingCalls[tName].push(m.content || '');
1169
+ pendingCalls[tName].push({args: m.content || '', startedAt: m.timestamp});
1078
1170
  } else if (m.role === 'tool_result') {
1079
1171
  const tName = m.toolName || 'unknown';
1080
- const tArgs =
1172
+ const call =
1081
1173
  pendingCalls[tName] && pendingCalls[tName].length > 0
1082
1174
  ? pendingCalls[tName].shift()!
1083
- : '';
1175
+ : undefined;
1176
+ const tArgs = call?.args ?? '';
1084
1177
  mapped.push({
1085
1178
  id: this.generateId(),
1086
1179
  role: 'tool',
@@ -1094,6 +1187,15 @@ export class WhereverClient {
1094
1187
  toolOutput: m.content,
1095
1188
  isError: m.isError,
1096
1189
  sessionId,
1190
+ // Duration from the matched call. Only when both timestamps are
1191
+ // finite and coherent (end >= start); otherwise leave unset so the UI
1192
+ // simply shows no duration rather than a bogus one.
1193
+ ...(call &&
1194
+ Number.isFinite(call.startedAt) &&
1195
+ Number.isFinite(m.timestamp) &&
1196
+ m.timestamp >= call.startedAt
1197
+ ? {startedAt: call.startedAt, endedAt: m.timestamp}
1198
+ : {}),
1097
1199
  });
1098
1200
  } else {
1099
1201
  mapped.push({
@@ -1108,21 +1210,26 @@ export class WhereverClient {
1108
1210
  }
1109
1211
  }
1110
1212
 
1111
- for (const [tName, argsList] of Object.entries(pendingCalls)) {
1112
- for (const args of argsList) {
1213
+ for (const [tName, calls] of Object.entries(pendingCalls)) {
1214
+ for (const call of calls) {
1113
1215
  mapped.push({
1114
1216
  id: this.generateId(),
1115
1217
  role: 'tool',
1116
- content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
1218
+ content: call.args ? `$ ${tName} ${call.args}` : `$ ${tName}`,
1117
1219
  timestamp:
1118
1220
  mapped.length > 0
1119
1221
  ? mapped[mapped.length - 1].timestamp + 1
1120
1222
  : Date.now(),
1121
1223
  isStreaming: applyStreamingTail,
1122
1224
  toolName: tName,
1123
- toolArgs: args,
1225
+ toolArgs: call.args,
1124
1226
  toolOutput: '',
1125
1227
  sessionId,
1228
+ // An unmatched call (no result yet). Keep its start so a still-running
1229
+ // tool in the streaming tail can tick "Elapsed"; leave endedAt unset.
1230
+ ...(Number.isFinite(call.startedAt)
1231
+ ? {startedAt: call.startedAt}
1232
+ : {}),
1126
1233
  });
1127
1234
  }
1128
1235
  }
@@ -1232,6 +1339,11 @@ export class WhereverClient {
1232
1339
  return false;
1233
1340
  }
1234
1341
 
1342
+ // The frame was handed to an OPEN socket, but that is NOT proof of delivery:
1343
+ // a half-open TCP connection accepts send() (buffers locally, no throw) yet
1344
+ // the bytes never reach the server. So commit the echo as delivery:'sending'
1345
+ // (unconfirmed) and arm a watchdog + persist it, so it is recoverable on
1346
+ // reload and flips to 'failed' if the server never echoes it back.
1235
1347
  const message: ChatMessage = {
1236
1348
  id: this.generateId(),
1237
1349
  role: 'user',
@@ -1239,15 +1351,189 @@ export class WhereverClient {
1239
1351
  timestamp: Date.now(),
1240
1352
  isStreaming: false,
1241
1353
  sessionId: s.sessionId,
1354
+ delivery: 'sending',
1242
1355
  };
1243
1356
  this.stateStore.update((st: WhereverState) => ({
1244
1357
  ...st,
1245
1358
  sessionError: null,
1246
1359
  messages: [...st.messages, message],
1247
1360
  }));
1361
+ this.armConfirm(message.id);
1362
+ this.persistPending(s.sessionId);
1363
+ return true;
1364
+ }
1365
+
1366
+ // ==========================================================================
1367
+ // Outbound-message delivery confirmation + recovery.
1368
+ //
1369
+ // An optimistic user echo is unconfirmed until the server echoes it back. This
1370
+ // machinery makes an unconfirmed message survive a reload and surface a retry
1371
+ // affordance instead of being silently lost when a half-open socket swallowed
1372
+ // the frame.
1373
+ // ==========================================================================
1374
+
1375
+ private pendingKey(sessionId: string): string {
1376
+ return WhereverClient.PENDING_PREFIX + sessionId;
1377
+ }
1378
+
1379
+ // Persist the current session's still-unconfirmed (delivery-tagged) user
1380
+ // messages so a reload can recover them. Cleared to empty when none remain.
1381
+ private persistPending(sessionId: string | null): void {
1382
+ if (!sessionId || typeof localStorage === 'undefined') return;
1383
+ const pending = get(this.stateStore).messages.filter(
1384
+ (m) => m.role === 'user' && m.delivery !== undefined,
1385
+ );
1386
+ try {
1387
+ if (pending.length === 0) {
1388
+ localStorage.removeItem(this.pendingKey(sessionId));
1389
+ } else {
1390
+ localStorage.setItem(
1391
+ this.pendingKey(sessionId),
1392
+ JSON.stringify(
1393
+ pending.map((m) => ({
1394
+ id: m.id,
1395
+ content: m.content,
1396
+ timestamp: m.timestamp,
1397
+ // Persist as 'failed': a reload cannot know if it ever landed, so
1398
+ // it must be presented as needs-attention, never as delivered.
1399
+ delivery: 'failed' as const,
1400
+ })),
1401
+ ),
1402
+ );
1403
+ }
1404
+ } catch {}
1405
+ }
1406
+
1407
+ // Load persisted unconfirmed messages for a session (used on load/resync to
1408
+ // re-surface anything a previous tab left in limbo).
1409
+ private loadPersistedPending(sessionId: string): ChatMessage[] {
1410
+ if (typeof localStorage === 'undefined') return [];
1411
+ try {
1412
+ const raw = localStorage.getItem(this.pendingKey(sessionId));
1413
+ if (!raw) return [];
1414
+ const arr = JSON.parse(raw);
1415
+ if (!Array.isArray(arr)) return [];
1416
+ return arr
1417
+ .filter((m) => m && typeof m.content === 'string')
1418
+ .map((m) => ({
1419
+ id: typeof m.id === 'string' ? m.id : this.generateId(),
1420
+ role: 'user' as const,
1421
+ content: m.content,
1422
+ timestamp: typeof m.timestamp === 'number' ? m.timestamp : Date.now(),
1423
+ isStreaming: false,
1424
+ sessionId,
1425
+ delivery: 'failed' as const,
1426
+ }));
1427
+ } catch {
1428
+ return [];
1429
+ }
1430
+ }
1431
+
1432
+ private armConfirm(messageId: string): void {
1433
+ this.clearConfirm(messageId);
1434
+ if (typeof setTimeout !== 'function') return;
1435
+ const timer = setTimeout(() => {
1436
+ this.confirmTimers.delete(messageId);
1437
+ // Still unconfirmed after the window: mark it failed so the UI offers a
1438
+ // retry. Delivery is genuinely uncertain (a half-open socket may have
1439
+ // eaten it), so we do NOT auto-resend: that risks a duplicate. The user
1440
+ // decides.
1441
+ let sessionId: string | null = null;
1442
+ this.stateStore.update((st: WhereverState) => {
1443
+ const m = st.messages.find((x) => x.id === messageId);
1444
+ if (!m || m.delivery !== 'sending') return st;
1445
+ sessionId = st.sessionId;
1446
+ return {
1447
+ ...st,
1448
+ messages: st.messages.map((x) =>
1449
+ x.id === messageId ? {...x, delivery: 'failed'} : x,
1450
+ ),
1451
+ };
1452
+ });
1453
+ if (sessionId) this.persistPending(sessionId);
1454
+ }, WhereverClient.CONFIRM_MS);
1455
+ if (timer && typeof (timer as any).unref === 'function') {
1456
+ (timer as any).unref();
1457
+ }
1458
+ this.confirmTimers.set(messageId, timer);
1459
+ }
1460
+
1461
+ private clearConfirm(messageId: string): void {
1462
+ const t = this.confirmTimers.get(messageId);
1463
+ if (t) {
1464
+ clearTimeout(t);
1465
+ this.confirmTimers.delete(messageId);
1466
+ }
1467
+ }
1468
+
1469
+ // Mark the oldest still-unconfirmed user message with this content as
1470
+ // delivered (the server echoed it back). Content-matched because the server
1471
+ // echo carries no client message id. Returns true if one was confirmed.
1472
+ private confirmDeliveredByContent(content: string): boolean {
1473
+ let confirmedId: string | null = null;
1474
+ let sessionId: string | null = null;
1475
+ this.stateStore.update((st: WhereverState) => {
1476
+ const target = st.messages.find(
1477
+ (m) => m.role === 'user' && m.delivery !== undefined && m.content === content,
1478
+ );
1479
+ if (!target) return st;
1480
+ confirmedId = target.id;
1481
+ sessionId = st.sessionId;
1482
+ return {
1483
+ ...st,
1484
+ messages: st.messages.map((m) =>
1485
+ m.id === target.id ? {...m, delivery: undefined} : m,
1486
+ ),
1487
+ };
1488
+ });
1489
+ if (confirmedId) {
1490
+ this.clearConfirm(confirmedId);
1491
+ this.persistPending(sessionId);
1492
+ return true;
1493
+ }
1494
+ return false;
1495
+ }
1496
+
1497
+ // Retry a failed (or sending) outbound message: re-send its frame and re-arm
1498
+ // confirmation. Returns false if it could not be handed to an OPEN socket (the
1499
+ // message stays failed/recoverable).
1500
+ public resendMessage(messageId: string): boolean {
1501
+ const s = get(this.stateStore);
1502
+ const m = s.messages.find((x) => x.id === messageId && x.role === 'user');
1503
+ if (!m || !s.sessionId) return false;
1504
+ if (!this.getIsConnected()) {
1505
+ if (!this.ws && !this.reconnectTimer) this.scheduleReconnect();
1506
+ return false;
1507
+ }
1508
+ const ok = this.send({type: 'message', message: m.content, sessionId: s.sessionId});
1509
+ if (!ok) return false;
1510
+ this.stateStore.update((st: WhereverState) => ({
1511
+ ...st,
1512
+ sessionError: null,
1513
+ messages: st.messages.map((x) =>
1514
+ x.id === messageId ? {...x, delivery: 'sending', timestamp: Date.now()} : x,
1515
+ ),
1516
+ }));
1517
+ this.armConfirm(messageId);
1518
+ this.persistPending(s.sessionId);
1248
1519
  return true;
1249
1520
  }
1250
1521
 
1522
+ // Drop a failed outbound message the user chooses not to resend. Removes it
1523
+ // from the transcript and from the persisted-pending store.
1524
+ public discardMessage(messageId: string): void {
1525
+ let sessionId: string | null = null;
1526
+ this.clearConfirm(messageId);
1527
+ this.stateStore.update((st: WhereverState) => {
1528
+ sessionId = st.sessionId;
1529
+ return {
1530
+ ...st,
1531
+ messages: st.messages.filter((m) => m.id !== messageId),
1532
+ };
1533
+ });
1534
+ if (sessionId) this.persistPending(sessionId);
1535
+ }
1536
+
1251
1537
  public abort() {
1252
1538
  const s = get(this.stateStore);
1253
1539
  if (!s.sessionId) return;
package/src/types.ts CHANGED
@@ -9,6 +9,26 @@ export interface ChatMessage {
9
9
  toolArgs?: string;
10
10
  toolOutput?: string;
11
11
  isError?: boolean;
12
+ // Wall-clock start of a tool call (ms epoch), set when the tool_start frame
13
+ // arrives. `timestamp` also carries this, but startedAt is kept explicit so
14
+ // the elapsed/took duration is unambiguous and survives content rewrites.
15
+ startedAt?: number;
16
+ // Wall-clock end of a tool call (ms epoch), set when tool_end arrives. While a
17
+ // tool is running this is undefined and the UI ticks a live "Elapsed N.Ns";
18
+ // once set the UI freezes it as "Took N.Ns" (mirrors the pi CLI).
19
+ endedAt?: number;
20
+ // Delivery state for an OUTBOUND user message. A frame handed to a socket that
21
+ // reports OPEN can still never reach the server (a half-open TCP connection:
22
+ // send() buffers locally, no throw, but the bytes never land). So an optimistic
23
+ // echo is NOT proof of delivery. `delivery` tracks that:
24
+ // 'sending' -> handed to the socket, awaiting the server's echo.
25
+ // 'failed' -> no echo within the confirmation window; delivery is
26
+ // uncertain, so the UI surfaces a retry affordance rather than
27
+ // a normal-looking sent message.
28
+ // Undefined = confirmed/delivered (or a message that never needed tracking,
29
+ // e.g. one loaded from server history). Confirmed on the server's user echo
30
+ // (message_end role:user) or when it reappears in loaded history.
31
+ delivery?: 'sending' | 'failed';
12
32
  }
13
33
 
14
34
  export interface ConflictInfo {