@wherever-dev/client 0.2.2 → 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
@@ -17,6 +17,7 @@ const defaultState: WhereverState = {
17
17
  creatingSession: false,
18
18
  loadingSession: false,
19
19
  resyncing: false,
20
+ agentPending: false,
20
21
  error: null,
21
22
  session: null,
22
23
  sessionId: null,
@@ -53,6 +54,18 @@ export class WhereverClient {
53
54
  // clear the flags and surface a recoverable error instead of an endless spin.
54
55
  private loadWatchdog: any = null;
55
56
  private static readonly LOAD_WATCHDOG_MS = 12_000;
57
+ // Watchdog for an in-flight session_new. Symmetrical to loadWatchdog: creating
58
+ // a session sets creatingSession=true and shows a BLOCKING full-screen overlay,
59
+ // and the only things that clear it are session_created/session_error/
60
+ // session_conflict/session_interrupted (or a socket close). If none of those
61
+ // ever arrives (a slow git init / remote-repo creation, an error thrown before
62
+ // the reply is sent, or a half-open socket the liveness watchdog has not yet
63
+ // reaped), the overlay spins forever and the only recovery is a reload. This
64
+ // timer guarantees creatingSession always resolves. It is longer than the load
65
+ // watchdog because creating can legitimately take a while (git init + creating
66
+ // a remote GitHub repo over the network).
67
+ private createWatchdog: any = null;
68
+ private static readonly CREATE_WATCHDOG_MS = 25_000;
56
69
  private reconnectAttempts = 0;
57
70
  private reconnectDelay = 2000;
58
71
  private maxReconnectDelay = 15000;
@@ -84,6 +97,13 @@ export class WhereverClient {
84
97
  private resumeModel?: string;
85
98
  private listeners = new Set<(msg: any) => void>();
86
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:';
87
107
 
88
108
  constructor(config: WhereverClientConfig) {
89
109
  this.config = {
@@ -172,14 +192,39 @@ export class WhereverClient {
172
192
  // resynced in place. resyncing stays true until message_history (or an
173
193
  // error/conflict) arrives, keeping the "reconnecting" affordance up and
174
194
  // input blocked without dropping the cached messages.
175
- if (this.resumeSessionFile) {
176
- const file = this.resumeSessionFile;
177
- const cwd = this.resumeCwd;
178
- const model = this.resumeModel;
179
- this.resumeSessionFile = null;
180
- this.resumeCwd = undefined;
181
- this.resumeModel = undefined;
182
- this.send({type: 'session_load', sessionFile: file, cwd, model});
195
+ //
196
+ // Re-attachment is REQUIRED on every reconnect that still holds a session,
197
+ // not just the suspend/resume path. The server is stateless per socket:
198
+ // each new connection starts attached to NO session (the old socket's
199
+ // close removed this client from the pool). If we do not re-issue
200
+ // session_load here, the relay is connected but the session stream is
201
+ // dead, so the UI shows a frozen conversation (a stale tool call as the
202
+ // last message, Abort disabled) while the agent keeps running headless.
203
+ // Two sources for what to rejoin:
204
+ // 1. resumeSessionFile -> explicit suspend()/resume() (tab background).
205
+ // 2. the store's activeSessionFile -> an UNSOLICITED drop (network
206
+ // blip, tab switch, laptop sleep, half-open reap) where suspend()
207
+ // never ran. This is the case that used to silently freeze.
208
+ const cached = get(this.stateStore);
209
+ const rejoinFile = this.resumeSessionFile ?? cached.activeSessionFile;
210
+ const rejoinCwd =
211
+ this.resumeSessionFile != null
212
+ ? this.resumeCwd
213
+ : (cached.activeCwd ?? undefined);
214
+ const rejoinModel =
215
+ this.resumeSessionFile != null
216
+ ? this.resumeModel
217
+ : (cached.activeModel ?? undefined);
218
+ this.resumeSessionFile = null;
219
+ this.resumeCwd = undefined;
220
+ this.resumeModel = undefined;
221
+ if (rejoinFile) {
222
+ // Keep the cached conversation on screen but mark it resyncing so the
223
+ // "Reconnecting and syncing session..." banner shows and sending is
224
+ // blocked until fresh history lands. resyncing is cleared by
225
+ // message_history (or an error/conflict) via the reducer.
226
+ this.stateStore.update(s => (s.resyncing ? s : {...s, resyncing: true}));
227
+ this.send({type: 'session_load', sessionFile: rejoinFile, cwd: rejoinCwd, model: rejoinModel});
183
228
  this.armLoadWatchdog();
184
229
  } else {
185
230
  this.stateStore.update(s => (s.resyncing ? {...s, resyncing: false} : s));
@@ -212,6 +257,12 @@ export class WhereverClient {
212
257
  // Never leave a session-load spinner stuck if the socket drops mid-load.
213
258
  loadingSession: false,
214
259
  creatingSession: false,
260
+ // If we still hold an active session, the drop is an unsolicited one on a
261
+ // live conversation: mark it resyncing NOW (during the reconnect backoff)
262
+ // so the user immediately sees "Reconnecting..." instead of a frozen view
263
+ // with a stale tool call and a disabled Abort. onOpen re-attaches and the
264
+ // reducer clears resyncing when fresh history lands.
265
+ resyncing: s.activeSessionFile ? true : s.resyncing,
215
266
  }));
216
267
  this.scheduleReconnect();
217
268
  };
@@ -250,6 +301,11 @@ export class WhereverClient {
250
301
  this.agentEndTimeout = null;
251
302
  }
252
303
  this.stopLivenessWatchdog();
304
+ // The load/create affordances belong to the socket we are tearing down. If
305
+ // left armed they would later fire against a fresh (re)connected session's
306
+ // state, so cancel them here.
307
+ this.clearLoadWatchdog();
308
+ this.clearCreateWatchdog();
253
309
 
254
310
  if (this.ws) {
255
311
  try {
@@ -262,11 +318,33 @@ export class WhereverClient {
262
318
  }
263
319
 
264
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();
265
327
  this.stateStore.set({
266
328
  ...defaultState,
267
329
  hideThinking: !!this.config.hideThinking,
268
330
  hideTools: !!this.config.hideTools,
269
331
  });
332
+ } else {
333
+ // Preserve-cache teardown (suspend / resume's pre-connect close). The
334
+ // socket is gone, so the store MUST reflect disconnected: leaving a stale
335
+ // connected:true made resume() early-return (its `if (connected) return`
336
+ // guard), so the real reconnect fell through to a plain connect() that did
337
+ // NOT preserve the session, which is what flashed the search / new-session
338
+ // empty-state on tab return. Clearing connected here (without wiping the
339
+ // cached session/messages) lets resume() actually rejoin in place, and
340
+ // never leaves the blocking load/create overlays up on a dead socket.
341
+ this.stateStore.update(s => ({
342
+ ...s,
343
+ connected: false,
344
+ connecting: false,
345
+ loadingSession: false,
346
+ creatingSession: false,
347
+ }));
270
348
  }
271
349
  }
272
350
 
@@ -300,7 +378,11 @@ export class WhereverClient {
300
378
  public resume() {
301
379
  const s = get(this.stateStore);
302
380
  if (s.connected || s.connecting) return;
303
- if (this.resumeSessionFile) {
381
+ // Rejoin whatever session we still hold: an explicit suspend() record OR the
382
+ // cached active session from an unsolicited drop. In BOTH cases onOpen
383
+ // re-issues session_load, so mark resyncing here to show the affordance and
384
+ // block sending until fresh history lands.
385
+ if (this.resumeSessionFile || s.activeSessionFile) {
304
386
  this.stateStore.update(st => ({...st, resyncing: true}));
305
387
  // Arm here too: if the socket never opens, onOpen never runs and the
306
388
  // resync affordance would otherwise hang. onClose also clears it, but the
@@ -318,6 +400,14 @@ export class WhereverClient {
318
400
  return this.resumeSessionFile !== null;
319
401
  }
320
402
 
403
+ // True when the store still holds an active session to rejoin in place -- from
404
+ // an explicit suspend() OR an unsolicited drop that left activeSessionFile set.
405
+ // Callers use this to prefer the preserve-cache resume() path over a fresh,
406
+ // session-wiping connect() when returning to a still-live conversation.
407
+ public hasActiveSession(): boolean {
408
+ return this.resumeSessionFile !== null || get(this.stateStore).activeSessionFile !== null;
409
+ }
410
+
321
411
  // Start (or restart) the stale-socket watchdog + keepalive for the current
322
412
  // socket. A half-open connection emits no 'close'/'error', so without this the
323
413
  // existing reconnect logic would never fire and the agent would hang forever.
@@ -434,6 +524,37 @@ export class WhereverClient {
434
524
  }
435
525
  }
436
526
 
527
+ // Arm (or re-arm) the create watchdog. Called when session_new is issued so an
528
+ // unanswered create can never strand the blocking "Creating session..."
529
+ // overlay. On expiry we clear creatingSession and surface a recoverable error
530
+ // instead of an endless spin that only a reload escapes.
531
+ private armCreateWatchdog() {
532
+ this.clearCreateWatchdog();
533
+ this.createWatchdog = setTimeout(() => {
534
+ this.createWatchdog = null;
535
+ const s = get(this.stateStore);
536
+ if (!s.creatingSession) return;
537
+ console.warn('[wherever] session create timed out; clearing creating state');
538
+ this.stateStore.update(st => ({
539
+ ...st,
540
+ creatingSession: false,
541
+ sessionError:
542
+ st.sessionError ||
543
+ 'Creating the session timed out. It may still be starting on the server; check the sidebar or reload.',
544
+ }));
545
+ }, WhereverClient.CREATE_WATCHDOG_MS);
546
+ }
547
+
548
+ // Clear the create watchdog. Called at every point a create resolves
549
+ // (session_created, session_error, session_conflict, session_interrupted,
550
+ // disconnect, leave).
551
+ private clearCreateWatchdog() {
552
+ if (this.createWatchdog) {
553
+ clearTimeout(this.createWatchdog);
554
+ this.createWatchdog = null;
555
+ }
556
+ }
557
+
437
558
  private scheduleReconnect() {
438
559
  if (this.reconnectTimer) return;
439
560
 
@@ -441,14 +562,23 @@ export class WhereverClient {
441
562
  this.reconnectTimer = null;
442
563
  this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
443
564
  console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
444
-
565
+
566
+ // If we still hold an active session, PRESERVE the cached store across the
567
+ // reconnect. A default connect() resets to a blank store, which wiped
568
+ // activeSessionFile BEFORE onOpen could re-attach to it -- that is what
569
+ // silently detached the frontend from a still-running session (frozen
570
+ // conversation, no re-follow, not even a "connecting"/"loading" hint).
571
+ // Preserving the store keeps the conversation on screen and lets onOpen
572
+ // re-issue session_load from activeSessionFile.
573
+ const preserve = !!get(this.stateStore).activeSessionFile;
574
+
445
575
  this.stateStore.update(s => ({
446
576
  ...s,
447
577
  connecting: true,
448
578
  error: 'Reconnecting...',
449
579
  }));
450
-
451
- this.connect();
580
+
581
+ this.connect(undefined, preserve);
452
582
  }, this.reconnectDelay);
453
583
  }
454
584
 
@@ -474,6 +604,18 @@ export class WhereverClient {
474
604
  break;
475
605
  }
476
606
 
607
+ // Any message that resolves an in-flight session_new disarms the create
608
+ // watchdog. session_created is the success path; error/conflict/interrupt end
609
+ // it too.
610
+ switch (msg.type) {
611
+ case 'session_created':
612
+ case 'session_error':
613
+ case 'session_conflict':
614
+ case 'session_interrupted':
615
+ this.clearCreateWatchdog();
616
+ break;
617
+ }
618
+
477
619
  switch (msg.type) {
478
620
  case 'connected':
479
621
  this.stateStore.update((s: WhereverState) => ({
@@ -594,6 +736,19 @@ export class WhereverClient {
594
736
  : m,
595
737
  );
596
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
+ }
597
752
  const lastUserMessage = [...newMessages]
598
753
  .reverse()
599
754
  .find((m) => m.role === 'user');
@@ -626,11 +781,24 @@ export class WhereverClient {
626
781
  this.agentEndTimeout = null;
627
782
  }
628
783
  this.agentEndTimeout = setTimeout(() => {
784
+ const now = Date.now();
629
785
  this.stateStore.update((s: WhereverState) => ({
630
786
  ...s,
631
787
  isStreaming: false,
632
788
  messages: s.messages.map((m: ChatMessage) =>
633
- 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,
634
802
  ),
635
803
  }));
636
804
  this.agentEndTimeout = null;
@@ -654,17 +822,19 @@ export class WhereverClient {
654
822
  ? {...m, isStreaming: false}
655
823
  : m,
656
824
  );
825
+ const startedAt = Date.now();
657
826
  const newMsg: ChatMessage = {
658
827
  id: this.generateId(),
659
828
  role: 'tool',
660
829
  content: toolArgs
661
830
  ? `$ ${msg.toolName} ${toolArgs}`
662
831
  : `$ ${msg.toolName}`,
663
- timestamp: Date.now(),
832
+ timestamp: startedAt,
664
833
  isStreaming: true,
665
834
  toolName: msg.toolName,
666
835
  toolArgs: toolArgs,
667
836
  toolOutput: '',
837
+ startedAt,
668
838
  };
669
839
  return {
670
840
  ...s,
@@ -715,6 +885,7 @@ export class WhereverClient {
715
885
  m.toolName === msg.toolName &&
716
886
  !m.content.startsWith('Tool error:'),
717
887
  );
888
+ const endedAt = Date.now();
718
889
  if (toolMsg) {
719
890
  const errorPrefix = msg.isError ? 'Error: ' : '';
720
891
  return {
@@ -727,6 +898,7 @@ export class WhereverClient {
727
898
  isStreaming: false,
728
899
  isError: msg.isError,
729
900
  toolOutput: result,
901
+ endedAt,
730
902
  }
731
903
  : m,
732
904
  ),
@@ -739,12 +911,13 @@ export class WhereverClient {
739
911
  id: this.generateId(),
740
912
  role: 'tool',
741
913
  content,
742
- timestamp: Date.now(),
914
+ timestamp: endedAt,
743
915
  isStreaming: false,
744
916
  toolName: msg.toolName,
745
917
  toolArgs: '',
746
918
  toolOutput: result,
747
919
  isError: msg.isError,
920
+ endedAt,
748
921
  };
749
922
  return {
750
923
  ...s,
@@ -755,15 +928,26 @@ export class WhereverClient {
755
928
  break;
756
929
  }
757
930
 
758
- case 'aborted':
931
+ case 'aborted': {
932
+ const abortedAt = Date.now();
759
933
  this.stateStore.update((s: WhereverState) => ({
760
934
  ...s,
761
935
  isStreaming: false,
762
936
  messages: s.messages.map((m: ChatMessage) =>
763
- 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,
764
947
  ),
765
948
  }));
766
949
  break;
950
+ }
767
951
 
768
952
  case 'session_created':
769
953
  this.stateStore.update((s: WhereverState) => ({
@@ -778,12 +962,35 @@ export class WhereverClient {
778
962
  // The server forces read-only for sessions in a configured
779
963
  // sessions.readOnly folder (observe-only fleet view).
780
964
  readOnly: msg.readOnly ?? false,
965
+ // pending -> the history is painted now but the live agent is still
966
+ // building; keep the composer disabled (agentPending) until
967
+ // session_ready. A non-pending create (new session, warm reload) is
968
+ // immediately sendable.
969
+ agentPending: msg.pending === true,
781
970
  // Initial context-usage snapshot for the new session (null if unknown;
782
971
  // live updates arrive via 'context_usage').
783
972
  contextUsage: msg.contextUsage ?? null,
784
973
  }));
785
974
  break;
786
975
 
976
+ case 'session_ready':
977
+ // The live agent finished building for a previously-pending load. Enable
978
+ // the composer and refresh the now-authoritative model/streaming/usage.
979
+ this.stateStore.update((s: WhereverState) => {
980
+ // Ignore a stale ready for a session we already switched away from.
981
+ if (msg.sessionFile && s.activeSessionFile && msg.sessionFile !== s.activeSessionFile) {
982
+ return s;
983
+ }
984
+ return {
985
+ ...s,
986
+ agentPending: false,
987
+ activeModel: msg.model ?? s.activeModel,
988
+ isStreaming: msg.isStreaming ?? s.isStreaming,
989
+ contextUsage: msg.contextUsage ?? s.contextUsage,
990
+ };
991
+ });
992
+ break;
993
+
787
994
  case 'context_usage':
788
995
  this.stateStore.update((s: WhereverState) => ({
789
996
  ...s,
@@ -803,6 +1010,7 @@ export class WhereverClient {
803
1010
  activeCwd: null,
804
1011
  activeModel: null,
805
1012
  loadingSession: false,
1013
+ agentPending: false,
806
1014
  };
807
1015
  }
808
1016
  return s;
@@ -817,6 +1025,10 @@ export class WhereverClient {
817
1025
  creatingSession: false,
818
1026
  loadingSession: false,
819
1027
  resyncing: false,
1028
+ // A failed (cold) agent build clears pending: the session stays
1029
+ // readable, but sending remains blocked (no live agent) and the error
1030
+ // is surfaced. This is the degrade-to-read-only path.
1031
+ agentPending: false,
820
1032
  }));
821
1033
  break;
822
1034
 
@@ -831,6 +1043,7 @@ export class WhereverClient {
831
1043
  creatingSession: false,
832
1044
  loadingSession: false,
833
1045
  resyncing: false,
1046
+ agentPending: false,
834
1047
  }));
835
1048
  break;
836
1049
 
@@ -847,18 +1060,47 @@ export class WhereverClient {
847
1060
  activeModel: null,
848
1061
  creatingSession: false,
849
1062
  loadingSession: false,
1063
+ agentPending: false,
850
1064
  }));
851
1065
  break;
852
1066
 
853
- 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];
854
1081
  this.stateStore.update((s: WhereverState) => {
855
1082
  const mapped = this.mapHistory(msg.messages, msg.sessionId, s.isStreaming);
856
1083
  const totalCount =
857
1084
  typeof msg.totalCount === 'number' ? msg.totalCount : mapped.length;
858
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
+ }
859
1101
  return {
860
1102
  ...s,
861
- messages: mapped,
1103
+ messages: [...mapped, ...undelivered],
862
1104
  historyTotalCount: totalCount,
863
1105
  historyOffset: offset,
864
1106
  loadingMoreHistory: false,
@@ -866,7 +1108,12 @@ export class WhereverClient {
866
1108
  resyncing: false,
867
1109
  };
868
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);
869
1115
  break;
1116
+ }
870
1117
 
871
1118
  case 'message_history_prepend':
872
1119
  this.stateStore.update((s: WhereverState) => {
@@ -907,7 +1154,11 @@ export class WhereverClient {
907
1154
  applyStreamingTail: boolean,
908
1155
  ): ChatMessage[] {
909
1156
  const mapped: ChatMessage[] = [];
910
- 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}[]> = {};
911
1162
 
912
1163
  for (const m of rawMessages) {
913
1164
  if (m.role === 'tool_call') {
@@ -915,13 +1166,14 @@ export class WhereverClient {
915
1166
  if (!pendingCalls[tName]) {
916
1167
  pendingCalls[tName] = [];
917
1168
  }
918
- pendingCalls[tName].push(m.content || '');
1169
+ pendingCalls[tName].push({args: m.content || '', startedAt: m.timestamp});
919
1170
  } else if (m.role === 'tool_result') {
920
1171
  const tName = m.toolName || 'unknown';
921
- const tArgs =
1172
+ const call =
922
1173
  pendingCalls[tName] && pendingCalls[tName].length > 0
923
1174
  ? pendingCalls[tName].shift()!
924
- : '';
1175
+ : undefined;
1176
+ const tArgs = call?.args ?? '';
925
1177
  mapped.push({
926
1178
  id: this.generateId(),
927
1179
  role: 'tool',
@@ -935,6 +1187,15 @@ export class WhereverClient {
935
1187
  toolOutput: m.content,
936
1188
  isError: m.isError,
937
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
+ : {}),
938
1199
  });
939
1200
  } else {
940
1201
  mapped.push({
@@ -949,21 +1210,26 @@ export class WhereverClient {
949
1210
  }
950
1211
  }
951
1212
 
952
- for (const [tName, argsList] of Object.entries(pendingCalls)) {
953
- for (const args of argsList) {
1213
+ for (const [tName, calls] of Object.entries(pendingCalls)) {
1214
+ for (const call of calls) {
954
1215
  mapped.push({
955
1216
  id: this.generateId(),
956
1217
  role: 'tool',
957
- content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
1218
+ content: call.args ? `$ ${tName} ${call.args}` : `$ ${tName}`,
958
1219
  timestamp:
959
1220
  mapped.length > 0
960
1221
  ? mapped[mapped.length - 1].timestamp + 1
961
1222
  : Date.now(),
962
1223
  isStreaming: applyStreamingTail,
963
1224
  toolName: tName,
964
- toolArgs: args,
1225
+ toolArgs: call.args,
965
1226
  toolOutput: '',
966
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
+ : {}),
967
1233
  });
968
1234
  }
969
1235
  }
@@ -1027,6 +1293,20 @@ export class WhereverClient {
1027
1293
  const s = get(this.stateStore);
1028
1294
  if (!s.sessionId) return false;
1029
1295
 
1296
+ // The session's transcript is loaded but its live agent is still building
1297
+ // (cold, fast-first load). Reading is fine; sending is not possible yet, and
1298
+ // a message sent now would have no agent to receive it. Surface a clear,
1299
+ // recoverable hint and keep the text (the composer is disabled anyway, but a
1300
+ // programmatic caller could still reach here).
1301
+ if (s.agentPending) {
1302
+ this.stateStore.update((st: WhereverState) => ({
1303
+ ...st,
1304
+ sessionError:
1305
+ st.sessionError ?? 'Preparing the session agent; please wait a moment, then resend.',
1306
+ }));
1307
+ return false;
1308
+ }
1309
+
1030
1310
  // Guard against sending on a dead / half-open socket. getIsConnected()
1031
1311
  // checks the real readyState (not the store's connected flag, which can lag
1032
1312
  // a half-open socket the liveness watchdog has not reaped yet). Sending here
@@ -1059,6 +1339,11 @@ export class WhereverClient {
1059
1339
  return false;
1060
1340
  }
1061
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.
1062
1347
  const message: ChatMessage = {
1063
1348
  id: this.generateId(),
1064
1349
  role: 'user',
@@ -1066,15 +1351,189 @@ export class WhereverClient {
1066
1351
  timestamp: Date.now(),
1067
1352
  isStreaming: false,
1068
1353
  sessionId: s.sessionId,
1354
+ delivery: 'sending',
1069
1355
  };
1070
1356
  this.stateStore.update((st: WhereverState) => ({
1071
1357
  ...st,
1072
1358
  sessionError: null,
1073
1359
  messages: [...st.messages, message],
1074
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);
1075
1519
  return true;
1076
1520
  }
1077
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
+
1078
1537
  public abort() {
1079
1538
  const s = get(this.stateStore);
1080
1539
  if (!s.sessionId) return;
@@ -1087,6 +1546,7 @@ export class WhereverClient {
1087
1546
  conflict: null,
1088
1547
  sessionError: null,
1089
1548
  loadingSession: true,
1549
+ agentPending: false,
1090
1550
  }));
1091
1551
  this.send({type: 'session_load', sessionFile, cwd, model});
1092
1552
  this.armLoadWatchdog();
@@ -1125,12 +1585,16 @@ export class WhereverClient {
1125
1585
  sessionError: null,
1126
1586
  creatingSession: false,
1127
1587
  resyncing: false,
1588
+ agentPending: false,
1128
1589
  contextUsage: null,
1129
1590
  loadingSession: true,
1130
1591
  }));
1131
1592
  this.resumeSessionFile = null;
1132
1593
  this.resumeCwd = undefined;
1133
1594
  this.resumeModel = undefined;
1595
+ // Switching supersedes any in-flight create; disarm its watchdog so it can't
1596
+ // later fire against the newly loaded session.
1597
+ this.clearCreateWatchdog();
1134
1598
  this.send({type: 'session_load', sessionFile, cwd, model});
1135
1599
  this.armLoadWatchdog();
1136
1600
  }
@@ -1157,11 +1621,25 @@ export class WhereverClient {
1157
1621
  createRemote,
1158
1622
  repoVisibility,
1159
1623
  });
1624
+ // Never let the blocking "Creating session..." overlay hang if the reply is
1625
+ // lost. Symmetrical with armLoadWatchdog for session_load.
1626
+ this.armCreateWatchdog();
1160
1627
  }
1161
1628
 
1162
1629
  public leaveSession() {
1163
1630
  const s = get(this.stateStore);
1164
- if (!s.sessionId) return;
1631
+ // Leaving abandons any in-flight create too, so disarm its watchdog even when
1632
+ // there is no sessionId yet (a create that has not resolved).
1633
+ this.clearCreateWatchdog();
1634
+ if (!s.sessionId) {
1635
+ if (s.creatingSession) {
1636
+ this.stateStore.update((st: WhereverState) => ({
1637
+ ...st,
1638
+ creatingSession: false,
1639
+ }));
1640
+ }
1641
+ return;
1642
+ }
1165
1643
  this.send({type: 'session_leave', sessionId: s.sessionId});
1166
1644
  this.stateStore.update((s: WhereverState) => ({
1167
1645
  ...s,
@@ -1175,6 +1653,7 @@ export class WhereverClient {
1175
1653
  creatingSession: false,
1176
1654
  loadingSession: false,
1177
1655
  resyncing: false,
1656
+ agentPending: false,
1178
1657
  contextUsage: null,
1179
1658
  }));
1180
1659
  this.clearLoadWatchdog();