@wherever-dev/client 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts CHANGED
@@ -15,6 +15,8 @@ const defaultState: WhereverState = {
15
15
  connected: false,
16
16
  connecting: false,
17
17
  creatingSession: false,
18
+ loadingSession: false,
19
+ resyncing: false,
18
20
  error: null,
19
21
  session: null,
20
22
  sessionId: null,
@@ -33,6 +35,7 @@ const defaultState: WhereverState = {
33
35
  historyTotalCount: 0,
34
36
  historyOffset: 0,
35
37
  loadingMoreHistory: false,
38
+ contextUsage: null,
36
39
  };
37
40
 
38
41
  export class WhereverClient {
@@ -41,10 +44,44 @@ export class WhereverClient {
41
44
  public stateStore: Writable<WhereverState>;
42
45
  private reconnectTimer: any = null;
43
46
  private agentEndTimeout: any = null;
47
+ // Watchdog for an in-flight session_load. We set loadingSession/resyncing the
48
+ // moment a load is requested and clear them when message_history (or an
49
+ // error/conflict/disconnect) arrives. If none of those ever comes back (a lost
50
+ // reply, a server that answered for a different session, or any unforeseen
51
+ // edge), the "Loading session..." / "Reconnecting..." affordance would hang
52
+ // forever. This timer guarantees the load state always resolves: on expiry we
53
+ // clear the flags and surface a recoverable error instead of an endless spin.
54
+ private loadWatchdog: any = null;
55
+ private static readonly LOAD_WATCHDOG_MS = 12_000;
44
56
  private reconnectAttempts = 0;
45
57
  private reconnectDelay = 2000;
46
58
  private maxReconnectDelay = 15000;
59
+ // Liveness watchdog: a half-open TCP socket fires neither 'close' nor 'error',
60
+ // so the existing reconnect machinery never triggers and the agent hangs
61
+ // forever (see work/observations/ws-half-open-connection-hangs-agent-no-heartbeat.md).
62
+ // We record the time of the last inbound frame and, if the socket goes silent
63
+ // for longer than STALE_SOCKET_MS, proactively tear it down and reconnect.
64
+ // A periodic app-level {type:'ping'} keeps a healthy connection refreshed even
65
+ // during long, token-less model turns.
66
+ private livenessTimer: any = null;
67
+ private heartbeatTimer: any = null;
68
+ private lastInboundAt = 0;
69
+ // > the server heartbeat (when present) and any normal token-less gap, so a
70
+ // healthy connection is never falsely reaped; short enough to self-heal fast.
71
+ private static readonly STALE_SOCKET_MS = 60_000;
72
+ // While a turn is streaming, the keepalive pong should keep traffic flowing, so
73
+ // a shorter deadline surfaces a stalled transport (vs a merely slow model)
74
+ // faster. Still > one HEARTBEAT_MS so a single healthy pong keeps it fresh.
75
+ private static readonly TURN_STALL_MS = 45_000;
76
+ // Send a keepalive well under STALE_SOCKET_MS so the pong refreshes liveness.
77
+ private static readonly HEARTBEAT_MS = 25_000;
47
78
  private isInitialConnect = true;
79
+ // When set, the next successful (re)connection should rejoin the previously
80
+ // active session instead of starting blank. Used by resume() so a backgrounded
81
+ // tab returns to its cached conversation and resyncs history in place.
82
+ private resumeSessionFile: string | null = null;
83
+ private resumeCwd?: string;
84
+ private resumeModel?: string;
48
85
  private listeners = new Set<(msg: any) => void>();
49
86
  private pendingUploads = new Map<string, {resolve: (val: any) => void, reject: (err: any) => void}>();
50
87
 
@@ -60,7 +97,7 @@ export class WhereverClient {
60
97
  });
61
98
  }
62
99
 
63
- public connect(newConfig?: Partial<WhereverClientConfig>) {
100
+ public connect(newConfig?: Partial<WhereverClientConfig>, preserveState = false) {
64
101
  if (newConfig) {
65
102
  this.config = {
66
103
  ...this.config,
@@ -70,12 +107,18 @@ export class WhereverClient {
70
107
 
71
108
  this.disconnect(false);
72
109
 
73
- this.stateStore.update(s => ({
74
- ...defaultState,
75
- connecting: true,
76
- hideThinking: !!this.config.hideThinking,
77
- hideTools: !!this.config.hideTools,
78
- }));
110
+ // preserveState keeps the cached session/messages in the store across a
111
+ // reconnect (resume path), so the previous conversation stays visible while
112
+ // we reconnect and resync. The default (fresh connect) clears to a blank
113
+ // store as before.
114
+ this.stateStore.update(s => preserveState
115
+ ? {...s, connecting: true, error: null}
116
+ : {
117
+ ...defaultState,
118
+ connecting: true,
119
+ hideThinking: !!this.config.hideThinking,
120
+ hideTools: !!this.config.hideTools,
121
+ });
79
122
 
80
123
  const protocol = this.config.secure ? "wss" : "ws";
81
124
  const host = this.config.host.startsWith('http')
@@ -112,19 +155,42 @@ export class WhereverClient {
112
155
 
113
156
  const onOpen = () => {
114
157
  if (this.ws !== currentWs) return;
158
+ if (!this.isInitialConnect) {
159
+ console.info('[wherever] reconnected to relay');
160
+ }
115
161
  this.reconnectAttempts = 0;
116
162
  this.reconnectDelay = 2000;
117
163
  this.isInitialConnect = false;
164
+ this.startLivenessWatchdog();
118
165
  this.stateStore.update(s => ({
119
166
  ...s,
120
167
  connected: true,
121
168
  connecting: false,
122
169
  error: null
123
170
  }));
171
+ // Resume path: rejoin the previously-active session so its history is
172
+ // resynced in place. resyncing stays true until message_history (or an
173
+ // error/conflict) arrives, keeping the "reconnecting" affordance up and
174
+ // 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});
183
+ this.armLoadWatchdog();
184
+ } else {
185
+ this.stateStore.update(s => (s.resyncing ? {...s, resyncing: false} : s));
186
+ }
124
187
  };
125
188
 
126
189
  const onMessage = (event: any) => {
127
190
  if (this.ws !== currentWs) return;
191
+ // Any inbound frame (including the pong reply to our keepalive) proves the
192
+ // socket is alive and resets the stale-socket watchdog.
193
+ this.lastInboundAt = Date.now();
128
194
  try {
129
195
  const rawData = typeof event.data === 'string' ? event.data : event.data.toString();
130
196
  const msg = JSON.parse(rawData);
@@ -136,11 +202,16 @@ export class WhereverClient {
136
202
 
137
203
  const onClose = () => {
138
204
  if (this.ws !== currentWs) return;
205
+ this.stopLivenessWatchdog();
206
+ this.clearLoadWatchdog();
139
207
  this.ws = null;
140
208
  this.stateStore.update(s => ({
141
209
  ...s,
142
210
  connected: false,
143
211
  connecting: false,
212
+ // Never leave a session-load spinner stuck if the socket drops mid-load.
213
+ loadingSession: false,
214
+ creatingSession: false,
144
215
  }));
145
216
  this.scheduleReconnect();
146
217
  };
@@ -171,7 +242,15 @@ export class WhereverClient {
171
242
  clearTimeout(this.reconnectTimer);
172
243
  this.reconnectTimer = null;
173
244
  }
174
-
245
+ // A pending agent_end clear timer belongs to the socket we are tearing down.
246
+ // Leaving it armed lets it fire against a freshly (re)connected session's
247
+ // state, so cancel it here.
248
+ if (this.agentEndTimeout) {
249
+ clearTimeout(this.agentEndTimeout);
250
+ this.agentEndTimeout = null;
251
+ }
252
+ this.stopLivenessWatchdog();
253
+
175
254
  if (this.ws) {
176
255
  try {
177
256
  if (typeof this.ws.removeAllListeners === 'function') {
@@ -191,12 +270,177 @@ export class WhereverClient {
191
270
  }
192
271
  }
193
272
 
273
+ // Suspend the connection without tearing down the cached session state. Used
274
+ // when the tab is backgrounded: closing the WebSocket improves bfcache
275
+ // eligibility, but we keep messages/sessionId so returning is a cheap resync
276
+ // rather than a full reload. Records the active session so resume() can rejoin
277
+ // it. Does NOT schedule a reconnect (disconnect(false) clears that timer).
278
+ public suspend() {
279
+ const s = get(this.stateStore);
280
+ if (s.activeSessionFile) {
281
+ this.resumeSessionFile = s.activeSessionFile;
282
+ this.resumeCwd = s.activeCwd ?? undefined;
283
+ this.resumeModel = s.activeModel ?? undefined;
284
+ }
285
+ // The socket producing the live stream is going away. If we carry a stale
286
+ // isStreaming:true across the suspend/resume gap, the composer will wrongly
287
+ // queue the next message as if the agent were still busy (and the queue
288
+ // never drains because no agent_end ever arrives on the dead socket). The
289
+ // authoritative value is re-established by session_created on rejoin.
290
+ if (s.isStreaming) {
291
+ this.stateStore.update(st => ({...st, isStreaming: false}));
292
+ }
293
+ this.disconnect(false);
294
+ }
295
+
296
+ // Resume after suspend(): reconnect while preserving the cached store, mark
297
+ // the session as resyncing, and let onOpen rejoin the recorded session. If
298
+ // there is no active session to rejoin, this is just a state-preserving
299
+ // reconnect.
300
+ public resume() {
301
+ const s = get(this.stateStore);
302
+ if (s.connected || s.connecting) return;
303
+ if (this.resumeSessionFile) {
304
+ this.stateStore.update(st => ({...st, resyncing: true}));
305
+ // Arm here too: if the socket never opens, onOpen never runs and the
306
+ // resync affordance would otherwise hang. onClose also clears it, but the
307
+ // watchdog covers the half-open / never-opens case.
308
+ this.armLoadWatchdog();
309
+ }
310
+ this.connect(undefined, true);
311
+ }
312
+
313
+ // True when suspend() recorded an active session to rejoin on the next resume.
314
+ // Callers use this to take the resume (preserve-cache, rejoin-in-place) path
315
+ // only when there is actually a suspended session; otherwise a plain connect()
316
+ // is correct and avoids racing/latching the hash auto-join on a fresh load.
317
+ public hasSuspendedSession(): boolean {
318
+ return this.resumeSessionFile !== null;
319
+ }
320
+
321
+ // Start (or restart) the stale-socket watchdog + keepalive for the current
322
+ // socket. A half-open connection emits no 'close'/'error', so without this the
323
+ // existing reconnect logic would never fire and the agent would hang forever.
324
+ private startLivenessWatchdog() {
325
+ this.stopLivenessWatchdog();
326
+ this.lastInboundAt = Date.now();
327
+
328
+ const sendBeat = () => {
329
+ // Keep a healthy connection warm so the pong refreshes lastInboundAt even
330
+ // during long, token-less model turns.
331
+ try {
332
+ this.ping();
333
+ } catch {}
334
+ };
335
+ if (typeof setInterval === 'function') {
336
+ this.heartbeatTimer = setInterval(sendBeat, WhereverClient.HEARTBEAT_MS);
337
+ if (this.heartbeatTimer && typeof this.heartbeatTimer.unref === 'function') {
338
+ this.heartbeatTimer.unref();
339
+ }
340
+ }
341
+
342
+ const checkLiveness = () => {
343
+ if (!this.ws) return;
344
+ const silentFor = Date.now() - this.lastInboundAt;
345
+ const streaming = get(this.stateStore).isStreaming;
346
+ // Per-turn stall timeout: while a turn is in flight the heartbeat pong (and,
347
+ // normally, tokens) should keep traffic flowing, so a shorter deadline
348
+ // distinguishes "model is slow" (heartbeat still arriving -> not stale) from
349
+ // "transport is dead" (heartbeat stopped). When idle, fall back to the
350
+ // generic stale-socket threshold.
351
+ const threshold = streaming
352
+ ? WhereverClient.TURN_STALL_MS
353
+ : WhereverClient.STALE_SOCKET_MS;
354
+ if (silentFor < threshold) return;
355
+ // The socket has been silent past the threshold: treat it as dead. Tearing
356
+ // it down forcibly is what makes a half-open connection recover, since the
357
+ // OS never produced a FIN/RST to trigger the normal close path.
358
+ console.warn(
359
+ `[wherever] relay connection stale: no inbound frame for ${silentFor}ms ` +
360
+ `(threshold ${threshold}ms, ${streaming ? 'mid-turn' : 'idle'}); ` +
361
+ `tearing down dead socket and reconnecting`,
362
+ );
363
+ this.stopLivenessWatchdog();
364
+ const deadWs = this.ws;
365
+ this.ws = null;
366
+ try {
367
+ if (typeof deadWs.terminate === 'function') {
368
+ deadWs.terminate();
369
+ } else if (typeof deadWs.close === 'function') {
370
+ deadWs.close();
371
+ }
372
+ } catch {}
373
+ this.stateStore.update(s => ({
374
+ ...s,
375
+ connected: false,
376
+ connecting: false,
377
+ loadingSession: false,
378
+ creatingSession: false,
379
+ // If a turn was in flight, surface it as a recoverable error so the UI
380
+ // shows "the transport stalled" rather than silently parking mid-stream.
381
+ sessionError: streaming
382
+ ? 'Connection to relay stalled mid-turn; reconnecting...'
383
+ : s.sessionError,
384
+ isStreaming: false,
385
+ }));
386
+ this.scheduleReconnect();
387
+ };
388
+ if (typeof setInterval === 'function') {
389
+ this.livenessTimer = setInterval(checkLiveness, WhereverClient.HEARTBEAT_MS);
390
+ if (this.livenessTimer && typeof this.livenessTimer.unref === 'function') {
391
+ this.livenessTimer.unref();
392
+ }
393
+ }
394
+ }
395
+
396
+ private stopLivenessWatchdog() {
397
+ if (this.heartbeatTimer) {
398
+ clearInterval(this.heartbeatTimer);
399
+ this.heartbeatTimer = null;
400
+ }
401
+ if (this.livenessTimer) {
402
+ clearInterval(this.livenessTimer);
403
+ this.livenessTimer = null;
404
+ }
405
+ }
406
+
407
+ // Arm (or re-arm) the load watchdog. Called whenever a session_load is issued
408
+ // so an unresolved load can never strand the loading UI. Idempotent: a fresh
409
+ // load resets the deadline.
410
+ private armLoadWatchdog() {
411
+ this.clearLoadWatchdog();
412
+ this.loadWatchdog = setTimeout(() => {
413
+ this.loadWatchdog = null;
414
+ const s = get(this.stateStore);
415
+ if (!s.loadingSession && !s.resyncing) return;
416
+ console.warn('[wherever] session load timed out; clearing loading state');
417
+ this.stateStore.update(st => ({
418
+ ...st,
419
+ loadingSession: false,
420
+ resyncing: false,
421
+ sessionError:
422
+ st.sessionError ||
423
+ 'Loading the session timed out. Please retry from the sidebar or reload.',
424
+ }));
425
+ }, WhereverClient.LOAD_WATCHDOG_MS);
426
+ }
427
+
428
+ // Clear the load watchdog. Called at every point the load resolves
429
+ // (message_history, session_error, session_conflict, disconnect, leave).
430
+ private clearLoadWatchdog() {
431
+ if (this.loadWatchdog) {
432
+ clearTimeout(this.loadWatchdog);
433
+ this.loadWatchdog = null;
434
+ }
435
+ }
436
+
194
437
  private scheduleReconnect() {
195
438
  if (this.reconnectTimer) return;
196
439
 
197
440
  this.reconnectTimer = setTimeout(() => {
198
441
  this.reconnectTimer = null;
199
442
  this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
443
+ console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
200
444
 
201
445
  this.stateStore.update(s => ({
202
446
  ...s,
@@ -217,6 +461,19 @@ export class WhereverClient {
217
461
  }
218
462
  }
219
463
 
464
+ // Any message that resolves an in-flight session_load disarms the watchdog.
465
+ // session_created arrives just before message_history; message_history is the
466
+ // real completion, but an error/conflict/destroy/interrupt also resolves it.
467
+ switch (msg.type) {
468
+ case 'message_history':
469
+ case 'session_error':
470
+ case 'session_conflict':
471
+ case 'session_destroyed':
472
+ case 'session_interrupted':
473
+ this.clearLoadWatchdog();
474
+ break;
475
+ }
476
+
220
477
  switch (msg.type) {
221
478
  case 'connected':
222
479
  this.stateStore.update((s: WhereverState) => ({
@@ -518,6 +775,19 @@ export class WhereverClient {
518
775
  activeModel: msg.model,
519
776
  isStreaming: msg.isStreaming ?? false,
520
777
  creatingSession: false,
778
+ // The server forces read-only for sessions in a configured
779
+ // sessions.readOnly folder (observe-only fleet view).
780
+ readOnly: msg.readOnly ?? false,
781
+ // Initial context-usage snapshot for the new session (null if unknown;
782
+ // live updates arrive via 'context_usage').
783
+ contextUsage: msg.contextUsage ?? null,
784
+ }));
785
+ break;
786
+
787
+ case 'context_usage':
788
+ this.stateStore.update((s: WhereverState) => ({
789
+ ...s,
790
+ contextUsage: msg.contextUsage ?? null,
521
791
  }));
522
792
  break;
523
793
 
@@ -532,6 +802,7 @@ export class WhereverClient {
532
802
  activeSessionFile: null,
533
803
  activeCwd: null,
534
804
  activeModel: null,
805
+ loadingSession: false,
535
806
  };
536
807
  }
537
808
  return s;
@@ -544,6 +815,8 @@ export class WhereverClient {
544
815
  sessionError: msg.error,
545
816
  isStreaming: false,
546
817
  creatingSession: false,
818
+ loadingSession: false,
819
+ resyncing: false,
547
820
  }));
548
821
  break;
549
822
 
@@ -556,6 +829,8 @@ export class WhereverClient {
556
829
  conflictingCwd: msg.conflictingCwd,
557
830
  },
558
831
  creatingSession: false,
832
+ loadingSession: false,
833
+ resyncing: false,
559
834
  }));
560
835
  break;
561
836
 
@@ -571,6 +846,7 @@ export class WhereverClient {
571
846
  activeCwd: null,
572
847
  activeModel: null,
573
848
  creatingSession: false,
849
+ loadingSession: false,
574
850
  }));
575
851
  break;
576
852
 
@@ -586,6 +862,8 @@ export class WhereverClient {
586
862
  historyTotalCount: totalCount,
587
863
  historyOffset: offset,
588
864
  loadingMoreHistory: false,
865
+ loadingSession: false,
866
+ resyncing: false,
589
867
  };
590
868
  });
591
869
  break;
@@ -725,18 +1003,62 @@ export class WhereverClient {
725
1003
  });
726
1004
  }
727
1005
 
728
- public send(msg: any) {
1006
+ // Returns true only when the frame was actually handed to an OPEN socket.
1007
+ // A non-OPEN (null / CONNECTING / CLOSING / half-open) socket silently
1008
+ // dropping the frame is what made messages vanish: they rendered locally but
1009
+ // never reached the server, so they were gone after a reload. Callers that
1010
+ // carry user intent (sendMessage) must check this and surface the failure.
1011
+ public send(msg: any): boolean {
729
1012
  if (this.ws && this.ws.readyState === 1 /* OPEN */) {
730
- this.ws.send(JSON.stringify(msg));
1013
+ try {
1014
+ this.ws.send(JSON.stringify(msg));
1015
+ return true;
1016
+ } catch {
1017
+ return false;
1018
+ }
731
1019
  }
1020
+ return false;
732
1021
  }
733
1022
 
734
- public sendMessage(text: string) {
1023
+ // Returns true only if the message actually went out over an OPEN socket.
1024
+ // Callers MUST use the return value to decide whether to clear the input:
1025
+ // clearing on a false return is what loses the user's text on a dropped send.
1026
+ public sendMessage(text: string): boolean {
735
1027
  const s = get(this.stateStore);
736
- if (!s.sessionId) return;
1028
+ if (!s.sessionId) return false;
1029
+
1030
+ // Guard against sending on a dead / half-open socket. getIsConnected()
1031
+ // checks the real readyState (not the store's connected flag, which can lag
1032
+ // a half-open socket the liveness watchdog has not reaped yet). Sending here
1033
+ // would be silently dropped, the message would appear locally, then vanish
1034
+ // on reload. Surface a recoverable error and make sure we are reconnecting
1035
+ // instead of optimistically rendering a message that never left.
1036
+ if (!this.getIsConnected()) {
1037
+ this.stateStore.update((st: WhereverState) => ({
1038
+ ...st,
1039
+ sessionError:
1040
+ 'Not connected to the relay; your message was not sent. Reconnecting, then please resend.',
1041
+ }));
1042
+ if (!this.ws && !this.reconnectTimer) {
1043
+ this.scheduleReconnect();
1044
+ }
1045
+ return false;
1046
+ }
1047
+
1048
+ // Send first; only commit the optimistic local echo + clear the error once
1049
+ // the frame is confirmed handed to an OPEN socket. This way a send that
1050
+ // fails (a narrow race between the readyState check and send) leaves no
1051
+ // phantom local message and keeps the input intact for the caller to retry.
1052
+ const ok = this.send({type: 'message', message: text, sessionId: s.sessionId});
1053
+ if (!ok) {
1054
+ this.stateStore.update((st: WhereverState) => ({
1055
+ ...st,
1056
+ sessionError:
1057
+ 'Message failed to send (connection dropped). Please resend once reconnected.',
1058
+ }));
1059
+ return false;
1060
+ }
737
1061
 
738
- this.stateStore.update((s: WhereverState) => ({...s, sessionError: null}));
739
-
740
1062
  const message: ChatMessage = {
741
1063
  id: this.generateId(),
742
1064
  role: 'user',
@@ -745,12 +1067,12 @@ export class WhereverClient {
745
1067
  isStreaming: false,
746
1068
  sessionId: s.sessionId,
747
1069
  };
748
- this.stateStore.update((s: WhereverState) => ({
749
- ...s,
750
- messages: [...s.messages, message],
1070
+ this.stateStore.update((st: WhereverState) => ({
1071
+ ...st,
1072
+ sessionError: null,
1073
+ messages: [...st.messages, message],
751
1074
  }));
752
-
753
- this.send({type: 'message', message: text, sessionId: s.sessionId});
1075
+ return true;
754
1076
  }
755
1077
 
756
1078
  public abort() {
@@ -764,8 +1086,53 @@ export class WhereverClient {
764
1086
  ...s,
765
1087
  conflict: null,
766
1088
  sessionError: null,
1089
+ loadingSession: true,
1090
+ }));
1091
+ this.send({type: 'session_load', sessionFile, cwd, model});
1092
+ this.armLoadWatchdog();
1093
+ }
1094
+
1095
+ // Switch from the currently-active session (if any) straight to another one in
1096
+ // a single, atomic step. Leaving + loading used to be done by the UI as two
1097
+ // calls separated by a 100ms setTimeout; that gap could strand the loading
1098
+ // state (a tap landing mid-switch, a leave whose load never fired) and leave
1099
+ // the "Loading session..." spinner hanging with an open sidebar. Doing both
1100
+ // here, synchronously, means there is never an in-between state and the
1101
+ // watchdog is always (re)armed for the new load, so a superseded or lost load
1102
+ // can never strand the UI: the latest tap always wins.
1103
+ public switchSession(sessionFile: string, cwd?: string, model?: string) {
1104
+ const s = get(this.stateStore);
1105
+ // Tapping the already-active session is a no-op (don't tear it down just to
1106
+ // reload the same history).
1107
+ if (s.activeSessionFile === sessionFile && !s.loadingSession && !s.resyncing) {
1108
+ return;
1109
+ }
1110
+ if (s.sessionId) {
1111
+ this.send({type: 'session_leave', sessionId: s.sessionId});
1112
+ }
1113
+ // Reset to a clean loading state for the target session in one update so the
1114
+ // old conversation clears immediately and the spinner reflects the new load.
1115
+ this.stateStore.update((st: WhereverState) => ({
1116
+ ...st,
1117
+ messages: [],
1118
+ session: null,
1119
+ sessionId: null,
1120
+ activeSessionFile: null,
1121
+ activeCwd: null,
1122
+ activeModel: null,
1123
+ readOnly: false,
1124
+ conflict: null,
1125
+ sessionError: null,
1126
+ creatingSession: false,
1127
+ resyncing: false,
1128
+ contextUsage: null,
1129
+ loadingSession: true,
767
1130
  }));
1131
+ this.resumeSessionFile = null;
1132
+ this.resumeCwd = undefined;
1133
+ this.resumeModel = undefined;
768
1134
  this.send({type: 'session_load', sessionFile, cwd, model});
1135
+ this.armLoadWatchdog();
769
1136
  }
770
1137
 
771
1138
  public createSession(
@@ -780,6 +1147,7 @@ export class WhereverClient {
780
1147
  conflict: null,
781
1148
  sessionError: null,
782
1149
  creatingSession: true,
1150
+ loadingSession: false,
783
1151
  }));
784
1152
  this.send({
785
1153
  type: 'session_new',
@@ -805,7 +1173,14 @@ export class WhereverClient {
805
1173
  activeModel: null,
806
1174
  readOnly: false,
807
1175
  creatingSession: false,
1176
+ loadingSession: false,
1177
+ resyncing: false,
1178
+ contextUsage: null,
808
1179
  }));
1180
+ this.clearLoadWatchdog();
1181
+ this.resumeSessionFile = null;
1182
+ this.resumeCwd = undefined;
1183
+ this.resumeModel = undefined;
809
1184
  }
810
1185
 
811
1186
  public resolveConflict(action: 'take_over' | 'read_only', cwd?: string) {
package/src/types.ts CHANGED
@@ -21,6 +21,16 @@ export interface WhereverState {
21
21
  connected: boolean;
22
22
  connecting: boolean;
23
23
  creatingSession: boolean;
24
+ // True from the moment a session_load is requested until its message_history
25
+ // (or an error/conflict) arrives. Distinguishes "opening an existing session"
26
+ // from "a brand new empty session" so the UI can show a loading state instead
27
+ // of the "New Session Started" empty state.
28
+ loadingSession: boolean;
29
+ // True while the connection was suspended (e.g. the tab was backgrounded) and
30
+ // is now reconnecting + rejoining the previously-active session. The cached
31
+ // messages remain visible; the UI shows a "reconnecting/syncing" affordance
32
+ // and blocks input until the resync completes.
33
+ resyncing: boolean;
24
34
  error: string | null;
25
35
  session: string | null;
26
36
  sessionId: string | null;
@@ -43,4 +53,13 @@ export interface WhereverState {
43
53
  historyTotalCount: number;
44
54
  historyOffset: number;
45
55
  loadingMoreHistory: boolean;
56
+ // Context-window usage for the active session (drives the "11.3% / 1.0M"
57
+ // indicator). null when unknown (no model, no usage yet, or just compacted).
58
+ contextUsage: ContextUsage | null;
59
+ }
60
+
61
+ export interface ContextUsage {
62
+ tokens: number | null;
63
+ contextWindow: number;
64
+ percent: number | null;
46
65
  }