@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/dist/client.js CHANGED
@@ -5,6 +5,7 @@ const defaultState = {
5
5
  creatingSession: false,
6
6
  loadingSession: false,
7
7
  resyncing: false,
8
+ agentPending: false,
8
9
  error: null,
9
10
  session: null,
10
11
  sessionId: null,
@@ -40,6 +41,18 @@ export class WhereverClient {
40
41
  // clear the flags and surface a recoverable error instead of an endless spin.
41
42
  loadWatchdog = null;
42
43
  static LOAD_WATCHDOG_MS = 12_000;
44
+ // Watchdog for an in-flight session_new. Symmetrical to loadWatchdog: creating
45
+ // a session sets creatingSession=true and shows a BLOCKING full-screen overlay,
46
+ // and the only things that clear it are session_created/session_error/
47
+ // session_conflict/session_interrupted (or a socket close). If none of those
48
+ // ever arrives (a slow git init / remote-repo creation, an error thrown before
49
+ // the reply is sent, or a half-open socket the liveness watchdog has not yet
50
+ // reaped), the overlay spins forever and the only recovery is a reload. This
51
+ // timer guarantees creatingSession always resolves. It is longer than the load
52
+ // watchdog because creating can legitimately take a while (git init + creating
53
+ // a remote GitHub repo over the network).
54
+ createWatchdog = null;
55
+ static CREATE_WATCHDOG_MS = 25_000;
43
56
  reconnectAttempts = 0;
44
57
  reconnectDelay = 2000;
45
58
  maxReconnectDelay = 15000;
@@ -71,6 +84,13 @@ export class WhereverClient {
71
84
  resumeModel;
72
85
  listeners = new Set();
73
86
  pendingUploads = new Map();
87
+ // Per-message confirmation watchdogs. A user message committed optimistically
88
+ // is only proven delivered when the server echoes it back; if no echo lands
89
+ // within CONFIRM_MS the watchdog flips it to delivery:'failed' so the UI can
90
+ // offer a retry instead of pretending it was sent (the half-open-socket loss).
91
+ confirmTimers = new Map();
92
+ static CONFIRM_MS = 12_000;
93
+ static PENDING_PREFIX = 'wherever-pending:';
74
94
  constructor(config) {
75
95
  this.config = {
76
96
  secure: true,
@@ -151,14 +171,37 @@ export class WhereverClient {
151
171
  // resynced in place. resyncing stays true until message_history (or an
152
172
  // error/conflict) arrives, keeping the "reconnecting" affordance up and
153
173
  // input blocked without dropping the cached messages.
154
- if (this.resumeSessionFile) {
155
- const file = this.resumeSessionFile;
156
- const cwd = this.resumeCwd;
157
- const model = this.resumeModel;
158
- this.resumeSessionFile = null;
159
- this.resumeCwd = undefined;
160
- this.resumeModel = undefined;
161
- this.send({ type: 'session_load', sessionFile: file, cwd, model });
174
+ //
175
+ // Re-attachment is REQUIRED on every reconnect that still holds a session,
176
+ // not just the suspend/resume path. The server is stateless per socket:
177
+ // each new connection starts attached to NO session (the old socket's
178
+ // close removed this client from the pool). If we do not re-issue
179
+ // session_load here, the relay is connected but the session stream is
180
+ // dead, so the UI shows a frozen conversation (a stale tool call as the
181
+ // last message, Abort disabled) while the agent keeps running headless.
182
+ // Two sources for what to rejoin:
183
+ // 1. resumeSessionFile -> explicit suspend()/resume() (tab background).
184
+ // 2. the store's activeSessionFile -> an UNSOLICITED drop (network
185
+ // blip, tab switch, laptop sleep, half-open reap) where suspend()
186
+ // never ran. This is the case that used to silently freeze.
187
+ const cached = get(this.stateStore);
188
+ const rejoinFile = this.resumeSessionFile ?? cached.activeSessionFile;
189
+ const rejoinCwd = this.resumeSessionFile != null
190
+ ? this.resumeCwd
191
+ : (cached.activeCwd ?? undefined);
192
+ const rejoinModel = this.resumeSessionFile != null
193
+ ? this.resumeModel
194
+ : (cached.activeModel ?? undefined);
195
+ this.resumeSessionFile = null;
196
+ this.resumeCwd = undefined;
197
+ this.resumeModel = undefined;
198
+ if (rejoinFile) {
199
+ // Keep the cached conversation on screen but mark it resyncing so the
200
+ // "Reconnecting and syncing session..." banner shows and sending is
201
+ // blocked until fresh history lands. resyncing is cleared by
202
+ // message_history (or an error/conflict) via the reducer.
203
+ this.stateStore.update(s => (s.resyncing ? s : { ...s, resyncing: true }));
204
+ this.send({ type: 'session_load', sessionFile: rejoinFile, cwd: rejoinCwd, model: rejoinModel });
162
205
  this.armLoadWatchdog();
163
206
  }
164
207
  else {
@@ -193,6 +236,12 @@ export class WhereverClient {
193
236
  // Never leave a session-load spinner stuck if the socket drops mid-load.
194
237
  loadingSession: false,
195
238
  creatingSession: false,
239
+ // If we still hold an active session, the drop is an unsolicited one on a
240
+ // live conversation: mark it resyncing NOW (during the reconnect backoff)
241
+ // so the user immediately sees "Reconnecting..." instead of a frozen view
242
+ // with a stale tool call and a disabled Abort. onOpen re-attaches and the
243
+ // reducer clears resyncing when fresh history lands.
244
+ resyncing: s.activeSessionFile ? true : s.resyncing,
196
245
  }));
197
246
  this.scheduleReconnect();
198
247
  };
@@ -230,6 +279,11 @@ export class WhereverClient {
230
279
  this.agentEndTimeout = null;
231
280
  }
232
281
  this.stopLivenessWatchdog();
282
+ // The load/create affordances belong to the socket we are tearing down. If
283
+ // left armed they would later fire against a fresh (re)connected session's
284
+ // state, so cancel them here.
285
+ this.clearLoadWatchdog();
286
+ this.clearCreateWatchdog();
233
287
  if (this.ws) {
234
288
  try {
235
289
  if (typeof this.ws.removeAllListeners === 'function') {
@@ -241,12 +295,36 @@ export class WhereverClient {
241
295
  this.ws = null;
242
296
  }
243
297
  if (resetState) {
298
+ // Full teardown wipes the store, so no unconfirmed message survives in it;
299
+ // clear their watchdogs to avoid firing against a fresh store. The
300
+ // persisted-pending localStorage entries intentionally REMAIN so a later
301
+ // load can still recover them.
302
+ for (const t of this.confirmTimers.values())
303
+ clearTimeout(t);
304
+ this.confirmTimers.clear();
244
305
  this.stateStore.set({
245
306
  ...defaultState,
246
307
  hideThinking: !!this.config.hideThinking,
247
308
  hideTools: !!this.config.hideTools,
248
309
  });
249
310
  }
311
+ else {
312
+ // Preserve-cache teardown (suspend / resume's pre-connect close). The
313
+ // socket is gone, so the store MUST reflect disconnected: leaving a stale
314
+ // connected:true made resume() early-return (its `if (connected) return`
315
+ // guard), so the real reconnect fell through to a plain connect() that did
316
+ // NOT preserve the session, which is what flashed the search / new-session
317
+ // empty-state on tab return. Clearing connected here (without wiping the
318
+ // cached session/messages) lets resume() actually rejoin in place, and
319
+ // never leaves the blocking load/create overlays up on a dead socket.
320
+ this.stateStore.update(s => ({
321
+ ...s,
322
+ connected: false,
323
+ connecting: false,
324
+ loadingSession: false,
325
+ creatingSession: false,
326
+ }));
327
+ }
250
328
  }
251
329
  // Suspend the connection without tearing down the cached session state. Used
252
330
  // when the tab is backgrounded: closing the WebSocket improves bfcache
@@ -278,7 +356,11 @@ export class WhereverClient {
278
356
  const s = get(this.stateStore);
279
357
  if (s.connected || s.connecting)
280
358
  return;
281
- if (this.resumeSessionFile) {
359
+ // Rejoin whatever session we still hold: an explicit suspend() record OR the
360
+ // cached active session from an unsolicited drop. In BOTH cases onOpen
361
+ // re-issues session_load, so mark resyncing here to show the affordance and
362
+ // block sending until fresh history lands.
363
+ if (this.resumeSessionFile || s.activeSessionFile) {
282
364
  this.stateStore.update(st => ({ ...st, resyncing: true }));
283
365
  // Arm here too: if the socket never opens, onOpen never runs and the
284
366
  // resync affordance would otherwise hang. onClose also clears it, but the
@@ -294,6 +376,13 @@ export class WhereverClient {
294
376
  hasSuspendedSession() {
295
377
  return this.resumeSessionFile !== null;
296
378
  }
379
+ // True when the store still holds an active session to rejoin in place -- from
380
+ // an explicit suspend() OR an unsolicited drop that left activeSessionFile set.
381
+ // Callers use this to prefer the preserve-cache resume() path over a fresh,
382
+ // session-wiping connect() when returning to a still-live conversation.
383
+ hasActiveSession() {
384
+ return this.resumeSessionFile !== null || get(this.stateStore).activeSessionFile !== null;
385
+ }
297
386
  // Start (or restart) the stale-socket watchdog + keepalive for the current
298
387
  // socket. A half-open connection emits no 'close'/'error', so without this the
299
388
  // existing reconnect logic would never fire and the agent would hang forever.
@@ -407,6 +496,35 @@ export class WhereverClient {
407
496
  this.loadWatchdog = null;
408
497
  }
409
498
  }
499
+ // Arm (or re-arm) the create watchdog. Called when session_new is issued so an
500
+ // unanswered create can never strand the blocking "Creating session..."
501
+ // overlay. On expiry we clear creatingSession and surface a recoverable error
502
+ // instead of an endless spin that only a reload escapes.
503
+ armCreateWatchdog() {
504
+ this.clearCreateWatchdog();
505
+ this.createWatchdog = setTimeout(() => {
506
+ this.createWatchdog = null;
507
+ const s = get(this.stateStore);
508
+ if (!s.creatingSession)
509
+ return;
510
+ console.warn('[wherever] session create timed out; clearing creating state');
511
+ this.stateStore.update(st => ({
512
+ ...st,
513
+ creatingSession: false,
514
+ sessionError: st.sessionError ||
515
+ 'Creating the session timed out. It may still be starting on the server; check the sidebar or reload.',
516
+ }));
517
+ }, WhereverClient.CREATE_WATCHDOG_MS);
518
+ }
519
+ // Clear the create watchdog. Called at every point a create resolves
520
+ // (session_created, session_error, session_conflict, session_interrupted,
521
+ // disconnect, leave).
522
+ clearCreateWatchdog() {
523
+ if (this.createWatchdog) {
524
+ clearTimeout(this.createWatchdog);
525
+ this.createWatchdog = null;
526
+ }
527
+ }
410
528
  scheduleReconnect() {
411
529
  if (this.reconnectTimer)
412
530
  return;
@@ -414,12 +532,20 @@ export class WhereverClient {
414
532
  this.reconnectTimer = null;
415
533
  this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
416
534
  console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
535
+ // If we still hold an active session, PRESERVE the cached store across the
536
+ // reconnect. A default connect() resets to a blank store, which wiped
537
+ // activeSessionFile BEFORE onOpen could re-attach to it -- that is what
538
+ // silently detached the frontend from a still-running session (frozen
539
+ // conversation, no re-follow, not even a "connecting"/"loading" hint).
540
+ // Preserving the store keeps the conversation on screen and lets onOpen
541
+ // re-issue session_load from activeSessionFile.
542
+ const preserve = !!get(this.stateStore).activeSessionFile;
417
543
  this.stateStore.update(s => ({
418
544
  ...s,
419
545
  connecting: true,
420
546
  error: 'Reconnecting...',
421
547
  }));
422
- this.connect();
548
+ this.connect(undefined, preserve);
423
549
  }, this.reconnectDelay);
424
550
  }
425
551
  handleMessage(msg) {
@@ -443,6 +569,17 @@ export class WhereverClient {
443
569
  this.clearLoadWatchdog();
444
570
  break;
445
571
  }
572
+ // Any message that resolves an in-flight session_new disarms the create
573
+ // watchdog. session_created is the success path; error/conflict/interrupt end
574
+ // it too.
575
+ switch (msg.type) {
576
+ case 'session_created':
577
+ case 'session_error':
578
+ case 'session_conflict':
579
+ case 'session_interrupted':
580
+ this.clearCreateWatchdog();
581
+ break;
582
+ }
446
583
  switch (msg.type) {
447
584
  case 'connected':
448
585
  this.stateStore.update((s) => ({
@@ -544,6 +681,19 @@ export class WhereverClient {
544
681
  : m);
545
682
  }
546
683
  else if (msg.content) {
684
+ // The server echoes the user's own message back once pi has appended
685
+ // it: that is the delivery CONFIRMATION for an optimistic (unconfirmed)
686
+ // echo. Confirm the matching pending message (flip delivery off, clear
687
+ // its watchdog, update the persisted-pending store) instead of adding
688
+ // a duplicate. If there was no pending match (e.g. another client sent
689
+ // it), fall back to the existing content-dedupe.
690
+ if (msg.role === 'user') {
691
+ const confirmedPending = this.confirmDeliveredByContent(msg.content);
692
+ if (confirmedPending) {
693
+ // Re-read: confirmDeliveredByContent already updated the store.
694
+ return get(this.stateStore);
695
+ }
696
+ }
547
697
  const lastUserMessage = [...newMessages]
548
698
  .reverse()
549
699
  .find((m) => m.role === 'user');
@@ -572,10 +722,22 @@ export class WhereverClient {
572
722
  this.agentEndTimeout = null;
573
723
  }
574
724
  this.agentEndTimeout = setTimeout(() => {
725
+ const now = Date.now();
575
726
  this.stateStore.update((s) => ({
576
727
  ...s,
577
728
  isStreaming: false,
578
- messages: s.messages.map((m) => m.isStreaming ? { ...m, isStreaming: false } : m),
729
+ messages: s.messages.map((m) => m.isStreaming
730
+ ? {
731
+ ...m,
732
+ isStreaming: false,
733
+ // Freeze a still-running tool's duration if it never got a
734
+ // tool_end (turn ended between steps), so "Elapsed" stops
735
+ // ticking and shows the final "Took".
736
+ endedAt: m.role === 'tool' && m.endedAt === undefined
737
+ ? now
738
+ : m.endedAt,
739
+ }
740
+ : m),
579
741
  }));
580
742
  this.agentEndTimeout = null;
581
743
  }, 300);
@@ -595,17 +757,19 @@ export class WhereverClient {
595
757
  const finalizedMessages = s.messages.map((m) => m.isStreaming && (m.role === 'assistant' || m.role === 'thinking')
596
758
  ? { ...m, isStreaming: false }
597
759
  : m);
760
+ const startedAt = Date.now();
598
761
  const newMsg = {
599
762
  id: this.generateId(),
600
763
  role: 'tool',
601
764
  content: toolArgs
602
765
  ? `$ ${msg.toolName} ${toolArgs}`
603
766
  : `$ ${msg.toolName}`,
604
- timestamp: Date.now(),
767
+ timestamp: startedAt,
605
768
  isStreaming: true,
606
769
  toolName: msg.toolName,
607
770
  toolArgs: toolArgs,
608
771
  toolOutput: '',
772
+ startedAt,
609
773
  };
610
774
  return {
611
775
  ...s,
@@ -646,6 +810,7 @@ export class WhereverClient {
646
810
  .find((m) => m.role === 'tool' &&
647
811
  m.toolName === msg.toolName &&
648
812
  !m.content.startsWith('Tool error:'));
813
+ const endedAt = Date.now();
649
814
  if (toolMsg) {
650
815
  const errorPrefix = msg.isError ? 'Error: ' : '';
651
816
  return {
@@ -657,6 +822,7 @@ export class WhereverClient {
657
822
  isStreaming: false,
658
823
  isError: msg.isError,
659
824
  toolOutput: result,
825
+ endedAt,
660
826
  }
661
827
  : m),
662
828
  };
@@ -669,12 +835,13 @@ export class WhereverClient {
669
835
  id: this.generateId(),
670
836
  role: 'tool',
671
837
  content,
672
- timestamp: Date.now(),
838
+ timestamp: endedAt,
673
839
  isStreaming: false,
674
840
  toolName: msg.toolName,
675
841
  toolArgs: '',
676
842
  toolOutput: result,
677
843
  isError: msg.isError,
844
+ endedAt,
678
845
  };
679
846
  return {
680
847
  ...s,
@@ -684,13 +851,23 @@ export class WhereverClient {
684
851
  });
685
852
  break;
686
853
  }
687
- case 'aborted':
854
+ case 'aborted': {
855
+ const abortedAt = Date.now();
688
856
  this.stateStore.update((s) => ({
689
857
  ...s,
690
858
  isStreaming: false,
691
- messages: s.messages.map((m) => m.isStreaming ? { ...m, isStreaming: false } : m),
859
+ messages: s.messages.map((m) => m.isStreaming
860
+ ? {
861
+ ...m,
862
+ isStreaming: false,
863
+ endedAt: m.role === 'tool' && m.endedAt === undefined
864
+ ? abortedAt
865
+ : m.endedAt,
866
+ }
867
+ : m),
692
868
  }));
693
869
  break;
870
+ }
694
871
  case 'session_created':
695
872
  this.stateStore.update((s) => ({
696
873
  ...s,
@@ -704,11 +881,33 @@ export class WhereverClient {
704
881
  // The server forces read-only for sessions in a configured
705
882
  // sessions.readOnly folder (observe-only fleet view).
706
883
  readOnly: msg.readOnly ?? false,
884
+ // pending -> the history is painted now but the live agent is still
885
+ // building; keep the composer disabled (agentPending) until
886
+ // session_ready. A non-pending create (new session, warm reload) is
887
+ // immediately sendable.
888
+ agentPending: msg.pending === true,
707
889
  // Initial context-usage snapshot for the new session (null if unknown;
708
890
  // live updates arrive via 'context_usage').
709
891
  contextUsage: msg.contextUsage ?? null,
710
892
  }));
711
893
  break;
894
+ case 'session_ready':
895
+ // The live agent finished building for a previously-pending load. Enable
896
+ // the composer and refresh the now-authoritative model/streaming/usage.
897
+ this.stateStore.update((s) => {
898
+ // Ignore a stale ready for a session we already switched away from.
899
+ if (msg.sessionFile && s.activeSessionFile && msg.sessionFile !== s.activeSessionFile) {
900
+ return s;
901
+ }
902
+ return {
903
+ ...s,
904
+ agentPending: false,
905
+ activeModel: msg.model ?? s.activeModel,
906
+ isStreaming: msg.isStreaming ?? s.isStreaming,
907
+ contextUsage: msg.contextUsage ?? s.contextUsage,
908
+ };
909
+ });
910
+ break;
712
911
  case 'context_usage':
713
912
  this.stateStore.update((s) => ({
714
913
  ...s,
@@ -727,6 +926,7 @@ export class WhereverClient {
727
926
  activeCwd: null,
728
927
  activeModel: null,
729
928
  loadingSession: false,
929
+ agentPending: false,
730
930
  };
731
931
  }
732
932
  return s;
@@ -740,6 +940,10 @@ export class WhereverClient {
740
940
  creatingSession: false,
741
941
  loadingSession: false,
742
942
  resyncing: false,
943
+ // A failed (cold) agent build clears pending: the session stays
944
+ // readable, but sending remains blocked (no live agent) and the error
945
+ // is surfaced. This is the degrade-to-read-only path.
946
+ agentPending: false,
743
947
  }));
744
948
  break;
745
949
  case 'session_conflict':
@@ -753,6 +957,7 @@ export class WhereverClient {
753
957
  creatingSession: false,
754
958
  loadingSession: false,
755
959
  resyncing: false,
960
+ agentPending: false,
756
961
  }));
757
962
  break;
758
963
  case 'session_interrupted':
@@ -768,16 +973,43 @@ export class WhereverClient {
768
973
  activeModel: null,
769
974
  creatingSession: false,
770
975
  loadingSession: false,
976
+ agentPending: false,
771
977
  }));
772
978
  break;
773
- case 'message_history':
979
+ case 'message_history': {
980
+ // The server transcript is authoritative for what was actually persisted.
981
+ // Reconcile it against any unconfirmed outbound messages: keep the ones
982
+ // that ARE in history (delivered), and re-surface the ones that are NOT
983
+ // as recoverable 'failed' items so a message a half-open socket swallowed
984
+ // is never silently lost across a reload/resync.
985
+ const sessionIdForPending = msg.sessionId;
986
+ // Carry-over from the CURRENT store (this-tab sends still in flight) plus
987
+ // anything a PREVIOUS tab persisted before a reload.
988
+ const inFlight = get(this.stateStore).messages.filter((m) => m.role === 'user' && m.delivery !== undefined);
989
+ const persisted = this.loadPersistedPending(sessionIdForPending);
990
+ const candidates = [...persisted, ...inFlight];
774
991
  this.stateStore.update((s) => {
775
992
  const mapped = this.mapHistory(msg.messages, msg.sessionId, s.isStreaming);
776
993
  const totalCount = typeof msg.totalCount === 'number' ? msg.totalCount : mapped.length;
777
994
  const offset = typeof msg.offset === 'number' ? msg.offset : 0;
995
+ const historyContents = new Set(mapped.filter((m) => m.role === 'user').map((m) => m.content));
996
+ // Unconfirmed candidates whose content is NOT in the loaded history are
997
+ // undelivered. De-dupe by content so two identical undelivered sends do
998
+ // not multiply. Everything else the server persisted is already in
999
+ // `mapped` (confirmed).
1000
+ const seen = new Set();
1001
+ const undelivered = [];
1002
+ for (const c of candidates) {
1003
+ if (historyContents.has(c.content))
1004
+ continue;
1005
+ if (seen.has(c.content))
1006
+ continue;
1007
+ seen.add(c.content);
1008
+ undelivered.push({ ...c, sessionId: sessionIdForPending, delivery: 'failed' });
1009
+ }
778
1010
  return {
779
1011
  ...s,
780
- messages: mapped,
1012
+ messages: [...mapped, ...undelivered],
781
1013
  historyTotalCount: totalCount,
782
1014
  historyOffset: offset,
783
1015
  loadingMoreHistory: false,
@@ -785,7 +1017,13 @@ export class WhereverClient {
785
1017
  resyncing: false,
786
1018
  };
787
1019
  });
1020
+ // Clear watchdogs for anything now confirmed, and rewrite the persisted
1021
+ // store to exactly the still-undelivered set.
1022
+ for (const c of candidates)
1023
+ this.clearConfirm(c.id);
1024
+ this.persistPending(sessionIdForPending);
788
1025
  break;
1026
+ }
789
1027
  case 'message_history_prepend':
790
1028
  this.stateStore.update((s) => {
791
1029
  // Older window prepended ahead of currently-loaded messages. No
@@ -819,6 +1057,10 @@ export class WhereverClient {
819
1057
  */
820
1058
  mapHistory(rawMessages, sessionId, applyStreamingTail) {
821
1059
  const mapped = [];
1060
+ // Each pending tool_call carries its args AND its start timestamp (the ts of
1061
+ // the toolCall entry). When the matching tool_result arrives, startedAt =
1062
+ // the call ts and endedAt = the result ts, so a tool reconstructed from
1063
+ // loaded history shows the same "Took N.Ns" as a live-streamed one.
822
1064
  const pendingCalls = {};
823
1065
  for (const m of rawMessages) {
824
1066
  if (m.role === 'tool_call') {
@@ -826,13 +1068,14 @@ export class WhereverClient {
826
1068
  if (!pendingCalls[tName]) {
827
1069
  pendingCalls[tName] = [];
828
1070
  }
829
- pendingCalls[tName].push(m.content || '');
1071
+ pendingCalls[tName].push({ args: m.content || '', startedAt: m.timestamp });
830
1072
  }
831
1073
  else if (m.role === 'tool_result') {
832
1074
  const tName = m.toolName || 'unknown';
833
- const tArgs = pendingCalls[tName] && pendingCalls[tName].length > 0
1075
+ const call = pendingCalls[tName] && pendingCalls[tName].length > 0
834
1076
  ? pendingCalls[tName].shift()
835
- : '';
1077
+ : undefined;
1078
+ const tArgs = call?.args ?? '';
836
1079
  mapped.push({
837
1080
  id: this.generateId(),
838
1081
  role: 'tool',
@@ -846,6 +1089,15 @@ export class WhereverClient {
846
1089
  toolOutput: m.content,
847
1090
  isError: m.isError,
848
1091
  sessionId,
1092
+ // Duration from the matched call. Only when both timestamps are
1093
+ // finite and coherent (end >= start); otherwise leave unset so the UI
1094
+ // simply shows no duration rather than a bogus one.
1095
+ ...(call &&
1096
+ Number.isFinite(call.startedAt) &&
1097
+ Number.isFinite(m.timestamp) &&
1098
+ m.timestamp >= call.startedAt
1099
+ ? { startedAt: call.startedAt, endedAt: m.timestamp }
1100
+ : {}),
849
1101
  });
850
1102
  }
851
1103
  else {
@@ -860,20 +1112,25 @@ export class WhereverClient {
860
1112
  });
861
1113
  }
862
1114
  }
863
- for (const [tName, argsList] of Object.entries(pendingCalls)) {
864
- for (const args of argsList) {
1115
+ for (const [tName, calls] of Object.entries(pendingCalls)) {
1116
+ for (const call of calls) {
865
1117
  mapped.push({
866
1118
  id: this.generateId(),
867
1119
  role: 'tool',
868
- content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
1120
+ content: call.args ? `$ ${tName} ${call.args}` : `$ ${tName}`,
869
1121
  timestamp: mapped.length > 0
870
1122
  ? mapped[mapped.length - 1].timestamp + 1
871
1123
  : Date.now(),
872
1124
  isStreaming: applyStreamingTail,
873
1125
  toolName: tName,
874
- toolArgs: args,
1126
+ toolArgs: call.args,
875
1127
  toolOutput: '',
876
1128
  sessionId,
1129
+ // An unmatched call (no result yet). Keep its start so a still-running
1130
+ // tool in the streaming tail can tick "Elapsed"; leave endedAt unset.
1131
+ ...(Number.isFinite(call.startedAt)
1132
+ ? { startedAt: call.startedAt }
1133
+ : {}),
877
1134
  });
878
1135
  }
879
1136
  }
@@ -936,6 +1193,18 @@ export class WhereverClient {
936
1193
  const s = get(this.stateStore);
937
1194
  if (!s.sessionId)
938
1195
  return false;
1196
+ // The session's transcript is loaded but its live agent is still building
1197
+ // (cold, fast-first load). Reading is fine; sending is not possible yet, and
1198
+ // a message sent now would have no agent to receive it. Surface a clear,
1199
+ // recoverable hint and keep the text (the composer is disabled anyway, but a
1200
+ // programmatic caller could still reach here).
1201
+ if (s.agentPending) {
1202
+ this.stateStore.update((st) => ({
1203
+ ...st,
1204
+ sessionError: st.sessionError ?? 'Preparing the session agent; please wait a moment, then resend.',
1205
+ }));
1206
+ return false;
1207
+ }
939
1208
  // Guard against sending on a dead / half-open socket. getIsConnected()
940
1209
  // checks the real readyState (not the store's connected flag, which can lag
941
1210
  // a half-open socket the liveness watchdog has not reaped yet). Sending here
@@ -964,6 +1233,11 @@ export class WhereverClient {
964
1233
  }));
965
1234
  return false;
966
1235
  }
1236
+ // The frame was handed to an OPEN socket, but that is NOT proof of delivery:
1237
+ // a half-open TCP connection accepts send() (buffers locally, no throw) yet
1238
+ // the bytes never reach the server. So commit the echo as delivery:'sending'
1239
+ // (unconfirmed) and arm a watchdog + persist it, so it is recoverable on
1240
+ // reload and flips to 'failed' if the server never echoes it back.
967
1241
  const message = {
968
1242
  id: this.generateId(),
969
1243
  role: 'user',
@@ -971,14 +1245,179 @@ export class WhereverClient {
971
1245
  timestamp: Date.now(),
972
1246
  isStreaming: false,
973
1247
  sessionId: s.sessionId,
1248
+ delivery: 'sending',
974
1249
  };
975
1250
  this.stateStore.update((st) => ({
976
1251
  ...st,
977
1252
  sessionError: null,
978
1253
  messages: [...st.messages, message],
979
1254
  }));
1255
+ this.armConfirm(message.id);
1256
+ this.persistPending(s.sessionId);
980
1257
  return true;
981
1258
  }
1259
+ // ==========================================================================
1260
+ // Outbound-message delivery confirmation + recovery.
1261
+ //
1262
+ // An optimistic user echo is unconfirmed until the server echoes it back. This
1263
+ // machinery makes an unconfirmed message survive a reload and surface a retry
1264
+ // affordance instead of being silently lost when a half-open socket swallowed
1265
+ // the frame.
1266
+ // ==========================================================================
1267
+ pendingKey(sessionId) {
1268
+ return WhereverClient.PENDING_PREFIX + sessionId;
1269
+ }
1270
+ // Persist the current session's still-unconfirmed (delivery-tagged) user
1271
+ // messages so a reload can recover them. Cleared to empty when none remain.
1272
+ persistPending(sessionId) {
1273
+ if (!sessionId || typeof localStorage === 'undefined')
1274
+ return;
1275
+ const pending = get(this.stateStore).messages.filter((m) => m.role === 'user' && m.delivery !== undefined);
1276
+ try {
1277
+ if (pending.length === 0) {
1278
+ localStorage.removeItem(this.pendingKey(sessionId));
1279
+ }
1280
+ else {
1281
+ localStorage.setItem(this.pendingKey(sessionId), JSON.stringify(pending.map((m) => ({
1282
+ id: m.id,
1283
+ content: m.content,
1284
+ timestamp: m.timestamp,
1285
+ // Persist as 'failed': a reload cannot know if it ever landed, so
1286
+ // it must be presented as needs-attention, never as delivered.
1287
+ delivery: 'failed',
1288
+ }))));
1289
+ }
1290
+ }
1291
+ catch { }
1292
+ }
1293
+ // Load persisted unconfirmed messages for a session (used on load/resync to
1294
+ // re-surface anything a previous tab left in limbo).
1295
+ loadPersistedPending(sessionId) {
1296
+ if (typeof localStorage === 'undefined')
1297
+ return [];
1298
+ try {
1299
+ const raw = localStorage.getItem(this.pendingKey(sessionId));
1300
+ if (!raw)
1301
+ return [];
1302
+ const arr = JSON.parse(raw);
1303
+ if (!Array.isArray(arr))
1304
+ return [];
1305
+ return arr
1306
+ .filter((m) => m && typeof m.content === 'string')
1307
+ .map((m) => ({
1308
+ id: typeof m.id === 'string' ? m.id : this.generateId(),
1309
+ role: 'user',
1310
+ content: m.content,
1311
+ timestamp: typeof m.timestamp === 'number' ? m.timestamp : Date.now(),
1312
+ isStreaming: false,
1313
+ sessionId,
1314
+ delivery: 'failed',
1315
+ }));
1316
+ }
1317
+ catch {
1318
+ return [];
1319
+ }
1320
+ }
1321
+ armConfirm(messageId) {
1322
+ this.clearConfirm(messageId);
1323
+ if (typeof setTimeout !== 'function')
1324
+ return;
1325
+ const timer = setTimeout(() => {
1326
+ this.confirmTimers.delete(messageId);
1327
+ // Still unconfirmed after the window: mark it failed so the UI offers a
1328
+ // retry. Delivery is genuinely uncertain (a half-open socket may have
1329
+ // eaten it), so we do NOT auto-resend: that risks a duplicate. The user
1330
+ // decides.
1331
+ let sessionId = null;
1332
+ this.stateStore.update((st) => {
1333
+ const m = st.messages.find((x) => x.id === messageId);
1334
+ if (!m || m.delivery !== 'sending')
1335
+ return st;
1336
+ sessionId = st.sessionId;
1337
+ return {
1338
+ ...st,
1339
+ messages: st.messages.map((x) => x.id === messageId ? { ...x, delivery: 'failed' } : x),
1340
+ };
1341
+ });
1342
+ if (sessionId)
1343
+ this.persistPending(sessionId);
1344
+ }, WhereverClient.CONFIRM_MS);
1345
+ if (timer && typeof timer.unref === 'function') {
1346
+ timer.unref();
1347
+ }
1348
+ this.confirmTimers.set(messageId, timer);
1349
+ }
1350
+ clearConfirm(messageId) {
1351
+ const t = this.confirmTimers.get(messageId);
1352
+ if (t) {
1353
+ clearTimeout(t);
1354
+ this.confirmTimers.delete(messageId);
1355
+ }
1356
+ }
1357
+ // Mark the oldest still-unconfirmed user message with this content as
1358
+ // delivered (the server echoed it back). Content-matched because the server
1359
+ // echo carries no client message id. Returns true if one was confirmed.
1360
+ confirmDeliveredByContent(content) {
1361
+ let confirmedId = null;
1362
+ let sessionId = null;
1363
+ this.stateStore.update((st) => {
1364
+ const target = st.messages.find((m) => m.role === 'user' && m.delivery !== undefined && m.content === content);
1365
+ if (!target)
1366
+ return st;
1367
+ confirmedId = target.id;
1368
+ sessionId = st.sessionId;
1369
+ return {
1370
+ ...st,
1371
+ messages: st.messages.map((m) => m.id === target.id ? { ...m, delivery: undefined } : m),
1372
+ };
1373
+ });
1374
+ if (confirmedId) {
1375
+ this.clearConfirm(confirmedId);
1376
+ this.persistPending(sessionId);
1377
+ return true;
1378
+ }
1379
+ return false;
1380
+ }
1381
+ // Retry a failed (or sending) outbound message: re-send its frame and re-arm
1382
+ // confirmation. Returns false if it could not be handed to an OPEN socket (the
1383
+ // message stays failed/recoverable).
1384
+ resendMessage(messageId) {
1385
+ const s = get(this.stateStore);
1386
+ const m = s.messages.find((x) => x.id === messageId && x.role === 'user');
1387
+ if (!m || !s.sessionId)
1388
+ return false;
1389
+ if (!this.getIsConnected()) {
1390
+ if (!this.ws && !this.reconnectTimer)
1391
+ this.scheduleReconnect();
1392
+ return false;
1393
+ }
1394
+ const ok = this.send({ type: 'message', message: m.content, sessionId: s.sessionId });
1395
+ if (!ok)
1396
+ return false;
1397
+ this.stateStore.update((st) => ({
1398
+ ...st,
1399
+ sessionError: null,
1400
+ messages: st.messages.map((x) => x.id === messageId ? { ...x, delivery: 'sending', timestamp: Date.now() } : x),
1401
+ }));
1402
+ this.armConfirm(messageId);
1403
+ this.persistPending(s.sessionId);
1404
+ return true;
1405
+ }
1406
+ // Drop a failed outbound message the user chooses not to resend. Removes it
1407
+ // from the transcript and from the persisted-pending store.
1408
+ discardMessage(messageId) {
1409
+ let sessionId = null;
1410
+ this.clearConfirm(messageId);
1411
+ this.stateStore.update((st) => {
1412
+ sessionId = st.sessionId;
1413
+ return {
1414
+ ...st,
1415
+ messages: st.messages.filter((m) => m.id !== messageId),
1416
+ };
1417
+ });
1418
+ if (sessionId)
1419
+ this.persistPending(sessionId);
1420
+ }
982
1421
  abort() {
983
1422
  const s = get(this.stateStore);
984
1423
  if (!s.sessionId)
@@ -991,6 +1430,7 @@ export class WhereverClient {
991
1430
  conflict: null,
992
1431
  sessionError: null,
993
1432
  loadingSession: true,
1433
+ agentPending: false,
994
1434
  }));
995
1435
  this.send({ type: 'session_load', sessionFile, cwd, model });
996
1436
  this.armLoadWatchdog();
@@ -1028,12 +1468,16 @@ export class WhereverClient {
1028
1468
  sessionError: null,
1029
1469
  creatingSession: false,
1030
1470
  resyncing: false,
1471
+ agentPending: false,
1031
1472
  contextUsage: null,
1032
1473
  loadingSession: true,
1033
1474
  }));
1034
1475
  this.resumeSessionFile = null;
1035
1476
  this.resumeCwd = undefined;
1036
1477
  this.resumeModel = undefined;
1478
+ // Switching supersedes any in-flight create; disarm its watchdog so it can't
1479
+ // later fire against the newly loaded session.
1480
+ this.clearCreateWatchdog();
1037
1481
  this.send({ type: 'session_load', sessionFile, cwd, model });
1038
1482
  this.armLoadWatchdog();
1039
1483
  }
@@ -1053,11 +1497,24 @@ export class WhereverClient {
1053
1497
  createRemote,
1054
1498
  repoVisibility,
1055
1499
  });
1500
+ // Never let the blocking "Creating session..." overlay hang if the reply is
1501
+ // lost. Symmetrical with armLoadWatchdog for session_load.
1502
+ this.armCreateWatchdog();
1056
1503
  }
1057
1504
  leaveSession() {
1058
1505
  const s = get(this.stateStore);
1059
- if (!s.sessionId)
1506
+ // Leaving abandons any in-flight create too, so disarm its watchdog even when
1507
+ // there is no sessionId yet (a create that has not resolved).
1508
+ this.clearCreateWatchdog();
1509
+ if (!s.sessionId) {
1510
+ if (s.creatingSession) {
1511
+ this.stateStore.update((st) => ({
1512
+ ...st,
1513
+ creatingSession: false,
1514
+ }));
1515
+ }
1060
1516
  return;
1517
+ }
1061
1518
  this.send({ type: 'session_leave', sessionId: s.sessionId });
1062
1519
  this.stateStore.update((s) => ({
1063
1520
  ...s,
@@ -1071,6 +1528,7 @@ export class WhereverClient {
1071
1528
  creatingSession: false,
1072
1529
  loadingSession: false,
1073
1530
  resyncing: false,
1531
+ agentPending: false,
1074
1532
  contextUsage: null,
1075
1533
  }));
1076
1534
  this.clearLoadWatchdog();