@wherever-dev/client 0.2.1 → 0.3.0
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/CHANGELOG.md +59 -0
- package/dist/client.d.ts +27 -3
- package/dist/client.js +566 -16
- package/dist/client.js.map +1 -1
- package/dist/types.d.ts +9 -0
- package/package.json +11 -3
- package/src/client.ts +591 -23
- package/src/types.ts +26 -0
- package/test/agent-pending.test.ts +107 -0
- package/test/creating-session-watchdog.test.ts +82 -0
- package/test/harness.ts +97 -0
- package/test/reconnect-rejoins-session.test.ts +136 -0
- package/test/resume-keeps-session.test.ts +118 -0
package/dist/client.js
CHANGED
|
@@ -3,6 +3,9 @@ const defaultState = {
|
|
|
3
3
|
connected: false,
|
|
4
4
|
connecting: false,
|
|
5
5
|
creatingSession: false,
|
|
6
|
+
loadingSession: false,
|
|
7
|
+
resyncing: false,
|
|
8
|
+
agentPending: false,
|
|
6
9
|
error: null,
|
|
7
10
|
session: null,
|
|
8
11
|
sessionId: null,
|
|
@@ -21,6 +24,7 @@ const defaultState = {
|
|
|
21
24
|
historyTotalCount: 0,
|
|
22
25
|
historyOffset: 0,
|
|
23
26
|
loadingMoreHistory: false,
|
|
27
|
+
contextUsage: null,
|
|
24
28
|
};
|
|
25
29
|
export class WhereverClient {
|
|
26
30
|
ws = null;
|
|
@@ -28,10 +32,56 @@ export class WhereverClient {
|
|
|
28
32
|
stateStore;
|
|
29
33
|
reconnectTimer = null;
|
|
30
34
|
agentEndTimeout = null;
|
|
35
|
+
// Watchdog for an in-flight session_load. We set loadingSession/resyncing the
|
|
36
|
+
// moment a load is requested and clear them when message_history (or an
|
|
37
|
+
// error/conflict/disconnect) arrives. If none of those ever comes back (a lost
|
|
38
|
+
// reply, a server that answered for a different session, or any unforeseen
|
|
39
|
+
// edge), the "Loading session..." / "Reconnecting..." affordance would hang
|
|
40
|
+
// forever. This timer guarantees the load state always resolves: on expiry we
|
|
41
|
+
// clear the flags and surface a recoverable error instead of an endless spin.
|
|
42
|
+
loadWatchdog = null;
|
|
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;
|
|
31
56
|
reconnectAttempts = 0;
|
|
32
57
|
reconnectDelay = 2000;
|
|
33
58
|
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
|
+
livenessTimer = null;
|
|
67
|
+
heartbeatTimer = null;
|
|
68
|
+
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
|
+
static 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
|
+
static TURN_STALL_MS = 45_000;
|
|
76
|
+
// Send a keepalive well under STALE_SOCKET_MS so the pong refreshes liveness.
|
|
77
|
+
static HEARTBEAT_MS = 25_000;
|
|
34
78
|
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
|
+
resumeSessionFile = null;
|
|
83
|
+
resumeCwd;
|
|
84
|
+
resumeModel;
|
|
35
85
|
listeners = new Set();
|
|
36
86
|
pendingUploads = new Map();
|
|
37
87
|
constructor(config) {
|
|
@@ -45,7 +95,7 @@ export class WhereverClient {
|
|
|
45
95
|
hideTools: !!this.config.hideTools,
|
|
46
96
|
});
|
|
47
97
|
}
|
|
48
|
-
connect(newConfig) {
|
|
98
|
+
connect(newConfig, preserveState = false) {
|
|
49
99
|
if (newConfig) {
|
|
50
100
|
this.config = {
|
|
51
101
|
...this.config,
|
|
@@ -53,12 +103,18 @@ export class WhereverClient {
|
|
|
53
103
|
};
|
|
54
104
|
}
|
|
55
105
|
this.disconnect(false);
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
106
|
+
// preserveState keeps the cached session/messages in the store across a
|
|
107
|
+
// reconnect (resume path), so the previous conversation stays visible while
|
|
108
|
+
// we reconnect and resync. The default (fresh connect) clears to a blank
|
|
109
|
+
// store as before.
|
|
110
|
+
this.stateStore.update(s => preserveState
|
|
111
|
+
? { ...s, connecting: true, error: null }
|
|
112
|
+
: {
|
|
113
|
+
...defaultState,
|
|
114
|
+
connecting: true,
|
|
115
|
+
hideThinking: !!this.config.hideThinking,
|
|
116
|
+
hideTools: !!this.config.hideTools,
|
|
117
|
+
});
|
|
62
118
|
const protocol = this.config.secure ? "wss" : "ws";
|
|
63
119
|
const host = this.config.host.startsWith('http')
|
|
64
120
|
? this.config.host.replace(/^https?:\/\//, '')
|
|
@@ -91,19 +147,66 @@ export class WhereverClient {
|
|
|
91
147
|
const onOpen = () => {
|
|
92
148
|
if (this.ws !== currentWs)
|
|
93
149
|
return;
|
|
150
|
+
if (!this.isInitialConnect) {
|
|
151
|
+
console.info('[wherever] reconnected to relay');
|
|
152
|
+
}
|
|
94
153
|
this.reconnectAttempts = 0;
|
|
95
154
|
this.reconnectDelay = 2000;
|
|
96
155
|
this.isInitialConnect = false;
|
|
156
|
+
this.startLivenessWatchdog();
|
|
97
157
|
this.stateStore.update(s => ({
|
|
98
158
|
...s,
|
|
99
159
|
connected: true,
|
|
100
160
|
connecting: false,
|
|
101
161
|
error: null
|
|
102
162
|
}));
|
|
163
|
+
// Resume path: rejoin the previously-active session so its history is
|
|
164
|
+
// resynced in place. resyncing stays true until message_history (or an
|
|
165
|
+
// error/conflict) arrives, keeping the "reconnecting" affordance up and
|
|
166
|
+
// input blocked without dropping the cached messages.
|
|
167
|
+
//
|
|
168
|
+
// Re-attachment is REQUIRED on every reconnect that still holds a session,
|
|
169
|
+
// not just the suspend/resume path. The server is stateless per socket:
|
|
170
|
+
// each new connection starts attached to NO session (the old socket's
|
|
171
|
+
// close removed this client from the pool). If we do not re-issue
|
|
172
|
+
// session_load here, the relay is connected but the session stream is
|
|
173
|
+
// dead, so the UI shows a frozen conversation (a stale tool call as the
|
|
174
|
+
// last message, Abort disabled) while the agent keeps running headless.
|
|
175
|
+
// Two sources for what to rejoin:
|
|
176
|
+
// 1. resumeSessionFile -> explicit suspend()/resume() (tab background).
|
|
177
|
+
// 2. the store's activeSessionFile -> an UNSOLICITED drop (network
|
|
178
|
+
// blip, tab switch, laptop sleep, half-open reap) where suspend()
|
|
179
|
+
// never ran. This is the case that used to silently freeze.
|
|
180
|
+
const cached = get(this.stateStore);
|
|
181
|
+
const rejoinFile = this.resumeSessionFile ?? cached.activeSessionFile;
|
|
182
|
+
const rejoinCwd = this.resumeSessionFile != null
|
|
183
|
+
? this.resumeCwd
|
|
184
|
+
: (cached.activeCwd ?? undefined);
|
|
185
|
+
const rejoinModel = this.resumeSessionFile != null
|
|
186
|
+
? this.resumeModel
|
|
187
|
+
: (cached.activeModel ?? undefined);
|
|
188
|
+
this.resumeSessionFile = null;
|
|
189
|
+
this.resumeCwd = undefined;
|
|
190
|
+
this.resumeModel = undefined;
|
|
191
|
+
if (rejoinFile) {
|
|
192
|
+
// Keep the cached conversation on screen but mark it resyncing so the
|
|
193
|
+
// "Reconnecting and syncing session..." banner shows and sending is
|
|
194
|
+
// blocked until fresh history lands. resyncing is cleared by
|
|
195
|
+
// message_history (or an error/conflict) via the reducer.
|
|
196
|
+
this.stateStore.update(s => (s.resyncing ? s : { ...s, resyncing: true }));
|
|
197
|
+
this.send({ type: 'session_load', sessionFile: rejoinFile, cwd: rejoinCwd, model: rejoinModel });
|
|
198
|
+
this.armLoadWatchdog();
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
this.stateStore.update(s => (s.resyncing ? { ...s, resyncing: false } : s));
|
|
202
|
+
}
|
|
103
203
|
};
|
|
104
204
|
const onMessage = (event) => {
|
|
105
205
|
if (this.ws !== currentWs)
|
|
106
206
|
return;
|
|
207
|
+
// Any inbound frame (including the pong reply to our keepalive) proves the
|
|
208
|
+
// socket is alive and resets the stale-socket watchdog.
|
|
209
|
+
this.lastInboundAt = Date.now();
|
|
107
210
|
try {
|
|
108
211
|
const rawData = typeof event.data === 'string' ? event.data : event.data.toString();
|
|
109
212
|
const msg = JSON.parse(rawData);
|
|
@@ -116,11 +219,22 @@ export class WhereverClient {
|
|
|
116
219
|
const onClose = () => {
|
|
117
220
|
if (this.ws !== currentWs)
|
|
118
221
|
return;
|
|
222
|
+
this.stopLivenessWatchdog();
|
|
223
|
+
this.clearLoadWatchdog();
|
|
119
224
|
this.ws = null;
|
|
120
225
|
this.stateStore.update(s => ({
|
|
121
226
|
...s,
|
|
122
227
|
connected: false,
|
|
123
228
|
connecting: false,
|
|
229
|
+
// Never leave a session-load spinner stuck if the socket drops mid-load.
|
|
230
|
+
loadingSession: false,
|
|
231
|
+
creatingSession: false,
|
|
232
|
+
// If we still hold an active session, the drop is an unsolicited one on a
|
|
233
|
+
// live conversation: mark it resyncing NOW (during the reconnect backoff)
|
|
234
|
+
// so the user immediately sees "Reconnecting..." instead of a frozen view
|
|
235
|
+
// with a stale tool call and a disabled Abort. onOpen re-attaches and the
|
|
236
|
+
// reducer clears resyncing when fresh history lands.
|
|
237
|
+
resyncing: s.activeSessionFile ? true : s.resyncing,
|
|
124
238
|
}));
|
|
125
239
|
this.scheduleReconnect();
|
|
126
240
|
};
|
|
@@ -150,6 +264,19 @@ export class WhereverClient {
|
|
|
150
264
|
clearTimeout(this.reconnectTimer);
|
|
151
265
|
this.reconnectTimer = null;
|
|
152
266
|
}
|
|
267
|
+
// A pending agent_end clear timer belongs to the socket we are tearing down.
|
|
268
|
+
// Leaving it armed lets it fire against a freshly (re)connected session's
|
|
269
|
+
// state, so cancel it here.
|
|
270
|
+
if (this.agentEndTimeout) {
|
|
271
|
+
clearTimeout(this.agentEndTimeout);
|
|
272
|
+
this.agentEndTimeout = null;
|
|
273
|
+
}
|
|
274
|
+
this.stopLivenessWatchdog();
|
|
275
|
+
// The load/create affordances belong to the socket we are tearing down. If
|
|
276
|
+
// left armed they would later fire against a fresh (re)connected session's
|
|
277
|
+
// state, so cancel them here.
|
|
278
|
+
this.clearLoadWatchdog();
|
|
279
|
+
this.clearCreateWatchdog();
|
|
153
280
|
if (this.ws) {
|
|
154
281
|
try {
|
|
155
282
|
if (typeof this.ws.removeAllListeners === 'function') {
|
|
@@ -167,6 +294,222 @@ export class WhereverClient {
|
|
|
167
294
|
hideTools: !!this.config.hideTools,
|
|
168
295
|
});
|
|
169
296
|
}
|
|
297
|
+
else {
|
|
298
|
+
// Preserve-cache teardown (suspend / resume's pre-connect close). The
|
|
299
|
+
// socket is gone, so the store MUST reflect disconnected: leaving a stale
|
|
300
|
+
// connected:true made resume() early-return (its `if (connected) return`
|
|
301
|
+
// guard), so the real reconnect fell through to a plain connect() that did
|
|
302
|
+
// NOT preserve the session, which is what flashed the search / new-session
|
|
303
|
+
// empty-state on tab return. Clearing connected here (without wiping the
|
|
304
|
+
// cached session/messages) lets resume() actually rejoin in place, and
|
|
305
|
+
// never leaves the blocking load/create overlays up on a dead socket.
|
|
306
|
+
this.stateStore.update(s => ({
|
|
307
|
+
...s,
|
|
308
|
+
connected: false,
|
|
309
|
+
connecting: false,
|
|
310
|
+
loadingSession: false,
|
|
311
|
+
creatingSession: false,
|
|
312
|
+
}));
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
// Suspend the connection without tearing down the cached session state. Used
|
|
316
|
+
// when the tab is backgrounded: closing the WebSocket improves bfcache
|
|
317
|
+
// eligibility, but we keep messages/sessionId so returning is a cheap resync
|
|
318
|
+
// rather than a full reload. Records the active session so resume() can rejoin
|
|
319
|
+
// it. Does NOT schedule a reconnect (disconnect(false) clears that timer).
|
|
320
|
+
suspend() {
|
|
321
|
+
const s = get(this.stateStore);
|
|
322
|
+
if (s.activeSessionFile) {
|
|
323
|
+
this.resumeSessionFile = s.activeSessionFile;
|
|
324
|
+
this.resumeCwd = s.activeCwd ?? undefined;
|
|
325
|
+
this.resumeModel = s.activeModel ?? undefined;
|
|
326
|
+
}
|
|
327
|
+
// The socket producing the live stream is going away. If we carry a stale
|
|
328
|
+
// isStreaming:true across the suspend/resume gap, the composer will wrongly
|
|
329
|
+
// queue the next message as if the agent were still busy (and the queue
|
|
330
|
+
// never drains because no agent_end ever arrives on the dead socket). The
|
|
331
|
+
// authoritative value is re-established by session_created on rejoin.
|
|
332
|
+
if (s.isStreaming) {
|
|
333
|
+
this.stateStore.update(st => ({ ...st, isStreaming: false }));
|
|
334
|
+
}
|
|
335
|
+
this.disconnect(false);
|
|
336
|
+
}
|
|
337
|
+
// Resume after suspend(): reconnect while preserving the cached store, mark
|
|
338
|
+
// the session as resyncing, and let onOpen rejoin the recorded session. If
|
|
339
|
+
// there is no active session to rejoin, this is just a state-preserving
|
|
340
|
+
// reconnect.
|
|
341
|
+
resume() {
|
|
342
|
+
const s = get(this.stateStore);
|
|
343
|
+
if (s.connected || s.connecting)
|
|
344
|
+
return;
|
|
345
|
+
// Rejoin whatever session we still hold: an explicit suspend() record OR the
|
|
346
|
+
// cached active session from an unsolicited drop. In BOTH cases onOpen
|
|
347
|
+
// re-issues session_load, so mark resyncing here to show the affordance and
|
|
348
|
+
// block sending until fresh history lands.
|
|
349
|
+
if (this.resumeSessionFile || s.activeSessionFile) {
|
|
350
|
+
this.stateStore.update(st => ({ ...st, resyncing: true }));
|
|
351
|
+
// Arm here too: if the socket never opens, onOpen never runs and the
|
|
352
|
+
// resync affordance would otherwise hang. onClose also clears it, but the
|
|
353
|
+
// watchdog covers the half-open / never-opens case.
|
|
354
|
+
this.armLoadWatchdog();
|
|
355
|
+
}
|
|
356
|
+
this.connect(undefined, true);
|
|
357
|
+
}
|
|
358
|
+
// True when suspend() recorded an active session to rejoin on the next resume.
|
|
359
|
+
// Callers use this to take the resume (preserve-cache, rejoin-in-place) path
|
|
360
|
+
// only when there is actually a suspended session; otherwise a plain connect()
|
|
361
|
+
// is correct and avoids racing/latching the hash auto-join on a fresh load.
|
|
362
|
+
hasSuspendedSession() {
|
|
363
|
+
return this.resumeSessionFile !== null;
|
|
364
|
+
}
|
|
365
|
+
// True when the store still holds an active session to rejoin in place -- from
|
|
366
|
+
// an explicit suspend() OR an unsolicited drop that left activeSessionFile set.
|
|
367
|
+
// Callers use this to prefer the preserve-cache resume() path over a fresh,
|
|
368
|
+
// session-wiping connect() when returning to a still-live conversation.
|
|
369
|
+
hasActiveSession() {
|
|
370
|
+
return this.resumeSessionFile !== null || get(this.stateStore).activeSessionFile !== null;
|
|
371
|
+
}
|
|
372
|
+
// Start (or restart) the stale-socket watchdog + keepalive for the current
|
|
373
|
+
// socket. A half-open connection emits no 'close'/'error', so without this the
|
|
374
|
+
// existing reconnect logic would never fire and the agent would hang forever.
|
|
375
|
+
startLivenessWatchdog() {
|
|
376
|
+
this.stopLivenessWatchdog();
|
|
377
|
+
this.lastInboundAt = Date.now();
|
|
378
|
+
const sendBeat = () => {
|
|
379
|
+
// Keep a healthy connection warm so the pong refreshes lastInboundAt even
|
|
380
|
+
// during long, token-less model turns.
|
|
381
|
+
try {
|
|
382
|
+
this.ping();
|
|
383
|
+
}
|
|
384
|
+
catch { }
|
|
385
|
+
};
|
|
386
|
+
if (typeof setInterval === 'function') {
|
|
387
|
+
this.heartbeatTimer = setInterval(sendBeat, WhereverClient.HEARTBEAT_MS);
|
|
388
|
+
if (this.heartbeatTimer && typeof this.heartbeatTimer.unref === 'function') {
|
|
389
|
+
this.heartbeatTimer.unref();
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
const checkLiveness = () => {
|
|
393
|
+
if (!this.ws)
|
|
394
|
+
return;
|
|
395
|
+
const silentFor = Date.now() - this.lastInboundAt;
|
|
396
|
+
const streaming = get(this.stateStore).isStreaming;
|
|
397
|
+
// Per-turn stall timeout: while a turn is in flight the heartbeat pong (and,
|
|
398
|
+
// normally, tokens) should keep traffic flowing, so a shorter deadline
|
|
399
|
+
// distinguishes "model is slow" (heartbeat still arriving -> not stale) from
|
|
400
|
+
// "transport is dead" (heartbeat stopped). When idle, fall back to the
|
|
401
|
+
// generic stale-socket threshold.
|
|
402
|
+
const threshold = streaming
|
|
403
|
+
? WhereverClient.TURN_STALL_MS
|
|
404
|
+
: WhereverClient.STALE_SOCKET_MS;
|
|
405
|
+
if (silentFor < threshold)
|
|
406
|
+
return;
|
|
407
|
+
// The socket has been silent past the threshold: treat it as dead. Tearing
|
|
408
|
+
// it down forcibly is what makes a half-open connection recover, since the
|
|
409
|
+
// OS never produced a FIN/RST to trigger the normal close path.
|
|
410
|
+
console.warn(`[wherever] relay connection stale: no inbound frame for ${silentFor}ms ` +
|
|
411
|
+
`(threshold ${threshold}ms, ${streaming ? 'mid-turn' : 'idle'}); ` +
|
|
412
|
+
`tearing down dead socket and reconnecting`);
|
|
413
|
+
this.stopLivenessWatchdog();
|
|
414
|
+
const deadWs = this.ws;
|
|
415
|
+
this.ws = null;
|
|
416
|
+
try {
|
|
417
|
+
if (typeof deadWs.terminate === 'function') {
|
|
418
|
+
deadWs.terminate();
|
|
419
|
+
}
|
|
420
|
+
else if (typeof deadWs.close === 'function') {
|
|
421
|
+
deadWs.close();
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
catch { }
|
|
425
|
+
this.stateStore.update(s => ({
|
|
426
|
+
...s,
|
|
427
|
+
connected: false,
|
|
428
|
+
connecting: false,
|
|
429
|
+
loadingSession: false,
|
|
430
|
+
creatingSession: false,
|
|
431
|
+
// If a turn was in flight, surface it as a recoverable error so the UI
|
|
432
|
+
// shows "the transport stalled" rather than silently parking mid-stream.
|
|
433
|
+
sessionError: streaming
|
|
434
|
+
? 'Connection to relay stalled mid-turn; reconnecting...'
|
|
435
|
+
: s.sessionError,
|
|
436
|
+
isStreaming: false,
|
|
437
|
+
}));
|
|
438
|
+
this.scheduleReconnect();
|
|
439
|
+
};
|
|
440
|
+
if (typeof setInterval === 'function') {
|
|
441
|
+
this.livenessTimer = setInterval(checkLiveness, WhereverClient.HEARTBEAT_MS);
|
|
442
|
+
if (this.livenessTimer && typeof this.livenessTimer.unref === 'function') {
|
|
443
|
+
this.livenessTimer.unref();
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
stopLivenessWatchdog() {
|
|
448
|
+
if (this.heartbeatTimer) {
|
|
449
|
+
clearInterval(this.heartbeatTimer);
|
|
450
|
+
this.heartbeatTimer = null;
|
|
451
|
+
}
|
|
452
|
+
if (this.livenessTimer) {
|
|
453
|
+
clearInterval(this.livenessTimer);
|
|
454
|
+
this.livenessTimer = null;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
// Arm (or re-arm) the load watchdog. Called whenever a session_load is issued
|
|
458
|
+
// so an unresolved load can never strand the loading UI. Idempotent: a fresh
|
|
459
|
+
// load resets the deadline.
|
|
460
|
+
armLoadWatchdog() {
|
|
461
|
+
this.clearLoadWatchdog();
|
|
462
|
+
this.loadWatchdog = setTimeout(() => {
|
|
463
|
+
this.loadWatchdog = null;
|
|
464
|
+
const s = get(this.stateStore);
|
|
465
|
+
if (!s.loadingSession && !s.resyncing)
|
|
466
|
+
return;
|
|
467
|
+
console.warn('[wherever] session load timed out; clearing loading state');
|
|
468
|
+
this.stateStore.update(st => ({
|
|
469
|
+
...st,
|
|
470
|
+
loadingSession: false,
|
|
471
|
+
resyncing: false,
|
|
472
|
+
sessionError: st.sessionError ||
|
|
473
|
+
'Loading the session timed out. Please retry from the sidebar or reload.',
|
|
474
|
+
}));
|
|
475
|
+
}, WhereverClient.LOAD_WATCHDOG_MS);
|
|
476
|
+
}
|
|
477
|
+
// Clear the load watchdog. Called at every point the load resolves
|
|
478
|
+
// (message_history, session_error, session_conflict, disconnect, leave).
|
|
479
|
+
clearLoadWatchdog() {
|
|
480
|
+
if (this.loadWatchdog) {
|
|
481
|
+
clearTimeout(this.loadWatchdog);
|
|
482
|
+
this.loadWatchdog = null;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
// Arm (or re-arm) the create watchdog. Called when session_new is issued so an
|
|
486
|
+
// unanswered create can never strand the blocking "Creating session..."
|
|
487
|
+
// overlay. On expiry we clear creatingSession and surface a recoverable error
|
|
488
|
+
// instead of an endless spin that only a reload escapes.
|
|
489
|
+
armCreateWatchdog() {
|
|
490
|
+
this.clearCreateWatchdog();
|
|
491
|
+
this.createWatchdog = setTimeout(() => {
|
|
492
|
+
this.createWatchdog = null;
|
|
493
|
+
const s = get(this.stateStore);
|
|
494
|
+
if (!s.creatingSession)
|
|
495
|
+
return;
|
|
496
|
+
console.warn('[wherever] session create timed out; clearing creating state');
|
|
497
|
+
this.stateStore.update(st => ({
|
|
498
|
+
...st,
|
|
499
|
+
creatingSession: false,
|
|
500
|
+
sessionError: st.sessionError ||
|
|
501
|
+
'Creating the session timed out. It may still be starting on the server; check the sidebar or reload.',
|
|
502
|
+
}));
|
|
503
|
+
}, WhereverClient.CREATE_WATCHDOG_MS);
|
|
504
|
+
}
|
|
505
|
+
// Clear the create watchdog. Called at every point a create resolves
|
|
506
|
+
// (session_created, session_error, session_conflict, session_interrupted,
|
|
507
|
+
// disconnect, leave).
|
|
508
|
+
clearCreateWatchdog() {
|
|
509
|
+
if (this.createWatchdog) {
|
|
510
|
+
clearTimeout(this.createWatchdog);
|
|
511
|
+
this.createWatchdog = null;
|
|
512
|
+
}
|
|
170
513
|
}
|
|
171
514
|
scheduleReconnect() {
|
|
172
515
|
if (this.reconnectTimer)
|
|
@@ -174,12 +517,21 @@ export class WhereverClient {
|
|
|
174
517
|
this.reconnectTimer = setTimeout(() => {
|
|
175
518
|
this.reconnectTimer = null;
|
|
176
519
|
this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
|
|
520
|
+
console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
|
|
521
|
+
// If we still hold an active session, PRESERVE the cached store across the
|
|
522
|
+
// reconnect. A default connect() resets to a blank store, which wiped
|
|
523
|
+
// activeSessionFile BEFORE onOpen could re-attach to it -- that is what
|
|
524
|
+
// silently detached the frontend from a still-running session (frozen
|
|
525
|
+
// conversation, no re-follow, not even a "connecting"/"loading" hint).
|
|
526
|
+
// Preserving the store keeps the conversation on screen and lets onOpen
|
|
527
|
+
// re-issue session_load from activeSessionFile.
|
|
528
|
+
const preserve = !!get(this.stateStore).activeSessionFile;
|
|
177
529
|
this.stateStore.update(s => ({
|
|
178
530
|
...s,
|
|
179
531
|
connecting: true,
|
|
180
532
|
error: 'Reconnecting...',
|
|
181
533
|
}));
|
|
182
|
-
this.connect();
|
|
534
|
+
this.connect(undefined, preserve);
|
|
183
535
|
}, this.reconnectDelay);
|
|
184
536
|
}
|
|
185
537
|
handleMessage(msg) {
|
|
@@ -191,6 +543,29 @@ export class WhereverClient {
|
|
|
191
543
|
console.error("Error in message listener:", err);
|
|
192
544
|
}
|
|
193
545
|
}
|
|
546
|
+
// Any message that resolves an in-flight session_load disarms the watchdog.
|
|
547
|
+
// session_created arrives just before message_history; message_history is the
|
|
548
|
+
// real completion, but an error/conflict/destroy/interrupt also resolves it.
|
|
549
|
+
switch (msg.type) {
|
|
550
|
+
case 'message_history':
|
|
551
|
+
case 'session_error':
|
|
552
|
+
case 'session_conflict':
|
|
553
|
+
case 'session_destroyed':
|
|
554
|
+
case 'session_interrupted':
|
|
555
|
+
this.clearLoadWatchdog();
|
|
556
|
+
break;
|
|
557
|
+
}
|
|
558
|
+
// Any message that resolves an in-flight session_new disarms the create
|
|
559
|
+
// watchdog. session_created is the success path; error/conflict/interrupt end
|
|
560
|
+
// it too.
|
|
561
|
+
switch (msg.type) {
|
|
562
|
+
case 'session_created':
|
|
563
|
+
case 'session_error':
|
|
564
|
+
case 'session_conflict':
|
|
565
|
+
case 'session_interrupted':
|
|
566
|
+
this.clearCreateWatchdog();
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
194
569
|
switch (msg.type) {
|
|
195
570
|
case 'connected':
|
|
196
571
|
this.stateStore.update((s) => ({
|
|
@@ -449,6 +824,40 @@ export class WhereverClient {
|
|
|
449
824
|
activeModel: msg.model,
|
|
450
825
|
isStreaming: msg.isStreaming ?? false,
|
|
451
826
|
creatingSession: false,
|
|
827
|
+
// The server forces read-only for sessions in a configured
|
|
828
|
+
// sessions.readOnly folder (observe-only fleet view).
|
|
829
|
+
readOnly: msg.readOnly ?? false,
|
|
830
|
+
// pending -> the history is painted now but the live agent is still
|
|
831
|
+
// building; keep the composer disabled (agentPending) until
|
|
832
|
+
// session_ready. A non-pending create (new session, warm reload) is
|
|
833
|
+
// immediately sendable.
|
|
834
|
+
agentPending: msg.pending === true,
|
|
835
|
+
// Initial context-usage snapshot for the new session (null if unknown;
|
|
836
|
+
// live updates arrive via 'context_usage').
|
|
837
|
+
contextUsage: msg.contextUsage ?? null,
|
|
838
|
+
}));
|
|
839
|
+
break;
|
|
840
|
+
case 'session_ready':
|
|
841
|
+
// The live agent finished building for a previously-pending load. Enable
|
|
842
|
+
// the composer and refresh the now-authoritative model/streaming/usage.
|
|
843
|
+
this.stateStore.update((s) => {
|
|
844
|
+
// Ignore a stale ready for a session we already switched away from.
|
|
845
|
+
if (msg.sessionFile && s.activeSessionFile && msg.sessionFile !== s.activeSessionFile) {
|
|
846
|
+
return s;
|
|
847
|
+
}
|
|
848
|
+
return {
|
|
849
|
+
...s,
|
|
850
|
+
agentPending: false,
|
|
851
|
+
activeModel: msg.model ?? s.activeModel,
|
|
852
|
+
isStreaming: msg.isStreaming ?? s.isStreaming,
|
|
853
|
+
contextUsage: msg.contextUsage ?? s.contextUsage,
|
|
854
|
+
};
|
|
855
|
+
});
|
|
856
|
+
break;
|
|
857
|
+
case 'context_usage':
|
|
858
|
+
this.stateStore.update((s) => ({
|
|
859
|
+
...s,
|
|
860
|
+
contextUsage: msg.contextUsage ?? null,
|
|
452
861
|
}));
|
|
453
862
|
break;
|
|
454
863
|
case 'session_destroyed':
|
|
@@ -462,6 +871,8 @@ export class WhereverClient {
|
|
|
462
871
|
activeSessionFile: null,
|
|
463
872
|
activeCwd: null,
|
|
464
873
|
activeModel: null,
|
|
874
|
+
loadingSession: false,
|
|
875
|
+
agentPending: false,
|
|
465
876
|
};
|
|
466
877
|
}
|
|
467
878
|
return s;
|
|
@@ -473,6 +884,12 @@ export class WhereverClient {
|
|
|
473
884
|
sessionError: msg.error,
|
|
474
885
|
isStreaming: false,
|
|
475
886
|
creatingSession: false,
|
|
887
|
+
loadingSession: false,
|
|
888
|
+
resyncing: false,
|
|
889
|
+
// A failed (cold) agent build clears pending: the session stays
|
|
890
|
+
// readable, but sending remains blocked (no live agent) and the error
|
|
891
|
+
// is surfaced. This is the degrade-to-read-only path.
|
|
892
|
+
agentPending: false,
|
|
476
893
|
}));
|
|
477
894
|
break;
|
|
478
895
|
case 'session_conflict':
|
|
@@ -484,6 +901,9 @@ export class WhereverClient {
|
|
|
484
901
|
conflictingCwd: msg.conflictingCwd,
|
|
485
902
|
},
|
|
486
903
|
creatingSession: false,
|
|
904
|
+
loadingSession: false,
|
|
905
|
+
resyncing: false,
|
|
906
|
+
agentPending: false,
|
|
487
907
|
}));
|
|
488
908
|
break;
|
|
489
909
|
case 'session_interrupted':
|
|
@@ -498,6 +918,8 @@ export class WhereverClient {
|
|
|
498
918
|
activeCwd: null,
|
|
499
919
|
activeModel: null,
|
|
500
920
|
creatingSession: false,
|
|
921
|
+
loadingSession: false,
|
|
922
|
+
agentPending: false,
|
|
501
923
|
}));
|
|
502
924
|
break;
|
|
503
925
|
case 'message_history':
|
|
@@ -511,6 +933,8 @@ export class WhereverClient {
|
|
|
511
933
|
historyTotalCount: totalCount,
|
|
512
934
|
historyOffset: offset,
|
|
513
935
|
loadingMoreHistory: false,
|
|
936
|
+
loadingSession: false,
|
|
937
|
+
resyncing: false,
|
|
514
938
|
};
|
|
515
939
|
});
|
|
516
940
|
break;
|
|
@@ -640,16 +1064,70 @@ export class WhereverClient {
|
|
|
640
1064
|
beforeOffset: s.historyOffset,
|
|
641
1065
|
});
|
|
642
1066
|
}
|
|
1067
|
+
// Returns true only when the frame was actually handed to an OPEN socket.
|
|
1068
|
+
// A non-OPEN (null / CONNECTING / CLOSING / half-open) socket silently
|
|
1069
|
+
// dropping the frame is what made messages vanish: they rendered locally but
|
|
1070
|
+
// never reached the server, so they were gone after a reload. Callers that
|
|
1071
|
+
// carry user intent (sendMessage) must check this and surface the failure.
|
|
643
1072
|
send(msg) {
|
|
644
1073
|
if (this.ws && this.ws.readyState === 1 /* OPEN */) {
|
|
645
|
-
|
|
1074
|
+
try {
|
|
1075
|
+
this.ws.send(JSON.stringify(msg));
|
|
1076
|
+
return true;
|
|
1077
|
+
}
|
|
1078
|
+
catch {
|
|
1079
|
+
return false;
|
|
1080
|
+
}
|
|
646
1081
|
}
|
|
1082
|
+
return false;
|
|
647
1083
|
}
|
|
1084
|
+
// Returns true only if the message actually went out over an OPEN socket.
|
|
1085
|
+
// Callers MUST use the return value to decide whether to clear the input:
|
|
1086
|
+
// clearing on a false return is what loses the user's text on a dropped send.
|
|
648
1087
|
sendMessage(text) {
|
|
649
1088
|
const s = get(this.stateStore);
|
|
650
1089
|
if (!s.sessionId)
|
|
651
|
-
return;
|
|
652
|
-
|
|
1090
|
+
return false;
|
|
1091
|
+
// The session's transcript is loaded but its live agent is still building
|
|
1092
|
+
// (cold, fast-first load). Reading is fine; sending is not possible yet, and
|
|
1093
|
+
// a message sent now would have no agent to receive it. Surface a clear,
|
|
1094
|
+
// recoverable hint and keep the text (the composer is disabled anyway, but a
|
|
1095
|
+
// programmatic caller could still reach here).
|
|
1096
|
+
if (s.agentPending) {
|
|
1097
|
+
this.stateStore.update((st) => ({
|
|
1098
|
+
...st,
|
|
1099
|
+
sessionError: st.sessionError ?? 'Preparing the session agent; please wait a moment, then resend.',
|
|
1100
|
+
}));
|
|
1101
|
+
return false;
|
|
1102
|
+
}
|
|
1103
|
+
// Guard against sending on a dead / half-open socket. getIsConnected()
|
|
1104
|
+
// checks the real readyState (not the store's connected flag, which can lag
|
|
1105
|
+
// a half-open socket the liveness watchdog has not reaped yet). Sending here
|
|
1106
|
+
// would be silently dropped, the message would appear locally, then vanish
|
|
1107
|
+
// on reload. Surface a recoverable error and make sure we are reconnecting
|
|
1108
|
+
// instead of optimistically rendering a message that never left.
|
|
1109
|
+
if (!this.getIsConnected()) {
|
|
1110
|
+
this.stateStore.update((st) => ({
|
|
1111
|
+
...st,
|
|
1112
|
+
sessionError: 'Not connected to the relay; your message was not sent. Reconnecting, then please resend.',
|
|
1113
|
+
}));
|
|
1114
|
+
if (!this.ws && !this.reconnectTimer) {
|
|
1115
|
+
this.scheduleReconnect();
|
|
1116
|
+
}
|
|
1117
|
+
return false;
|
|
1118
|
+
}
|
|
1119
|
+
// Send first; only commit the optimistic local echo + clear the error once
|
|
1120
|
+
// the frame is confirmed handed to an OPEN socket. This way a send that
|
|
1121
|
+
// fails (a narrow race between the readyState check and send) leaves no
|
|
1122
|
+
// phantom local message and keeps the input intact for the caller to retry.
|
|
1123
|
+
const ok = this.send({ type: 'message', message: text, sessionId: s.sessionId });
|
|
1124
|
+
if (!ok) {
|
|
1125
|
+
this.stateStore.update((st) => ({
|
|
1126
|
+
...st,
|
|
1127
|
+
sessionError: 'Message failed to send (connection dropped). Please resend once reconnected.',
|
|
1128
|
+
}));
|
|
1129
|
+
return false;
|
|
1130
|
+
}
|
|
653
1131
|
const message = {
|
|
654
1132
|
id: this.generateId(),
|
|
655
1133
|
role: 'user',
|
|
@@ -658,11 +1136,12 @@ export class WhereverClient {
|
|
|
658
1136
|
isStreaming: false,
|
|
659
1137
|
sessionId: s.sessionId,
|
|
660
1138
|
};
|
|
661
|
-
this.stateStore.update((
|
|
662
|
-
...
|
|
663
|
-
|
|
1139
|
+
this.stateStore.update((st) => ({
|
|
1140
|
+
...st,
|
|
1141
|
+
sessionError: null,
|
|
1142
|
+
messages: [...st.messages, message],
|
|
664
1143
|
}));
|
|
665
|
-
|
|
1144
|
+
return true;
|
|
666
1145
|
}
|
|
667
1146
|
abort() {
|
|
668
1147
|
const s = get(this.stateStore);
|
|
@@ -675,8 +1154,57 @@ export class WhereverClient {
|
|
|
675
1154
|
...s,
|
|
676
1155
|
conflict: null,
|
|
677
1156
|
sessionError: null,
|
|
1157
|
+
loadingSession: true,
|
|
1158
|
+
agentPending: false,
|
|
678
1159
|
}));
|
|
679
1160
|
this.send({ type: 'session_load', sessionFile, cwd, model });
|
|
1161
|
+
this.armLoadWatchdog();
|
|
1162
|
+
}
|
|
1163
|
+
// Switch from the currently-active session (if any) straight to another one in
|
|
1164
|
+
// a single, atomic step. Leaving + loading used to be done by the UI as two
|
|
1165
|
+
// calls separated by a 100ms setTimeout; that gap could strand the loading
|
|
1166
|
+
// state (a tap landing mid-switch, a leave whose load never fired) and leave
|
|
1167
|
+
// the "Loading session..." spinner hanging with an open sidebar. Doing both
|
|
1168
|
+
// here, synchronously, means there is never an in-between state and the
|
|
1169
|
+
// watchdog is always (re)armed for the new load, so a superseded or lost load
|
|
1170
|
+
// can never strand the UI: the latest tap always wins.
|
|
1171
|
+
switchSession(sessionFile, cwd, model) {
|
|
1172
|
+
const s = get(this.stateStore);
|
|
1173
|
+
// Tapping the already-active session is a no-op (don't tear it down just to
|
|
1174
|
+
// reload the same history).
|
|
1175
|
+
if (s.activeSessionFile === sessionFile && !s.loadingSession && !s.resyncing) {
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
if (s.sessionId) {
|
|
1179
|
+
this.send({ type: 'session_leave', sessionId: s.sessionId });
|
|
1180
|
+
}
|
|
1181
|
+
// Reset to a clean loading state for the target session in one update so the
|
|
1182
|
+
// old conversation clears immediately and the spinner reflects the new load.
|
|
1183
|
+
this.stateStore.update((st) => ({
|
|
1184
|
+
...st,
|
|
1185
|
+
messages: [],
|
|
1186
|
+
session: null,
|
|
1187
|
+
sessionId: null,
|
|
1188
|
+
activeSessionFile: null,
|
|
1189
|
+
activeCwd: null,
|
|
1190
|
+
activeModel: null,
|
|
1191
|
+
readOnly: false,
|
|
1192
|
+
conflict: null,
|
|
1193
|
+
sessionError: null,
|
|
1194
|
+
creatingSession: false,
|
|
1195
|
+
resyncing: false,
|
|
1196
|
+
agentPending: false,
|
|
1197
|
+
contextUsage: null,
|
|
1198
|
+
loadingSession: true,
|
|
1199
|
+
}));
|
|
1200
|
+
this.resumeSessionFile = null;
|
|
1201
|
+
this.resumeCwd = undefined;
|
|
1202
|
+
this.resumeModel = undefined;
|
|
1203
|
+
// Switching supersedes any in-flight create; disarm its watchdog so it can't
|
|
1204
|
+
// later fire against the newly loaded session.
|
|
1205
|
+
this.clearCreateWatchdog();
|
|
1206
|
+
this.send({ type: 'session_load', sessionFile, cwd, model });
|
|
1207
|
+
this.armLoadWatchdog();
|
|
680
1208
|
}
|
|
681
1209
|
createSession(cwd, model, gitInit, createRemote, repoVisibility) {
|
|
682
1210
|
this.stateStore.update((s) => ({
|
|
@@ -684,6 +1212,7 @@ export class WhereverClient {
|
|
|
684
1212
|
conflict: null,
|
|
685
1213
|
sessionError: null,
|
|
686
1214
|
creatingSession: true,
|
|
1215
|
+
loadingSession: false,
|
|
687
1216
|
}));
|
|
688
1217
|
this.send({
|
|
689
1218
|
type: 'session_new',
|
|
@@ -693,11 +1222,24 @@ export class WhereverClient {
|
|
|
693
1222
|
createRemote,
|
|
694
1223
|
repoVisibility,
|
|
695
1224
|
});
|
|
1225
|
+
// Never let the blocking "Creating session..." overlay hang if the reply is
|
|
1226
|
+
// lost. Symmetrical with armLoadWatchdog for session_load.
|
|
1227
|
+
this.armCreateWatchdog();
|
|
696
1228
|
}
|
|
697
1229
|
leaveSession() {
|
|
698
1230
|
const s = get(this.stateStore);
|
|
699
|
-
|
|
1231
|
+
// Leaving abandons any in-flight create too, so disarm its watchdog even when
|
|
1232
|
+
// there is no sessionId yet (a create that has not resolved).
|
|
1233
|
+
this.clearCreateWatchdog();
|
|
1234
|
+
if (!s.sessionId) {
|
|
1235
|
+
if (s.creatingSession) {
|
|
1236
|
+
this.stateStore.update((st) => ({
|
|
1237
|
+
...st,
|
|
1238
|
+
creatingSession: false,
|
|
1239
|
+
}));
|
|
1240
|
+
}
|
|
700
1241
|
return;
|
|
1242
|
+
}
|
|
701
1243
|
this.send({ type: 'session_leave', sessionId: s.sessionId });
|
|
702
1244
|
this.stateStore.update((s) => ({
|
|
703
1245
|
...s,
|
|
@@ -709,7 +1251,15 @@ export class WhereverClient {
|
|
|
709
1251
|
activeModel: null,
|
|
710
1252
|
readOnly: false,
|
|
711
1253
|
creatingSession: false,
|
|
1254
|
+
loadingSession: false,
|
|
1255
|
+
resyncing: false,
|
|
1256
|
+
agentPending: false,
|
|
1257
|
+
contextUsage: null,
|
|
712
1258
|
}));
|
|
1259
|
+
this.clearLoadWatchdog();
|
|
1260
|
+
this.resumeSessionFile = null;
|
|
1261
|
+
this.resumeCwd = undefined;
|
|
1262
|
+
this.resumeModel = undefined;
|
|
713
1263
|
}
|
|
714
1264
|
resolveConflict(action, cwd) {
|
|
715
1265
|
const s = get(this.stateStore);
|